task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: Bear and Friendship Condition Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z. For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well. Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes. Input Specification: The first line of the input contain two integers *n* and *m* (3<=≤<=*n*<=≤<=150<=000, ) — the number of members and the number of pairs of members that are friends. The *i*-th of the next *m* lines contains two distinct integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*). Members *a**i* and *b**i* are friends with each other. No pair of members will appear more than once in the input. Output Specification: If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes). Demo Input: ['4 3\n1 3\n3 4\n1 4\n', '4 4\n3 1\n2 3\n3 4\n1 2\n', '10 4\n4 3\n5 10\n8 9\n1 2\n', '3 2\n1 2\n2 3\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n', 'NO\n'] Note: The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
700
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Kyoya Ootori has a bag with *n* colored balls that are colored with *k* different colors. The colors are labeled from 1 to *k*. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color *i* before drawing the last ball of color *i*<=+<=1 for all *i* from 1 to *k*<=-<=1. Now he wonders how many different ways this can happen. Input Specification: The first line of input will have one integer *k* (1<=≤<=*k*<=≤<=1000) the number of colors. Then, *k* lines will follow. The *i*-th line will contain *c**i*, the number of balls of the *i*-th color (1<=≤<=*c**i*<=≤<=1000). The total number of balls doesn't exceed 1000. Output Specification: A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1<=000<=000<=007. Demo Input: ['3\n2\n2\n1\n', '4\n1\n2\n3\n4\n'] Demo Output: ['3\n', '1680\n'] Note: In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
701
Title: Symmetric Projections Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a set of *n* points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines. Multiset is a set where equal elements are allowed. Multiset is called symmetric, if there is a point *P* on the plane such that the multiset is [centrally symmetric](https://en.wikipedia.org/wiki/Point_reflection) in respect of point *P*. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=2000) — the number of points in the set. Each of the next *n* lines contains two integers *x**i* and *y**i* (<=-<=106<=<=≤<=<=*x**i*,<=<=*y**i*<=<=≤<=<=106) — the coordinates of the points. It is guaranteed that no two points coincide. Output Specification: If there are infinitely many good lines, print -1. Otherwise, print single integer — the number of good lines. Demo Input: ['3\n1 2\n2 1\n3 3\n', '2\n4 3\n1 2\n'] Demo Output: ['3\n', '-1\n'] Note: Picture to the first sample test: <img class="tex-graphics" src="https://espresso.codeforces.com/eedc60313be8684bd6169b8b23f0f0afd92479a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> In the second sample, any line containing the origin is good.
702
Title: Greedy Merchants Time Limit: None seconds Memory Limit: None megabytes Problem Description: In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants. The Roman Empire consisted of *n* cities numbered from 1 to *n*. It also had *m* bidirectional roads numbered from 1 to *m*. Each road connected two different cities. Any two cities were connected by no more than one road. We say that there is a path between cities *c*1 and *c*2 if there exists a finite sequence of cities *t*1,<=*t*2,<=...,<=*t**p* (*p*<=≥<=1) such that: - *t*1<==<=*c*1 - *t**p*<==<=*c*2 - for any *i* (1<=≤<=*i*<=&lt;<=*p*), cities *t**i* and *t**i*<=+<=1 are connected by a road We know that there existed a path between any two cities in the Roman Empire. In the Empire *k* merchants lived numbered from 1 to *k*. For each merchant we know a pair of numbers *s**i* and *l**i*, where *s**i* is the number of the city where this merchant's warehouse is, and *l**i* is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop. Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays *d**i* dinars of tax, where *d**i* (*d**i*<=≥<=0) is the number of roads important for the *i*-th merchant. The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help. Input Specification: The first input line contains two integers *n* and *m*, separated by a space, *n* is the number of cities, and *m* is the number of roads in the empire. The following *m* lines contain pairs of integers *a**i*, *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*), separated by a space — the numbers of cities connected by the *i*-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer *k* — the number of merchants in the empire. The following *k* lines contain pairs of integers *s**i*, *l**i* (1<=≤<=*s**i*,<=*l**i*<=≤<=*n*), separated by a space, — *s**i* is the number of the city in which the warehouse of the *i*-th merchant is located, and *l**i* is the number of the city in which the shop of the *i*-th merchant is located. The input limitations for getting 20 points are: - 1<=≤<=*n*<=≤<=200 - 1<=≤<=*m*<=≤<=200 - 1<=≤<=*k*<=≤<=200 The input limitations for getting 50 points are: - 1<=≤<=*n*<=≤<=2000 - 1<=≤<=*m*<=≤<=2000 - 1<=≤<=*k*<=≤<=2000 The input limitations for getting 100 points are: - 1<=≤<=*n*<=≤<=105 - 1<=≤<=*m*<=≤<=105 - 1<=≤<=*k*<=≤<=105 Output Specification: Print exactly *k* lines, the *i*-th line should contain a single integer *d**i* — the number of dinars that the *i*-th merchant paid. Demo Input: ['7 8\n1 2\n2 3\n3 4\n4 5\n5 6\n5 7\n3 5\n4 7\n4\n1 5\n2 4\n2 6\n4 7\n'] Demo Output: ['2\n1\n2\n0\n'] Note: The given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2.
703
Title: Parametric Circulation Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vova has recently learned what a circulaton in a graph is. Recall the definition: let $G = (V, E)$ be a directed graph. A circulation $f$ is such a collection of non-negative real numbers $f_e$ ($e \in E$), that for each vertex $v \in V$ the following conservation condition holds: $$\sum\limits_{e \in \delta^{-}(v)} f_e = \sum\limits_{e \in \delta^{+}(v)} f_e$$ where $\delta^{+}(v)$ is the set of edges that end in the vertex $v$, and $\delta^{-}(v)$ is the set of edges that start in the vertex $v$. In other words, for each vertex the total incoming flow should be equal to the total outcoming flow. Let a $lr$-circulation be such a circulation $f$ that for each edge the condition $l_e \leq f_e \leq r_e$ holds, where $l_e$ and $r_e$ for each edge $e \in E$ are two non-negative real numbers denoting the lower and upper bounds on the value of the circulation on this edge $e$. Vova can't stop thinking about applications of a new topic. Right now he thinks about the following natural question: let the graph be fixed, and each value $l_e$ and $r_e$ be a linear function of a real variable $t$: $$l_e(t) = a_e t + b_e$$ $$r_e(t) = c_e t + d_e$$ Note that $t$ is the same for all edges. Let $t$ be chosen at random from uniform distribution on a segment $[0, 1]$. What is the probability of existence of $lr$-circulation in the graph? Input Specification: The first line contains two integers $n$, $m$ ($1 \leq n \leq 1000$, $1 \leq m \leq 2000$). Each of the next $m$ lines describes edges of the graph in the format $u_e$, $v_e$, $a_e$, $b_e$, $c_e$, $d_e$ ($1 \leq u_e, v_e \leq n$, $-10^4 \leq a_e, c_e \leq 10^4$, $0 \leq b_e, d_e \leq 10^4$), where $u_e$ and $v_e$ are the startpoint and the endpoint of the edge $e$, and the remaining 4 integers describe the linear functions for the upper and lower bound of circulation. It is guaranteed that for any $t \in [0, 1]$ and for any edge $e \in E$ the following condition holds $0 \leq l_e(t) \leq r_e(t) \leq 10^4$. Output Specification: Print a single real integer — the probability of existence of $lr$-circulation in the graph, given that $t$ is chosen uniformly at random from the segment $[0, 1]$. Your answer is considered correct if its absolute difference from jury's answer is not greater than $10^{-6}$. Demo Input: ['3 3\n1 2 0 3 -4 7\n2 3 -2 5 1 6\n3 1 0 4 0 4\n'] Demo Output: ['0.25'] Note: In the first example the conservation condition allows only circulations with equal values $f_e$ for all three edges. The value of circulation on the last edge should be $4$ whatever $t$ is chosen, so the probability is $$P(4 \in [3, -4t + 7]~~\&amp;~~4 \in [-2t + 5, t + 6]) = 0.25$$
704
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Hamming distance between strings *a* and *b* of equal length (denoted by *h*(*a*,<=*b*)) is equal to the number of distinct integers *i* (1<=≤<=*i*<=≤<=|*a*|), such that *a**i*<=≠<=*b**i*, where *a**i* is the *i*-th symbol of string *a*, *b**i* is the *i*-th symbol of string *b*. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4. John Doe had a paper on which four strings of equal length *s*1, *s*2, *s*3 and *s*4 were written. Each string *s**i* consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs. Help John restore the strings; find some four strings *s*'1, *s*'2, *s*'3,<=*s*'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set *s*'*i* must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. Input Specification: The first line contains space-separated integers *h*(*s*1,<=*s*2), *h*(*s*1,<=*s*3), *h*(*s*1,<=*s*4). The second line contains space-separated integers *h*(*s*2,<=*s*3) and *h*(*s*2,<=*s*4). The third line contains the single integer *h*(*s*3,<=*s*4). All given integers *h*(*s**i*,<=*s**j*) are non-negative and do not exceed 105. It is guaranteed that at least one number *h*(*s**i*,<=*s**j*) is positive. Output Specification: Print -1 if there's no suitable set of strings. Otherwise print on the first line number *len* — the length of each string. On the *i*-th of the next four lines print string *s*'*i*. If there are multiple sets with the minimum length of the strings, print any of them. Demo Input: ['4 4 4\n4 4\n4\n'] Demo Output: ['6\naaaabb\naabbaa\nbbaaaa\nbbbbbb\n'] Note: none
705
Title: Scissors Time Limit: None seconds Memory Limit: None megabytes Problem Description: Jenya has recently acquired quite a useful tool — *k*-scissors for cutting strings. They are generally used for cutting out two non-intersecting substrings of length *k* from an arbitrary string *s* (its length should be at least 2·*k* in order to perform this operation) and concatenating them afterwards (preserving the initial order). For example, with the help of 2-scissors you can cut *ab* and *de* out of *abcde* and concatenate them into *abde*, but not *ab* and *bc* since they're intersecting. It's a nice idea to test this tool before using it in practice. After looking through the papers, Jenya came up with two strings *s* and *t*. His question is whether it is possible to apply his scissors to string *s* such that the resulting concatenation contains *t* as a substring? Input Specification: The first line contains three integers *n*, *m*, *k* (2<=≤<=*m*<=≤<=2·*k*<=≤<=*n*<=≤<=5·105) — length of *s*, length of *t* and the aforementioned scissors' parameter correspondingly. The next two lines feature *s* and *t* consisting of lowercase latin letters. Output Specification: If there is no answer, print «No». Otherwise print «Yes» and two integers *L* and *R* denoting the indexes where cutted substrings start (1-indexed). If there are several possible answers, output any. Demo Input: ['7 4 3\nbaabaab\naaaa\n', '6 3 2\ncbcbcb\nbcc\n', '7 5 3\naabbaaa\naaaaa\n'] Demo Output: ['Yes\n1 5\n', 'Yes\n2 5\n', 'No\n'] Note: In the first sample case you can cut out two substrings starting at 1 and 5. The resulting string baaaab contains aaaa as a substring. In the second sample case the resulting string is bccb.
706
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Вася купил стол, у которого *n* ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2*n* частей возможно составить *n* ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2*n* частей в произвольном порядке. Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2*n* части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть. Input Specification: В первой строке задано число *n* (1<=≤<=*n*<=≤<=1000) — количество ножек у стола, купленного Васей. Во второй строке следует последовательность из 2*n* целых положительных чисел *a*1,<=*a*2,<=...,<=*a*2*n* (1<=≤<=*a**i*<=≤<=100<=000) — длины частей ножек стола в произвольном порядке. Output Specification: Выведите *n* строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать *n* ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них. Demo Input: ['3\n1 3 2 4 5 3\n', '3\n1 1 1 2 2 2\n'] Demo Output: ['1 5\n2 4\n3 3\n', '1 2\n2 1\n1 2\n'] Note: none
707
Title: Vasya and Polynomial Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function *P*(*x*)<==<=*a*0<=+<=*a*1*x*1<=+<=...<=+<=*a**n**x**n*. Numbers *a**i* are called coefficients of a polynomial, non-negative integer *n* is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials *P*(*x*) exist with integer non-negative coefficients so that , and , where and *b* are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input Specification: The input contains three integer positive numbers no greater than 1018. Output Specification: If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109<=+<=7. Demo Input: ['2 2 2\n', '2 3 3\n'] Demo Output: ['2\n', '1\n'] Note: none
708
Title: Ksusha and Square Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be? A pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points *p*,<=*q* (*p*<=≠<=*q*) and *q*,<=*p* are considered the same. Help Ksusha! Count the required expectation. Input Specification: The first line contains integer *n* (3<=≤<=*n*<=≤<=105) — the number of vertices of Ksusha's convex polygon. Next *n* lines contain the coordinates of the polygon vertices in clockwise or counterclockwise order. The *i*-th line contains integers *x**i*,<=*y**i* (|*x**i*|,<=|*y**i*|<=≤<=106) — the coordinates of the vertex that goes *i*-th in that order. Output Specification: Print a single real number — the required expected area. The answer will be considered correct if its absolute and relative error doesn't exceed 10<=-<=6. Demo Input: ['3\n0 0\n5 5\n5 0\n', '4\n-1 3\n4 5\n6 2\n3 -5\n', '3\n17 136\n859 937\n16 641\n'] Demo Output: ['4.6666666667\n', '8.1583333333\n', '66811.3704155169\n'] Note: none
709
Title: Bombing Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used. The enemy has *N* strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least *K* important objects of the enemy. The bombing impact point is already determined and has coordinates of [*X*0; *Y*0]. The nuclear warhead is marked by the estimated impact radius *R*<=≥<=0. All the buildings that are located closer than *R* to the bombing epicentre will be destroyed. All the buildings that are located further than *R* from the epicentre, can also be deactivated with some degree of probability. Let's assume that *D* is the distance between a building and the epicentre. This building's deactivation probability *P*(*D*,<=*R*) is calculated according to the following formula: If the estimated impact radius of the warhead is equal to zero, then all the buildings located in the impact point will be completely demolished and all the rest of important objects will not be damaged. The commanding officers want the probability of failing the task to be no more than ε. Nuclear warheads are too expensive a luxury, that's why you have to minimise the estimated impact radius of the warhead. Input Specification: The first line contains an integer *N* which represents the number of the enemy's objects (1<=≤<=*N*<=≤<=100). The second line contains two integers: *K* is the required number of deactivated objects, and ε is the maximally permitted probability of not completing the task, given in per mils (1<=≤<=*K*<=≤<=*N*, 1<=≤<=ε<=≤<=999). The third line contains *X*0 and *Y*0 which are the coordinates of the strike impact point. The next *N* lines contain two numbers *X**i* and *Y**i* each which are the coordinates of every strategically important object. All the coordinates are integer, their absolute values do not exceed 1000. Let us remind you that there are a thousand per mils in unity (number one). There can be several objects in one point. Output Specification: Print the sought estimated impact radius of the warhead. The absolute or relative measure of the inaccuracy of your answer should not exceed 10<=-<=6. Demo Input: ['1\n1 500\n5 5\n1 2\n', '5\n3 100\n0 0\n3 4\n60 70\n100 100\n10 10\n5 12\n'] Demo Output: ['3.84257761518762740\n', '13.45126176453737600\n'] Note: none
710
Title: Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's consider an *n*<=×<=*n* square matrix, consisting of digits one and zero. We'll consider a matrix good, if it meets the following condition: in each row of the matrix all ones go in one group. That is, each row of the matrix looks like that 00...0011...1100...00 (or simply consists of zeroes if it has no ones). You are given matrix *a* of size *n*<=×<=*n*, consisting of zeroes and ones. Your task is to determine whether you can get a good matrix *b* from it by rearranging the columns or not. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=500) — the size of matrix *a*. Each of *n* following lines contains *n* characters "0" and "1" — matrix *a*. Note that the characters are written without separators. Output Specification: Print "YES" in the first line, if you can rearrange the matrix columns so as to get a good matrix *b*. In the next *n* lines print the good matrix *b*. If there are multiple answers, you are allowed to print any of them. If it is impossible to get a good matrix, print "NO". Demo Input: ['6\n100010\n110110\n011001\n010010\n000100\n011001\n', '3\n110\n101\n011\n'] Demo Output: ['YES\n011000\n111100\n000111\n001100\n100000\n000111\n', 'NO\n'] Note: none
711
Title: Fox Dividing Cheese Time Limit: None seconds Memory Limit: None megabytes Problem Description: Two little greedy bears have found two pieces of cheese in the forest of weight *a* and *b* grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal". The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal. Input Specification: The first line contains two space-separated integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=109). Output Specification: If the fox is lying to the little bears and it is impossible to make the pieces equal, print -1. Otherwise, print the required minimum number of operations. If the pieces of the cheese are initially equal, the required number is 0. Demo Input: ['15 20\n', '14 8\n', '6 6\n'] Demo Output: ['3\n', '-1\n', '0\n'] Note: none
712
Title: Bear and Drawing Time Limit: None seconds Memory Limit: None megabytes Problem Description: Limak is a little bear who learns to draw. People usually start with houses, fences and flowers but why would bears do it? Limak lives in the forest and he decides to draw a tree. Recall that tree is a connected graph consisting of *n* vertices and *n*<=-<=1 edges. Limak chose a tree with *n* vertices. He has infinite strip of paper with two parallel rows of dots. Little bear wants to assign vertices of a tree to some *n* distinct dots on a paper so that edges would intersect only at their endpoints — drawn tree must be planar. Below you can see one of correct drawings for the first sample test. Is it possible for Limak to draw chosen tree? Input Specification: The first line contains single integer *n* (1<=≤<=*n*<=≤<=105). Next *n*<=-<=1 lines contain description of a tree. *i*-th of them contains two space-separated integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*) denoting an edge between vertices *a**i* and *b**i*. It's guaranteed that given description forms a tree. Output Specification: Print "Yes" (without the quotes) if Limak can draw chosen tree. Otherwise, print "No" (without the quotes). Demo Input: ['8\n1 2\n1 3\n1 6\n6 4\n6 7\n6 5\n7 8\n', '13\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9\n3 10\n4 11\n4 12\n4 13\n'] Demo Output: ['Yes\n', 'No\n'] Note: none
713
Title: Nikita and string Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b". Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? Input Specification: The first line contains a non-empty string of length not greater than 5<=000 containing only lowercase English letters "a" and "b". Output Specification: Print a single integer — the maximum possible size of beautiful string Nikita can get. Demo Input: ['abba\n', 'bab\n'] Demo Output: ['4', '2'] Note: It the first sample the string is already beautiful. In the second sample he needs to delete one of "b" to make it beautiful.
714
Title: Mahmoud and Ehab and yet another xor task Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ehab has an array *a* of *n* integers. He likes the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud *q* queries. In each of them, he gave Mahmoud 2 integers *l* and *x*, and asked him to find the number of subsequences of the first *l* elements of the array such that their bitwise-xor sum is *x*. Can you help Mahmoud answer the queries? A subsequence can contain elements that are not neighboring. Input Specification: The first line contains integers *n* and *q* (1<=≤<=*n*,<=*q*<=≤<=105), the number of elements in the array and the number of queries. The next line contains *n* integers *a*1, *a*2, ..., *a**n* (0<=≤<=*a**i*<=&lt;<=220), the elements of the array. The next *q* lines, each contains integers *l* and *x* (1<=≤<=*l*<=≤<=*n*, 0<=≤<=*x*<=&lt;<=220), representing the queries. Output Specification: For each query, output its answer modulo 109<=+<=7 in a newline. Demo Input: ['5 5\n0 1 2 3 4\n4 3\n2 0\n3 7\n5 7\n5 8\n', '3 2\n1 1 1\n3 1\n2 0\n'] Demo Output: ['4\n2\n0\n4\n0\n', '4\n2\n'] Note: The bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself.
715
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Limak is a big polar bear. He prepared *n* problems for an algorithmic contest. The *i*-th problem has initial score *p**i*. Also, testers said that it takes *t**i* minutes to solve the *i*-th problem. Problems aren't necessarily sorted by difficulty and maybe harder problems have smaller initial score but it's too late to change it — Limak has already announced initial scores for problems. Though it's still possible to adjust the speed of losing points, denoted by *c* in this statement. Let *T* denote the total number of minutes needed to solve all problems (so, *T*<==<=*t*1<=+<=*t*2<=+<=...<=+<=*t**n*). The contest will last exactly *T* minutes. So it's just enough to solve all problems. Points given for solving a problem decrease linearly. Solving the *i*-th problem after *x* minutes gives exactly points, where is some real constant that Limak must choose. Let's assume that *c* is fixed. During a contest a participant chooses some order in which he or she solves problems. There are *n*! possible orders and each of them gives some total number of points, not necessarily integer. We say that an order is optimal if it gives the maximum number of points. In other words, the total number of points given by this order is greater or equal than the number of points given by any other order. It's obvious that there is at least one optimal order. However, there may be more than one optimal order. Limak assumes that every participant will properly estimate *t**i* at the very beginning and will choose some optimal order. He also assumes that testers correctly predicted time needed to solve each problem. For two distinct problems *i* and *j* such that *p**i*<=&lt;<=*p**j* Limak wouldn't be happy to see a participant with strictly more points for problem *i* than for problem *j*. He calls such a situation a paradox. It's not hard to prove that there will be no paradox for *c*<==<=0. The situation may be worse for bigger *c*. What is the maximum real value *c* (remember that ) for which there is no paradox possible, that is, there will be no paradox for any optimal order of solving problems? It can be proved that the answer (the maximum *c* as described) always exists. Input Specification: The first line contains one integer *n* (2<=≤<=*n*<=≤<=150<=000) — the number of problems. The second line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=108) — initial scores. The third line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=108) where *t**i* is the number of minutes needed to solve the *i*-th problem. Output Specification: Print one real value on a single line — the maximum value of *c* that and there is no optimal order with a paradox. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6. Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct if . Demo Input: ['3\n4 3 10\n1 1 8\n', '4\n7 20 15 10\n7 20 15 10\n', '2\n10 20\n10 1\n'] Demo Output: ['0.62500000000\n', '0.31901840491\n', '1.00000000000\n'] Note: In the first sample, there are 3 problems. The first is (4, 1) (initial score is 4 and required time is 1 minute), the second problem is (3, 1) and the third one is (10, 8). The total time is *T* = 1 + 1 + 8 = 10. Let's show that there is a paradox for *c* = 0.7. Solving problems in order 1, 2, 3 turns out to give the best total score, equal to the sum of: 1. solved 1 minute after the start: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e300b226dba2622235193889de3334147547cfcb.png" style="max-width: 100.0%;max-height: 100.0%;"/> 1. solved 2 minutes after the start: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/899352b92886f248a9c8e31247a7e4043f9f45e9.png" style="max-width: 100.0%;max-height: 100.0%;"/> 1. solved 10 minutes after the start: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ed13f9d5e6cc1ef056b90a9157397d02abab0b16.png" style="max-width: 100.0%;max-height: 100.0%;"/> So, this order gives 3.72 + 2.58 + 3 = 9.3 points in total and this is the only optimal order (you can calculate total scores for other 5 possible orders too see that they are lower). You should check points for problems 1 and 3 to see a paradox. There is 4 &lt; 10 but 3.72 &gt; 3. It turns out that there is no paradox for *c* = 0.625 but there is a paradox for any bigger *c*. In the second sample, all 24 orders are optimal. In the third sample, even for *c* = 1 there is no paradox.
716
Title: Game with String Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string *s*, consisting of small English letters, and uniformly at random chooses an integer *k* from a segment [0,<=*len*(*s*)<=-<=1]. He tells Vasya this string *s*, and then shifts it *k* letters to the left, i. e. creates a new string *t*<==<=*s**k*<=+<=1*s**k*<=+<=2... *s**n**s*1*s*2... *s**k*. Vasya does not know the integer *k* nor the string *t*, but he wants to guess the integer *k*. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose. Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of *k* uniquely, it means, that if there are at least two cyclic shifts of *s* that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win. Input Specification: The only string contains the string *s* of length *l* (3<=≤<=*l*<=≤<=5000), consisting of small English letters only. Output Specification: Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10<=-<=6. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct if Demo Input: ['technocup\n', 'tictictactac\n', 'bbaabaabbb\n'] Demo Output: ['1.000000000000000\n', '0.333333333333333\n', '0.100000000000000\n'] Note: In the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely. In the second example if the first opened letter of *t* is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
717
Title: PolandBall and White-Red graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: PolandBall has an undirected simple graph consisting of *n* vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red. Colorfulness of the graph is a value *min*(*d**r*,<=*d**w*), where *d**r* is the diameter of the red subgraph and *d**w* is the diameter of white subgraph. The diameter of a graph is a largest value *d* such that shortest path between some pair of vertices in it is equal to *d*. If the graph is not connected, we consider its diameter to be -1. PolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to *k*. Can you help him and find any graph which satisfies PolandBall's requests? Input Specification: The only one input line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*k*<=≤<=1000), representing graph's size and sought colorfulness. Output Specification: If it's impossible to find a suitable graph, print -1. Otherwise, you can output any graph which fulfills PolandBall's requirements. First, output *m* — the number of red edges in your graph. Then, you should output *m* lines, each containing two integers *a**i* and *b**i*, (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*) which means that there is an undirected red edge between vertices *a**i* and *b**i*. Every red edge should be printed exactly once, you can print the edges and the vertices of every edge in arbitrary order. Remember that PolandBall's graph should remain simple, so no loops or multiple edges are allowed. Demo Input: ['4 1\n', '5 2\n'] Demo Output: ['-1\n', '4\n1 2\n2 3\n3 4\n4 5\n'] Note: In the first sample case, no graph can fulfill PolandBall's requirements. In the second sample case, red graph is a path from 1 to 5. Its diameter is 4. However, white graph has diameter 2, because it consists of edges 1-3, 1-4, 1-5, 2-4, 2-5, 3-5.
718
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* beacons located at distinct positions on a number line. The *i*-th beacon has position *a**i* and power level *b**i*. When the *i*-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance *b**i* inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated. Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. Input Specification: The first line of input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the initial number of beacons. The *i*-th of next *n* lines contains two integers *a**i* and *b**i* (0<=≤<=*a**i*<=≤<=1<=000<=000, 1<=≤<=*b**i*<=≤<=1<=000<=000) — the position and power level of the *i*-th beacon respectively. No two beacons will have the same position, so *a**i*<=≠<=*a**j* if *i*<=≠<=*j*. Output Specification: Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. Demo Input: ['4\n1 9\n3 1\n6 1\n7 4\n', '7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1\n'] Demo Output: ['1\n', '3\n'] Note: For the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2. For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.
719
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little time is left before Berland annual football championship. Therefore the coach of team "Losewille Rangers" decided to resume the practice, that were indefinitely interrupted for uncertain reasons. Overall there are *n* players in "Losewille Rangers". Each player on the team has a number — a unique integer from 1 to *n*. To prepare for the championship, the coach Mr. Floppe decided to spend some number of practices. Mr. Floppe spent some long nights of his holiday planning how to conduct the practices. He came to a very complex practice system. Each practice consists of one game, all *n* players of the team take part in the game. The players are sorted into two teams in some way. In this case, the teams may have different numbers of players, but each team must have at least one player. The coach wants to be sure that after the series of the practice sessions each pair of players had at least one practice, when they played in different teams. As the players' energy is limited, the coach wants to achieve the goal in the least number of practices. Help him to schedule the practices. Input Specification: A single input line contains integer *n* (2<=≤<=*n*<=≤<=1000). Output Specification: In the first line print *m* — the minimum number of practices the coach will have to schedule. Then print the descriptions of the practices in *m* lines. In the *i*-th of those lines print *f**i* — the number of players in the first team during the *i*-th practice (1<=≤<=*f**i*<=&lt;<=*n*), and *f**i* numbers from 1 to *n* — the numbers of players in the first team. The rest of the players will play in the second team during this practice. Separate numbers on a line with spaces. Print the numbers of the players in any order. If there are multiple optimal solutions, print any of them. Demo Input: ['2\n', '3\n'] Demo Output: ['1\n1 1\n', '2\n2 1 2\n1 1\n'] Note: none
720
Title: Devu and Birthday Celebration Time Limit: None seconds Memory Limit: None megabytes Problem Description: Today is Devu's birthday. For celebrating the occasion, he bought *n* sweets from the nearby market. He has invited his *f* friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend. He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed *n* sweets to his friends such that *i**th* friend is given *a**i* sweets. He wants to make sure that there should not be any positive integer *x*<=&gt;<=1, which divides every *a**i*. Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (109<=+<=7). To make the problem more interesting, you are given *q* queries. Each query contains an *n*, *f* pair. For each query please output the required number of ways modulo 1000000007 (109<=+<=7). Input Specification: The first line contains an integer *q* representing the number of queries (1<=≤<=*q*<=≤<=105). Each of the next *q* lines contains two space space-separated integers *n*, *f* (1<=≤<=*f*<=≤<=*n*<=≤<=105). Output Specification: For each query, output a single integer in a line corresponding to the answer of each query. Demo Input: ['5\n6 2\n7 2\n6 3\n6 4\n7 4\n'] Demo Output: ['2\n6\n9\n10\n20\n'] Note: For first query: *n* = 6, *f* = 2. Possible partitions are [1, 5] and [5, 1]. For second query: *n* = 7, *f* = 2. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning.
721
Title: Mentors Time Limit: None seconds Memory Limit: None megabytes Problem Description: In BerSoft $n$ programmers work, the programmer $i$ is characterized by a skill $r_i$. A programmer $a$ can be a mentor of a programmer $b$ if and only if the skill of the programmer $a$ is strictly greater than the skill of the programmer $b$ $(r_a &gt; r_b)$ and programmers $a$ and $b$ are not in a quarrel. You are given the skills of each programmers and a list of $k$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $i$, find the number of programmers, for which the programmer $i$ can be a mentor. Input Specification: The first line contains two integers $n$ and $k$ $(2 \le n \le 2 \cdot 10^5$, $0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $r_1, r_2, \dots, r_n$ $(1 \le r_i \le 10^{9})$, where $r_i$ equals to the skill of the $i$-th programmer. Each of the following $k$ lines contains two distinct integers $x$, $y$ $(1 \le x, y \le n$, $x \ne y)$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $x$ is in a quarrel with $y$ then $y$ is in a quarrel with $x$. Guaranteed, that for each pair $(x, y)$ there are no other pairs $(x, y)$ and $(y, x)$ in the input. Output Specification: Print $n$ integers, the $i$-th number should be equal to the number of programmers, for which the $i$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input. Demo Input: ['4 2\n10 4 10 15\n1 2\n4 3\n', '10 4\n5 4 1 5 4 3 7 1 2 5\n4 6\n2 1\n10 8\n3 5\n'] Demo Output: ['0 0 1 2 \n', '5 4 0 5 3 3 9 0 2 5 \n'] Note: In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.
722
Title: Two Paths Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Once archaeologists found *m* mysterious papers, each of which had a pair of integers written on them. Ancient people were known to like writing down the indexes of the roads they walked along, as «*a* *b*» or «*b* *a*», where *a*,<=*b* are the indexes of two different cities joint by the road . It is also known that the mysterious papers are pages of two travel journals (those days a new journal was written for every new journey). During one journey the traveler could walk along one and the same road several times in one or several directions but in that case he wrote a new entry for each time in his journal. Besides, the archaeologists think that the direction the traveler took on a road had no effect upon the entry: the entry that looks like «*a* *b*» could refer to the road from *a* to *b* as well as to the road from *b* to *a*. The archaeologists want to put the pages in the right order and reconstruct the two travel paths but unfortunately, they are bad at programming. That’s where you come in. Go help them! Input Specification: The first input line contains integer *m* (1<=≤<=*m*<=≤<=10000). Each of the following *m* lines describes one paper. Each description consists of two integers *a*,<=*b* (1<=≤<=*a*,<=*b*<=≤<=10000, *a*<=≠<=*b*). Output Specification: In the first line output the number *L*1. That is the length of the first path, i.e. the amount of papers in its description. In the following line output *L*1 space-separated numbers — the indexes of the papers that describe the first path. In the third and fourth lines output similarly the length of the second path *L*2 and the path itself. Both paths must contain at least one road, i.e. condition *L*1<=&gt;<=0 and *L*2<=&gt;<=0 must be met. The papers are numbered from 1 to *m* according to the order of their appearance in the input file. The numbers should be output in the order in which the traveler passed the corresponding roads. If the answer is not unique, output any. If it’s impossible to find such two paths, output «-1». Don’t forget that each paper should be used exactly once, i.e *L*1<=+<=*L*2<==<=*m*. Demo Input: ['2\n4 5\n4 3\n', '1\n1 2\n'] Demo Output: ['1\n2 \n1\n1\n', '-1\n'] Note: none
723
Title: Vladik and Entertaining Flags Time Limit: None seconds Memory Limit: None megabytes Problem Description: In his spare time Vladik estimates beauty of the flags. Every flag could be represented as the matrix *n*<=×<=*m* which consists of positive integers. Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1,<=*l*) and (*n*,<=*r*), where conditions 1<=≤<=*l*<=≤<=*r*<=≤<=*m* are satisfied. Help Vladik to calculate the beauty for some segments of the given flag. Input Specification: First line contains three space-separated integers *n*, *m*, *q* (1<=≤<=*n*<=≤<=10, 1<=≤<=*m*,<=*q*<=≤<=105) — dimensions of flag matrix and number of segments respectively. Each of next *n* lines contains *m* space-separated integers — description of flag matrix. All elements of flag matrix is positive integers not exceeding 106. Each of next *q* lines contains two space-separated integers *l*, *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*m*) — borders of segment which beauty Vladik wants to know. Output Specification: For each segment print the result on the corresponding line. Demo Input: ['4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5\n'] Demo Output: ['6\n7\n3\n4\n'] Note: Partitioning on components for every segment from first test case: <img class="tex-graphics" src="https://espresso.codeforces.com/5c89ff7036ddb39d2997c8f594d4a0729e524ab0.png" style="max-width: 100.0%;max-height: 100.0%;"/>
724
Title: Bulbs Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on. Input Specification: The first line of the input contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of buttons and the number of bulbs respectively. Each of the next *n* lines contains *x**i* (0<=≤<=*x**i*<=≤<=*m*) — the number of bulbs that are turned on by the *i*-th button, and then *x**i* numbers *y**ij* (1<=≤<=*y**ij*<=≤<=*m*) — the numbers of these bulbs. Output Specification: If it's possible to turn on all *m* bulbs print "YES", otherwise print "NO". Demo Input: ['3 4\n2 1 4\n3 1 3 1\n1 2\n', '3 3\n1 1\n1 2\n1 1\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.
725
Title: Months and Years Time Limit: None seconds Memory Limit: None megabytes Problem Description: Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December. A year is leap in one of two cases: either its number is divisible by 4, but not divisible by 100, or is divisible by 400. For example, the following years are leap: 2000, 2004, but years 1900 and 2018 are not leap. In this problem you are given *n* (1<=≤<=*n*<=≤<=24) integers *a*1,<=*a*2,<=...,<=*a**n*, and you have to check if these integers could be durations in days of *n* consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is *a*1 days, duration of the next month is *a*2 days, and so on. Input Specification: The first line contains single integer *n* (1<=≤<=*n*<=≤<=24) — the number of integers. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (28<=≤<=*a**i*<=≤<=31) — the numbers you are to check. Output Specification: If there are several consecutive months that fit the sequence, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can print each letter in arbitrary case (small or large). Demo Input: ['4\n31 31 30 31\n', '2\n30 30\n', '5\n29 31 30 31 30\n', '3\n31 28 30\n', '3\n31 31 28\n'] Demo Output: ['Yes\n\n', 'No\n\n', 'Yes\n\n', 'No\n\n', 'Yes\n\n'] Note: In the first example the integers can denote months July, August, September and October. In the second example the answer is no, because there are no two consecutive months each having 30 days. In the third example the months are: February (leap year) — March — April – May — June. In the fourth example the number of days in the second month is 28, so this is February. March follows February and has 31 days, but not 30, so the answer is NO. In the fifth example the months are: December — January — February (non-leap year).
726
Title: Petya and Staircases Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them. Now Petya is on the first stair of the staircase, consisting of *n* stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number *n* without touching a dirty stair once. One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=109, 0<=≤<=*m*<=≤<=3000) — the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains *m* different space-separated integers *d*1,<=*d*2,<=...,<=*d**m* (1<=≤<=*d**i*<=≤<=*n*) — the numbers of the dirty stairs (in an arbitrary order). Output Specification: Print "YES" if Petya can reach stair number *n*, stepping only on the clean stairs. Otherwise print "NO". Demo Input: ['10 5\n2 4 8 3 6\n', '10 5\n2 4 5 7 9\n'] Demo Output: ['NO', 'YES'] Note: none
727
Title: Sereja and Suffixes Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are staying on the positions *l**i*, *l**i*<=+<=1, ..., *n*. Formally, he want to find the number of distinct numbers among *a**l**i*,<=*a**l**i*<=+<=1,<=...,<=*a**n*.? Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each *l**i*. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=105) — the array elements. Next *m* lines contain integers *l*1,<=*l*2,<=...,<=*l**m*. The *i*-th line contains integer *l**i* (1<=≤<=*l**i*<=≤<=*n*). Output Specification: Print *m* lines — on the *i*-th line print the answer to the number *l**i*. Demo Input: ['10 10\n1 2 3 4 1 2 3 4 100000 99999\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n'] Demo Output: ['6\n6\n6\n6\n6\n5\n4\n3\n2\n1\n'] Note: none
728
Title: Little Elephant and Shifts Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Little Elephant has two permutations *a* and *b* of length *n*, consisting of numbers from 1 to *n*, inclusive. Let's denote the *i*-th (1<=≤<=*i*<=≤<=*n*) element of the permutation *a* as *a**i*, the *j*-th (1<=≤<=*j*<=≤<=*n*) element of the permutation *b* — as *b**j*. The distance between permutations *a* and *b* is the minimum absolute value of the difference between the positions of the occurrences of some number in *a* and in *b*. More formally, it's such minimum |*i*<=-<=*j*|, that *a**i*<==<=*b**j*. A cyclic shift number *i* (1<=≤<=*i*<=≤<=*n*) of permutation *b* consisting from *n* elements is a permutation *b**i**b**i*<=+<=1... *b**n**b*1*b*2... *b**i*<=-<=1. Overall a permutation has *n* cyclic shifts. The Little Elephant wonders, for all cyclic shifts of permutation *b*, what is the distance between the cyclic shift and permutation *a*? Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the size of the permutations. The second line contains permutation *a* as *n* distinct numbers from 1 to *n*, inclusive. The numbers are separated with single spaces. The third line contains permutation *b* in the same format. Output Specification: In *n* lines print *n* integers — the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation *b*, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on. Demo Input: ['2\n1 2\n2 1\n', '4\n2 1 3 4\n3 4 2 1\n'] Demo Output: ['1\n0\n', '2\n1\n0\n1\n'] Note: none
729
Title: Petya and Square Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Little Petya loves playing with squares. Mum bought him a square 2*n*<=×<=2*n* in size. Petya marked a cell inside the square and now he is solving the following task. The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any common points with the marked cell and the resulting two parts should be equal up to rotation. Petya wants to determine whether it is possible to cut the square in the required manner given the sizes of the square side and the coordinates of the marked cell. Help him. Input Specification: The first line contains three space-separated integers 2*n*, *x* and *y* (2<=≤<=2*n*<=≤<=100,<=1<=≤<=*x*,<=*y*<=≤<=2*n*), representing the length of a square's side and the coordinates of the marked cell. It is guaranteed that 2*n* is even. The coordinates of the marked cell are represented by a pair of numbers *x* *y*, where *x* represents the number of the row and *y* represents the number of the column. The rows and columns are numbered by consecutive integers from 1 to 2*n*. The rows are numbered from top to bottom and the columns are numbered from the left to the right. Output Specification: If the square is possible to cut, print "YES", otherwise print "NO" (without the quotes). Demo Input: ['4 1 1\n', '2 2 2\n'] Demo Output: ['YES\n', 'NO\n'] Note: A sample test from the statement and one of the possible ways of cutting the square are shown in the picture:
730
Title: Searching Rectangles Time Limit: None seconds Memory Limit: None megabytes Problem Description: Filya just learned new geometry object — rectangle. He is given a field consisting of *n*<=×<=*n* unit cells. Rows are numbered from bottom to top with integer from 1 to *n*. Columns are numbered from left to right with integers from 1 to *n*. Cell, located at the intersection of the row *r* and column *c* is denoted as (*r*,<=*c*). Filya has painted two rectangles, such that their sides are parallel to coordinate axes and each cell lies fully inside or fully outside each of them. Moreover, no cell lies in both rectangles. Later, hedgehog Filya became interested in the location of his rectangles but was unable to find the sheet of paper they were painted on. They were taken by Sonya and now she wants to play a little game with Filya. He tells her a query rectangle and she replies with the number of initial rectangles that lie fully inside the given query rectangle. The query rectangle should match the same conditions as initial rectangles. Rectangle lies fully inside the query if each o its cells lies inside the query. Filya knows Sonya really well, so is sure that if he asks more than 200 questions she will stop to reply. Input Specification: The first line of the input contains an integer *n* (2<=≤<=*n*<=≤<=216) — size of the field. For each query an integer between 0 and 2 is returned — the number of initial rectangles that lie fully inside the query rectangle. Output Specification: To make a query you have to print "? *x*1 *y*1 *x*2 *y*2" (without quotes) (1<=≤<=*x*1<=≤<=*x*2<=≤<=*n*, 1<=≤<=*y*1<=≤<=*y*2<=≤<=*n*), where (*x*1,<=*y*1) stands for the position of the bottom left cell of the query and (*x*2,<=*y*2) stands for the up right cell of the query. You are allowed to ask no more than 200 queries. After each query you should perform "flush" operation and read the answer. In case you suppose you've already determined the location of two rectangles (or run out of queries) you should print "! *x*11 *y*11 *x*12 *y*12 *x*21 *y*21 *x*22 *y*22" (without quotes), where first four integers describe the bottom left and up right cells of the first rectangle, and following four describe the corresponding cells of the second rectangle. You can print the rectangles in an arbitrary order. After you have printed the answer, print the end of the line and perform "flush". Your program should terminate immediately after it print the answer. Demo Input: ['5\n2\n1\n0\n1\n1\n1\n0\n1\n'] Demo Output: ['? 1 1 5 5\n? 1 1 3 3\n? 1 1 3 1\n? 2 2 2 2\n? 3 3 5 5\n? 3 3 3 5\n? 3 3 3 4\n? 3 4 3 5\n! 2 2 2 2 3 4 3 5\n'] Note: none
731
Title: Brain Network (hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage. Input Specification: The first line of the input contains one number *n* – the number of brains in the final nervous system (2<=≤<=*n*<=≤<=200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1,<=2,<=...,<=*n* in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2,<=3,<=...,<=*n* are added). The second line contains *n*<=-<=1 space-separated numbers *p*2,<=*p*3,<=...,<=*p**n*, meaning that after a new brain *k* is added to the system, it gets connected to a parent-brain . Output Specification: Output *n*<=-<=1 space-separated numbers – the brain latencies after the brain number *k* is added, for *k*<==<=2,<=3,<=...,<=*n*. Demo Input: ['6\n1\n2\n2\n1\n5\n'] Demo Output: ['1 2 2 3 4 '] Note: none
732
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over. You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with. Input Specification: The first line of the input contains two integers, *x*,<=*y* (1<=≤<=*x*,<=*y*<=≤<=1018,<=*xy*<=&gt;<=1) — the number of oranges and apples that were initially in the bag. Output Specification: Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them. If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible. Demo Input: ['1 4\n', '2 2\n', '3 2\n'] Demo Output: ['3B\n', 'Impossible\n', '1A1B\n'] Note: In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples. In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges. In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
733
Title: Nearest Minimums Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array of *n* integer numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. Input Specification: The first line contains positive integer *n* (2<=≤<=*n*<=≤<=105) — size of the given array. The second line contains *n* integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (1<=≤<=*a**i*<=≤<=109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times. Output Specification: Print the only number — distance between two nearest minimums in the array. Demo Input: ['2\n3 3\n', '3\n5 6 5\n', '9\n2 1 3 5 4 1 2 3 1\n'] Demo Output: ['1\n', '2\n', '3\n'] Note: none
734
Title: Center Alignment Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input Specification: The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. Output Specification: Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. Demo Input: ['This is\n\nCodeforces\nBeta\nRound\n5\n', 'welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck\n'] Demo Output: ['************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************\n', '****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************\n'] Note: none
735
Title: Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers? Input Specification: The first line contains an integer *n* — how many numbers Anna had (3<=≤<=*n*<=≤<=105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109. Output Specification: Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes). Demo Input: ['4\n1 2 3 2\n', '6\n1 1 2 2 2 3\n', '6\n2 4 1 1 2 2\n'] Demo Output: ['YES\n', 'YES\n', 'NO\n'] Note: none
736
Title: Cycle Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained *n* rows and *m* columns. The rows are numbered from top to bottom from 1 to *n*, the columns are numbered from the left to the right from 1 to *m*. Petya immediately decided to find the longest cool cycle whatever it takes. A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: - The cycle entirely consists of the cells that contain "1". - Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. - Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (*i*,<=*j*) (*i* is the row number, *j* is the column number) correspond to the point (*i*,<=*j*) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (*r*,<=*c*) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (*r*,<=*c*) lies in the part with the infinite area. Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and columns in the table, respectively. Each of the following *n* lines contains *m* characters. Each character can be either "0" or "1". Output Specification: Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. Demo Input: ['3 3\n111\n101\n111\n', '5 5\n01010\n10101\n01010\n10101\n01010\n', '7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111\n', '5 5\n11111\n10001\n10101\n10001\n11111\n'] Demo Output: ['8\n', '0\n', '24\n', '0\n'] Note: In the first example there's only one cycle and it is cool. In the second sample there's no cycle at all. In the third sample there are two cool cycles: their lengths are 12 and 24. In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle.
737
Title: Plane of Tanks: Duel Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya plays the Plane of Tanks. Tanks are described with the following attributes: - the number of hit points; - the interval between two gun shots (the time required to recharge the gun); - the probability that the gun shot will not pierce armor of the enemy tank; - the damage to the enemy's tank. The gun damage is described with a segment [*l*,<=*r*], where *l* and *r* are integer numbers. The potential gun damage *x* is chosen with equal probability among all integer numbers of the segment [*l*,<=*r*]. If the shot pierces the armor of an enemy's tank then the enemy loses *x* hit points. If the number of hit points becomes non-positive then the enemy tank is considered destroyed. It is possible that the shot does not pierce the armor of a tank. In this case the number of hit points doesn't change. The probability that the armor will not be pierced is considered as the shooting tank attribute and does not depend on players' behavior. The victory is near and there is only one enemy tank left. Vasya is ready for the battle — one more battle between the Good and the Evil is inevitable! Two enemies saw each other and each of them fired a shot at the same moment... The last battle has begun! Help Vasya to determine what is the probability that he will win the battle by destroying the enemy tank? If both tanks are destroyed (after simultaneous shots), then Vasya is considered a winner. You can assume that each player fires a shot just after the gun recharge and each tank has infinite number of ammo. Input Specification: The first line contains five integer numbers separated with spaces describing Vasya's tank: the number of hit points *hp* (10<=≤<=*hp*<=≤<=200), the interval between two shots *dt* (1<=≤<=*dt*<=≤<=30), gun damage segment *l* and *r* (10<=≤<=*l*<=≤<=*r*<=≤<=100), the probability that the enemy's tank armor will not be pierced *p* (0<=≤<=*p*<=≤<=100) (percents). The second line describes the tank of Vasya's enemy in the same format. Output Specification: Print the only number with absolute or relative error no more than 10<=-<=4 — probability of Vasya's victory. Demo Input: ['100 3 50 50 0\n100 3 50 50 0\n', '100 3 50 50 0\n100 2 48 50 0\n', '100 3 50 50 0\n100 1 50 50 50\n'] Demo Output: ['1.000000\n', '0.888889\n', '0.500000\n'] Note: In the first example both tanks are destroyed at once after the second shot. The probability of destroying the enemy tank is 1. In the second example Vasya's enemy tank fires the second shot before Vasya's tank, but has no time for the third shot. In order to destroy Vasya's tank it is necessary to fire two shots with damage 50. The probability of that event is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5b8cbead818d4c86d1b85c58f6f83a955392b329.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3aa776870a184225f95e5a8de47bdeadf28fa805.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Otherwise, Vasya wins. In the third example Vasya's enemy tank fires three shots with probability of armor piercing 0.5. In order to destroy Vasya's tank it is necessary that at least 2 of 3 shots pierce the armor of Vasya's tank. The probability of this event is 0.5.
738
Title: Information Reform Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal. The North Pole governor decided to carry out an information reform. Several cities were decided to be chosen and made regional centers. Maintaining a region center takes *k* fishlars (which is a local currency) per year. It is assumed that a regional center always has information on the latest news. For every city which is not a regional center, it was decided to appoint a regional center which will be responsible for keeping this city informed. In that case the maintenance costs will be equal to *d**len* fishlars per year, where *len* is the distance from a city to the corresponding regional center, measured in the number of roads along which one needs to go. Your task is to minimize the costs to carry out the reform. Input Specification: The first line contains two given numbers *n* and *k* (1<=≤<=*n*<=≤<=180,<=1<=≤<=*k*<=≤<=105). The second line contains *n*<=-<=1 integers *d**i*, numbered starting with 1 (*d**i*<=≤<=*d**i*<=+<=1,<=0<=≤<=*d**i*<=≤<=105). Next *n*<=-<=1 lines contain the pairs of cities connected by a road. Output Specification: On the first line print the minimum number of fishlars needed for a year's maintenance. On the second line print *n* numbers, where the *i*-th number will represent the number of the regional center, appointed to the *i*-th city. If the *i*-th city is a regional center itself, then you should print number *i*. If there are several solutions to that problem, print any of them. Demo Input: ['8 10\n2 5 9 11 15 19 20\n1 4\n1 3\n1 7\n4 6\n2 8\n2 3\n3 5\n'] Demo Output: ['38\n3 3 3 4 3 4 3 3 '] Note: none
739
Title: Planning The Expedition Time Limit: None seconds Memory Limit: None megabytes Problem Description: Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant. The warehouse has $m$ daily food packages. Each package has some food type $a_i$. Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food. Formally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different. What is the maximum possible number of days the expedition can last, following the requirements above? Input Specification: The first line contains two integers $n$ and $m$ ($1 \le n \le 100$, $1 \le m \le 100$) — the number of the expedition participants and the number of the daily food packages available. The second line contains sequence of integers $a_1, a_2, \dots, a_m$ ($1 \le a_i \le 100$), where $a_i$ is the type of $i$-th food package. Output Specification: Print the single integer — the number of days the expedition can last. If it is not possible to plan the expedition for even one day, print 0. Demo Input: ['4 10\n1 5 2 1 1 1 2 5 7 2\n', '100 1\n1\n', '2 5\n5 4 3 2 1\n', '3 9\n42 42 42 42 42 42 42 42 42\n'] Demo Output: ['2\n', '0\n', '1\n', '3\n'] Note: In the first example, Natasha can assign type $1$ food to the first participant, the same type $1$ to the second, type $5$ to the third and type $2$ to the fourth. In this case, the expedition can last for $2$ days, since each participant can get two food packages of his food type (there will be used $4$ packages of type $1$, two packages of type $2$ and two packages of type $5$). In the second example, there are $100$ participants and only $1$ food package. In this case, the expedition can't last even $1$ day.
740
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Limak is a little polar bear. He loves connecting with other bears via social networks. He has *n* friends and his relation with the *i*-th of them is described by a unique integer *t**i*. The bigger this value is, the better the friendship is. No two friends have the same value *t**i*. Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time. The system displays friends who are online. On the screen there is space to display at most *k* friends. If there are more than *k* friends online then the system displays only *k* best of them — those with biggest *t**i*. Your task is to handle queries of two types: - "1 id" — Friend *id* becomes online. It's guaranteed that he wasn't online before. - "2 id" — Check whether friend *id* is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type? Input Specification: The first line contains three integers *n*, *k* and *q* (1<=≤<=*n*,<=*q*<=≤<=150<=000,<=1<=≤<=*k*<=≤<=*min*(6,<=*n*)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=109) where *t**i* describes how good is Limak's relation with the *i*-th friend. The *i*-th of the following *q* lines contains two integers *type**i* and *id**i* (1<=≤<=*type**i*<=≤<=2,<=1<=≤<=*id**i*<=≤<=*n*) — the *i*-th query. If *type**i*<==<=1 then a friend *id**i* becomes online. If *type**i*<==<=2 then you should check whether a friend *id**i* is displayed. It's guaranteed that no two queries of the first type will have the same *id**i* becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (*type**i*<==<=2) so the output won't be empty. Output Specification: For each query of the second type print one line with the answer — "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise. Demo Input: ['4 2 8\n300 950 500 200\n1 3\n2 4\n2 3\n1 1\n1 2\n2 1\n2 2\n2 3\n', '6 3 9\n50 20 51 17 99 24\n1 3\n1 4\n1 5\n1 2\n2 4\n2 2\n1 1\n2 4\n2 3\n'] Demo Output: ['NO\nYES\nNO\nYES\nYES\n', 'NO\nYES\nNO\nYES\n'] Note: In the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries: 1. "1 3" — Friend 3 becomes online. 1. "2 4" — We should check if friend 4 is displayed. He isn't even online and thus we print "NO". 1. "2 3" — We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES". 1. "1 1" — Friend 1 becomes online. The system now displays both friend 1 and friend 3. 1. "1 2" — Friend 2 becomes online. There are 3 friends online now but we were given *k* = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (*t*<sub class="lower-index">1</sub> &lt; *t*<sub class="lower-index">2</sub>, *t*<sub class="lower-index">3</sub>) so friend 1 won't be displayed 1. "2 1" — Print "NO". 1. "2 2" — Print "YES". 1. "2 3" — Print "YES".
741
Title: Multipliers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ayrat has number *n*, represented as it's prime factorization *p**i* of size *m*, i.e. *n*<==<=*p*1·*p*2·...·*p**m*. Ayrat got secret information that that the product of all divisors of *n* taken modulo 109<=+<=7 is the password to the secret data base. Now he wants to calculate this value. Input Specification: The first line of the input contains a single integer *m* (1<=≤<=*m*<=≤<=200<=000) — the number of primes in factorization of *n*. The second line contains *m* primes numbers *p**i* (2<=≤<=*p**i*<=≤<=200<=000). Output Specification: Print one integer — the product of all divisors of *n* modulo 109<=+<=7. Demo Input: ['2\n2 3\n', '3\n2 3 2\n'] Demo Output: ['36\n', '1728\n'] Note: In the first sample *n* = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36. In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.
742
Title: Black and White Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: The board has got a painted tree graph, consisting of *n* nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles. Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer. A bad boy Vasya came up to the board and wrote number *s**v* near each node *v* — the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board. Your task is to restore the original tree by the node colors and numbers *s**v*. Input Specification: The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=105) — the number of nodes in the tree. Next *n* lines contain pairs of space-separated integers *c**i*, *s**i* (0<=≤<=*c**i*<=≤<=1, 0<=≤<=*s**i*<=≤<=109), where *c**i* stands for the color of the *i*-th vertex (0 is for white, 1 is for black), and *s**i* represents the sum of values of the edges that are incident to the *i*-th vertex of the tree that is painted on the board. Output Specification: Print the description of *n*<=-<=1 edges of the tree graph. Each description is a group of three integers *v**i*, *u**i*, *w**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*n*, *v**i*<=≠<=*u**i*, 0<=≤<=*w**i*<=≤<=109), where *v**i* and *u**i* — are the numbers of the nodes that are connected by the *i*-th edge, and *w**i* is its value. Note that the following condition must fulfill *c**v**i*<=≠<=*c**u**i*. It is guaranteed that for any input data there exists at least one graph that meets these data. If there are multiple solutions, print any of them. You are allowed to print the edges in any order. As you print the numbers, separate them with spaces. Demo Input: ['3\n1 3\n1 2\n0 5\n', '6\n1 0\n0 3\n1 8\n0 2\n0 3\n0 0\n'] Demo Output: ['3 1 3\n3 2 2\n', '2 3 3\n5 3 3\n4 3 2\n1 6 0\n2 1 0\n'] Note: none
743
Title: Sequence of points Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: You are given the following points with integer coordinates on the plane: *M*0,<=*A*0,<=*A*1,<=...,<=*A**n*<=-<=1, where *n* is odd number. Now we define the following infinite sequence of points *M**i*: *M**i* is symmetric to *M**i*<=-<=1 according (for every natural number *i*). Here point *B* is symmetric to *A* according *M*, if *M* is the center of the line segment *AB*. Given index *j* find the point *M**j*. Input Specification: On the first line you will be given an integer *n* (1<=≤<=*n*<=≤<=105), which will be odd, and *j* (1<=≤<=*j*<=≤<=1018), where *j* is the index of the desired point. The next line contains two space separated integers, the coordinates of *M*0. After that *n* lines follow, where the *i*-th line contain the space separated integer coordinates of the point *A**i*<=-<=1. The absolute values of all input coordinates will not be greater then 1000. Output Specification: On a single line output the coordinates of *M**j*, space separated. Demo Input: ['3 4\n0 0\n1 1\n2 3\n-5 3\n', '3 1\n5 5\n1000 1000\n-1000 1000\n3 100\n'] Demo Output: ['14 0\n', '1995 1995\n'] Note: none
744
Title: DZY Loves Planting Time Limit: None seconds Memory Limit: None megabytes Problem Description: DZY loves planting, and he enjoys solving tree problems. DZY has a weighted tree (connected undirected graph without cycles) containing *n* nodes (they are numbered from 1 to *n*). He defines the function *g*(*x*,<=*y*) (1<=≤<=*x*,<=*y*<=≤<=*n*) as the longest edge in the shortest path between nodes *x* and *y*. Specially *g*(*z*,<=*z*)<==<=0 for every *z*. For every integer sequence *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*), DZY defines *f*(*p*) as . DZY wants to find such a sequence *p* that *f*(*p*) has maximum possible value. But there is one more restriction: the element *j* can appear in *p* at most *x**j* times. Please, find the maximum possible *f*(*p*) under the described restrictions. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=3000). Each of the next *n*<=-<=1 lines contains three integers *a**i*,<=*b**i*,<=*c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; 1<=≤<=*c**i*<=≤<=10000), denoting an edge between *a**i* and *b**i* with length *c**i*. It is guaranteed that these edges form a tree. Each of the next *n* lines describes an element of sequence *x*. The *j*-th line contains an integer *x**j* (1<=≤<=*x**j*<=≤<=*n*). Output Specification: Print a single integer representing the answer. Demo Input: ['4\n1 2 1\n2 3 2\n3 4 3\n1\n1\n1\n1\n', '4\n1 2 1\n2 3 2\n3 4 3\n4\n4\n4\n4\n'] Demo Output: ['2\n', '3\n'] Note: In the first sample, one of the optimal *p* is [4, 3, 2, 1].
745
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website. Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic. Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "*n*', where *n* is the total number of tests. Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only. The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command. Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run: - all examples are the first several tests having filenames "1", "2", ..., "*e*", where *e* is the total number of examples; - all other files contain regular tests with filenames "*e*<=+<=1", "*e*<=+<=2", ..., "*n*", where *n* is the total number of all tests. Input Specification: The first line contains single integer *n* (1<=≤<=*n*<=≤<=105) — the number of files with tests. *n* lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the *i*-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct. Output Specification: In the first line print the minimum number of lines in Vladimir's script file. After that print the script file, each line should be "move file_1 file_2", where "file_1" is an existing at the moment of this line being run filename, and "file_2" — is a string of digits and small English letters with length from 1 to 6. Demo Input: ['5\n01 0\n2 1\n2extra 0\n3 1\n99 0\n', '2\n1 0\n2 1\n', '5\n1 0\n11 1\n111 0\n1111 1\n11111 0\n'] Demo Output: ['4\nmove 3 1\nmove 01 5\nmove 2extra 4\nmove 99 3\n', '3\nmove 1 3\nmove 2 1\nmove 3 2', '5\nmove 1 5\nmove 11 1\nmove 1111 2\nmove 111 4\nmove 11111 3\n'] Note: none
746
Title: A Good Contest Time Limit: None seconds Memory Limit: None megabytes Problem Description: Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it. Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same? Input Specification: The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of participants Anton has outscored in this contest . The next *n* lines describe participants results: the *i*-th of them consists of a participant handle *name**i* and two integers *before**i* and *after**i* (<=-<=4000<=≤<=*before**i*,<=*after**i*<=≤<=4000) — participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters «_» and «-» characters. It is guaranteed that all handles are distinct. Output Specification: Print «YES» (quotes for clarity), if Anton has performed good in the contest and «NO» (quotes for clarity) otherwise. Demo Input: ['3\nBurunduk1 2526 2537\nBudAlNik 2084 2214\nsubscriber 2833 2749\n', '3\nApplejack 2400 2400\nFluttershy 2390 2431\nPinkie_Pie -2500 -2450\n'] Demo Output: ['YES', 'NO'] Note: In the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest. In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest.
747
Title: Robots protection Time Limit: None seconds Memory Limit: None megabytes Problem Description: Company "Robots industries" produces robots for territory protection. Robots protect triangle territories — right isosceles triangles with catheti parallel to North-South and East-West directions. Owner of some land buys and sets robots on his territory to protect it. From time to time, businessmen want to build offices on that land and want to know how many robots will guard it. You are to handle these queries. Input Specification: The first line contains integer *N* — width and height of the land, and integer *Q* — number of queries to handle. Next *Q* lines contain queries you need to process. Two types of queries: 1. 1 *dir* *x* *y* *len* — add a robot to protect a triangle. Depending on the value of *dir*, the values of *x*, *y* and *len* represent a different triangle: *dir*<==<=1: Triangle is defined by the points (*x*,<=*y*), (*x*<=+<=*len*,<=*y*), (*x*,<=*y*<=+<=*len*) 1. *dir*<==<=2: Triangle is defined by the points (*x*,<=*y*), (*x*<=+<=*len*,<=*y*), (*x*,<=*y*<=-<=*len*) 1. *dir*<==<=3: Triangle is defined by the points (*x*,<=*y*), (*x*<=-<=*len*,<=*y*), (*x*,<=*y*<=+<=*len*) 1. *dir*<==<=4: Triangle is defined by the points (*x*,<=*y*), (*x*<=-<=*len*,<=*y*), (*x*,<=*y*<=-<=*len*) 1. 2 *x* *y* — output how many robots guard this point (robot guards a point if the point is inside or on the border of its triangle) - 1<=≤<=*N*<=≤<=5000 - 1<=≤<=*Q*<=≤<=105 - 1<=≤<=*dir*<=≤<=4 - All points of triangles are within range [1,<=*N*] - All numbers are positive integers Output Specification: For each second type query output how many robots guard this point. Each answer should be in a separate line. Demo Input: ['17 10\n1 1 3 2 4\n1 3 10 3 7\n1 2 6 8 2\n1 3 9 4 2\n2 4 4\n1 4 15 10 6\n2 7 7\n2 9 4\n2 12 2\n2 13 8\n'] Demo Output: ['2\n2\n2\n0\n1\n'] Note: none
748
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sonya was unable to think of a story for this problem, so here comes the formal description. You are given the array containing *n* positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0. Input Specification: The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=3000) — the length of the array. Next line contains *n* integer *a**i* (1<=≤<=*a**i*<=≤<=109). Output Specification: Print the minimum number of operation required to make the array strictly increasing. Demo Input: ['7\n2 1 5 11 5 9 11\n', '5\n5 4 3 2 1\n'] Demo Output: ['9\n', '12\n'] Note: In the first sample, the array is going to look as follows: 2 3 5 6 7 9 11 |2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9 And for the second sample: 1 2 3 4 5 |5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12
749
Title: Playing the ball Time Limit: None seconds Memory Limit: None megabytes Problem Description: A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game. Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who chooses an arbitrary direction and throws a ball in that direction. The ball hits the plane at distance *d* from the player's original position and continues flying in the same direction. After the ball hits the plane for the first time, it flies on and hits the plane again at distance 2·*d* from the player's original position and so on (it continue flying in the chosen direction and hitting the plane after each *d* units). All coders in the F company are strong, so the ball flies infinitely far away. The plane has *n* circles painted on it. If a ball hits the plane and hits a circle that is painted on the plane (including its border), then the player gets one point. The ball can hit multiple circles at once and get one point for each of them (if the ball hits some circle *x* times during the move, the player also gets *x* points). Count the maximum number of points a player can get if he throws a ball in the arbitrary direction. Note that the direction may have real cooridinates. Input Specification: The first line contains two space-separated integers — *n* и *d* (1<=≤<=*n*<=≤<=2·104; 5<=≤<=*d*<=≤<=10). Next *n* lines contain the circles' description. The *i*-th line contains three space-separated integers *x**i*, *y**i*, *r**i* (<=-<=10000<=≤<=*x**i*,<=*y**i*<=≤<=10000; 1<=≤<=*r*<=≤<=50), where (*x**i*,<=*y**i*,<=*r**i*) are the coordinates of the center and the radius of the circle, correspondingly. The point (0, 0) is not inside or on the border of some circle. Output Specification: Print a single integer — the maximum number of points you can get. Demo Input: ['2 5\n1 1 1\n5 0 1\n', '2 5\n4 0 3\n5 3 1\n', '1 10\n20 0 10\n'] Demo Output: ['1\n', '2\n', '3\n'] Note: none
750
Title: Towers Time Limit: None seconds Memory Limit: None megabytes Problem Description: As you know, all the kids in Berland love playing with cubes. Little Petya has *n* towers consisting of cubes of the same size. Tower with number *i* consists of *a**i* cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than *k* such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input Specification: The first line contains two space-separated positive integers *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1000) — the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains *n* space-separated positive integers *a**i* (1<=≤<=*a**i*<=≤<=104) — the towers' initial heights. Output Specification: In the first line print two space-separated non-negative integers *s* and *m* (*m*<=≤<=*k*). The first number is the value of the minimum possible instability that can be obtained after performing at most *k* operations, the second number is the number of operations needed for that. In the next *m* lines print the description of each operation as two positive integers *i* and *j*, each of them lies within limits from 1 to *n*. They represent that Petya took the top cube from the *i*-th tower and put in on the *j*-th one (*i*<=≠<=*j*). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Demo Input: ['3 2\n5 8 5\n', '3 4\n2 2 4\n', '5 3\n8 3 2 6 3\n'] Demo Output: ['0 2\n2 1\n2 3\n', '1 1\n3 2\n', '3 3\n1 3\n1 2\n1 3\n'] Note: In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6.
751
Title: Anton and Making Potions Time Limit: None seconds Memory Limit: None megabytes Problem Description: Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare *n* potions. Anton has a special kettle, that can prepare one potions in *x* seconds. Also, he knows spells of two types that can faster the process of preparing potions. 1. Spells of this type speed up the preparation time of one potion. There are *m* spells of this type, the *i*-th of them costs *b**i* manapoints and changes the preparation time of each potion to *a**i* instead of *x*. 1. Spells of this type immediately prepare some number of potions. There are *k* such spells, the *i*-th of them costs *d**i* manapoints and instantly create *c**i* potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed *s*. Consider that all spells are used instantly and right before Anton starts to prepare potions. Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least *n* potions. Input Specification: The first line of the input contains three integers *n*, *m*, *k* (1<=≤<=*n*<=≤<=2·109,<=1<=≤<=*m*,<=*k*<=≤<=2·105) — the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type. The second line of the input contains two integers *x* and *s* (2<=≤<=*x*<=≤<=2·109,<=1<=≤<=*s*<=≤<=2·109) — the initial number of seconds required to prepare one potion and the number of manapoints Anton can use. The third line contains *m* integers *a**i* (1<=≤<=*a**i*<=&lt;<=*x*) — the number of seconds it will take to prepare one potion if the *i*-th spell of the first type is used. The fourth line contains *m* integers *b**i* (1<=≤<=*b**i*<=≤<=2·109) — the number of manapoints to use the *i*-th spell of the first type. There are *k* integers *c**i* (1<=≤<=*c**i*<=≤<=*n*) in the fifth line — the number of potions that will be immediately created if the *i*-th spell of the second type is used. It's guaranteed that *c**i* are not decreasing, i.e. *c**i*<=≤<=*c**j* if *i*<=&lt;<=*j*. The sixth line contains *k* integers *d**i* (1<=≤<=*d**i*<=≤<=2·109) — the number of manapoints required to use the *i*-th spell of the second type. It's guaranteed that *d**i* are not decreasing, i.e. *d**i*<=≤<=*d**j* if *i*<=&lt;<=*j*. Output Specification: Print one integer — the minimum time one has to spent in order to prepare *n* potions. Demo Input: ['20 3 2\n10 99\n2 4 3\n20 10 40\n4 15\n10 80\n', '20 3 2\n10 99\n2 4 3\n200 100 400\n4 15\n100 800\n'] Demo Output: ['20\n', '200\n'] Note: In the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10 + 80 = 90, and the preparation time is 4·5 = 20 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each). In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20·10 = 200.
752
Title: Sereja and Dividing Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's assume that we have a sequence of doubles *a*1,<=*a*2,<=...,<=*a*|*a*| and a double variable *x*. You are allowed to perform the following two-staged operation: 1. choose an index of the sequence element *i* (1<=≤<=*i*<=≤<=|*a*|); 1. consecutively perform assignments: . Let's use function *g*(*a*,<=*x*) to represent the largest value that can be obtained from variable *x*, using the described operation any number of times and sequence *a*. Sereja has sequence *b*1,<=*b*2,<=...,<=*b*|*b*|. Help Sereja calculate sum: . Record [*b**i*,<=*b**i*<=+<=1,<=...,<=*b**j*] represents a sequence containing the elements in brackets in the given order. To avoid problems with precision, please, print the required sum divided by |*b*|2. Input Specification: The first line contains integer |*b*| (1<=≤<=|*b*|<=≤<=3·105) — the length of sequence *b*. The second line contains |*b*| integers *b*1, *b*2, ..., *b*|*b*| (1<=≤<=*b**i*<=≤<=105). Output Specification: In a single line print a real number — the required sum divided by |*b*|2. Your answer will be considered correct if its absolute or relative error won't exceed 10<=-<=6. Demo Input: ['5\n1 2 3 4 1\n'] Demo Output: ['1.238750000000000\n'] Note: none
753
Title: Race Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Old City is a rectangular city represented as an *m*<=×<=*n* grid of blocks. This city contains many buildings, straight two-way streets and junctions. Each junction and each building is exactly one block. All the streets have width of one block and are either vertical or horizontal. There is a junction on both sides of each street. We call two blocks adjacent if and only if they share a common side. No two blocks of different streets are adjacent and no two junctions are adjacent. There is an annual festival and as a part of it, The Old Peykan follows a special path in the city. This path starts from a block in a street, continues with many junctions and ends in a block of some street. For each street block, we know how much time it takes for the Old Peykan to go from this block to an adjacent block. Also the Old Peykan can go from each junction to its adjacent street blocks in one minute. Of course Old Peykan can't go to building blocks. We know the initial position of the Old Peykan and the sequence of junctions that it passes to reach its destination. After passing all the junctions and reaching the destination, it will stay there forever. Your task is to find out where will the Old Peykan be *k* minutes after it starts moving. Consider that The Old Peykan always follows the shortest path that passes through the given sequence of junctions and reaches the destination. Note that the Old Peykan may visit some blocks more than once. Input Specification: The first line of input contains three integers *m*, *n* and *k* (3<=≤<=*m*,<=*n*<=≤<=100,<=1<=≤<=*k*<=≤<=100000). Next *m* lines are representing the city's map. Each of them containts *n* characters, each character is a block: - Character "#" represents a building. - Digits "1", "2", ..., "9" represent a block of an street and this digit means the number of minutes it takes for the Old Peykan to pass this block. - Characters "a", "b", ..., "z" means that this block is a junction and this character is it's name. All the junction names are unique. Consider that all blocks have the coordinates: the *j*-th in the *i*-th line have coordinates (*i*,<=*j*) (1<=≤<=*i*<=≤<=*m*,<=1<=≤<=*j*<=≤<=*n*). The (*m*<=+<=2)th line contains two integers *r**s* and *c**s* (1<=≤<=*r**s*<=≤<=*m*,<=1<=≤<=*c**s*<=≤<=*n*), string *s* and another two integers *r**e* and *c**e* (1<=≤<=*r**e*<=≤<=*m*,<=1<=≤<=*c**e*<=≤<=*n*). The path starts from block (*r**s*,<=*c**s*), continues through junctions in the order that is specified by *s* and will end in block (*r**e*,<=*c**e*). Length of *s* is between 1 and 1000. It's guaranteed that string *s* denotes a correct path from the start position to the end position and string *s* doesn't contain two consecutive equal letters. Also start position (*r**s*,<=*c**s*) and the end position (*r**e*,<=*c**e*) are street blocks. Output Specification: In a single line print two integers *r**f* and *c**f* — (*r**f*,<=*c**f*) being the position of the Old Peykan after exactly *k* minutes. Demo Input: ['3 10 12\n##########\n#z1a1111b#\n##########\n2 3 ab 2 8\n', '10 3 5\n###\n#w#\n#1#\n#a#\n#1#\n#1#\n#1#\n#1#\n#b#\n###\n3 2 abababababababab 6 2\n', '3 10 6\n##########\n#z1a1311b#\n##########\n2 3 ab 2 8\n'] Demo Output: ['2 8\n', '8 2\n', '2 7\n'] Note: none
754
Title: Captain Marmot Time Limit: None seconds Memory Limit: None megabytes Problem Description: Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has *n* regiments, each consisting of 4 moles. Initially, each mole *i* (1<=≤<=*i*<=≤<=4*n*) is placed at some position (*x**i*,<=*y**i*) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible. Each mole *i* has a home placed at the position (*a**i*,<=*b**i*). Moving this mole one time means rotating his position point (*x**i*,<=*y**i*) 90 degrees counter-clockwise around it's home point (*a**i*,<=*b**i*). A regiment is compact only if the position points of the 4 moles form a square with non-zero area. Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible. Input Specification: The first line contains one integer *n* (1<=≤<=*n*<=≤<=100), the number of regiments. The next 4*n* lines contain 4 integers *x**i*, *y**i*, *a**i*, *b**i* (<=-<=104<=≤<=*x**i*,<=*y**i*,<=*a**i*,<=*b**i*<=≤<=104). Output Specification: Print *n* lines to the standard output. If the regiment *i* can be made compact, the *i*-th line should contain one integer, the minimal number of required moves. Otherwise, on the *i*-th line print "-1" (without quotes). Demo Input: ['4\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-2 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n-1 1 0 0\n2 2 0 1\n-1 0 0 -2\n3 0 0 -2\n-1 1 -2 0\n'] Demo Output: ['1\n-1\n3\n3\n'] Note: In the first regiment we can move once the second or the third mole. We can't make the second regiment compact. In the third regiment, from the last 3 moles we can move once one and twice another one. In the fourth regiment, we can move twice the first mole and once the third mole.
755
Title: Colorful Stones (Simplified Edition) Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string *s*. The *i*-th (1-based) character of *s* represents the color of the *i*-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively. Initially Squirrel Liss is standing on the first stone. You perform instructions one or more times. Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction *c*, if Liss is standing on a stone whose colors is *c*, Liss will move one stone forward, else she will not move. You are given a string *t*. The number of instructions is equal to the length of *t*, and the *i*-th character of *t* represents the *i*-th instruction. Calculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence. Input Specification: The input contains two lines. The first line contains the string *s* (1<=≤<=|*s*|<=≤<=50). The second line contains the string *t* (1<=≤<=|*t*|<=≤<=50). The characters of each string will be one of "R", "G", or "B". It is guaranteed that Liss don't move out of the sequence. Output Specification: Print the final 1-based position of Liss in a single line. Demo Input: ['RGB\nRRR\n', 'RRRBGBRBBB\nBBBRR\n', 'BRRBGBRGRBGRGRRGGBGBGBRGBRGRGGGRBRRRBRBBBGRRRGGBBB\nBBRBGGRGRGBBBRBGRBRBBBBRBRRRBGBBGBBRRBBGGRBRRBRGRB\n'] Demo Output: ['2\n', '3\n', '15\n'] Note: none
756
Title: k-Factorization Time Limit: None seconds Memory Limit: None megabytes Problem Description: Given a positive integer *n*, find *k* integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to *n*. Input Specification: The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=100000, 1<=≤<=*k*<=≤<=20). Output Specification: If it's impossible to find the representation of *n* as a product of *k* numbers, print -1. Otherwise, print *k* integers in any order. Their product must be equal to *n*. If there are multiple answers, print any of them. Demo Input: ['100000 2\n', '100000 20\n', '1024 5\n'] Demo Output: ['2 50000 \n', '-1\n', '2 64 2 2 2 \n'] Note: none
757
Title: Plus and Square Root Time Limit: None seconds Memory Limit: None megabytes Problem Description: ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, '<=+<=' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are *n*<=+<=1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level *k*, he can : 1. Press the '<=+<=' button. This increases the number on the screen by exactly *k*. So, if the number on the screen was *x*, it becomes *x*<=+<=*k*.1. Press the '' button. Let the number on the screen be *x*. After pressing this button, the number becomes . After that, ZS the Coder levels up, so his current level becomes *k*<=+<=1. This button can only be pressed when *x* is a perfect square, i.e. *x*<==<=*m*2 for some positive integer *m*. Additionally, after each move, if ZS the Coder is at level *k*, and the number on the screen is *m*, then *m* must be a multiple of *k*. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5. ZS the Coder needs your help in beating the game — he wants to reach level *n*<=+<=1. In other words, he needs to press the '' button *n* times. Help him determine the number of times he should press the '<=+<=' button before pressing the '' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level *n*<=+<=1, but not necessarily a sequence minimizing the number of presses. Input Specification: The first and only line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000), denoting that ZS the Coder wants to reach level *n*<=+<=1. Output Specification: Print *n* non-negative integers, one per line. *i*-th of them should be equal to the number of times that ZS the Coder needs to press the '<=+<=' button before pressing the '' button at level *i*. Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. Demo Input: ['3\n', '2\n', '4\n'] Demo Output: ['14\n16\n46\n', '999999999999999998\n44500000000\n', '2\n17\n46\n97\n'] Note: In the first sample case: On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14·1 = 16. Then, ZS the Coder pressed the '<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c77ded9b8209a8cb488cc2ec7b7fe1dae32a5309.png" style="max-width: 100.0%;max-height: 100.0%;"/>' button, and the number became <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c3d2663f5f74e9220fd5cbccbfaf4ca76ef7284f.png" style="max-width: 100.0%;max-height: 100.0%;"/>. After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16·2 = 36. Then, ZS pressed the '<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c77ded9b8209a8cb488cc2ec7b7fe1dae32a5309.png" style="max-width: 100.0%;max-height: 100.0%;"/>' button, levelling up and changing the number into <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/49ab1d31f1435b7c7b96550d63a35be671d3d85a.png" style="max-width: 100.0%;max-height: 100.0%;"/>. After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46·3 = 144. Then, ZS pressed the '<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c77ded9b8209a8cb488cc2ec7b7fe1dae32a5309.png" style="max-width: 100.0%;max-height: 100.0%;"/>' button, levelling up and changing the number into <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/499b57d4b7ba5e1e0957767cc182808ca48ef722.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4. Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10·3 = 36, and when the '<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c77ded9b8209a8cb488cc2ec7b7fe1dae32a5309.png" style="max-width: 100.0%;max-height: 100.0%;"/>' button is pressed, the number becomes <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/49ab1d31f1435b7c7b96550d63a35be671d3d85a.png" style="max-width: 100.0%;max-height: 100.0%;"/> and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution. In the second sample case: On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998·1 = 10<sup class="upper-index">18</sup>. Then, ZS the Coder pressed the '<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c77ded9b8209a8cb488cc2ec7b7fe1dae32a5309.png" style="max-width: 100.0%;max-height: 100.0%;"/>' button, and the number became <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f07f2a60ab6cecbd2507861a0df57a16a015fd86.png" style="max-width: 100.0%;max-height: 100.0%;"/>. After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 10<sup class="upper-index">9</sup> + 44500000000·2 = 9·10<sup class="upper-index">10</sup>. Then, ZS pressed the '<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c77ded9b8209a8cb488cc2ec7b7fe1dae32a5309.png" style="max-width: 100.0%;max-height: 100.0%;"/>' button, levelling up and changing the number into <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4c4d8829d987a7bcfd597cd1aa101327a66c0eca.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3.
758
Title: Below the Diagonal Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a square matrix consisting of *n* rows and *n* columns. We assume that the rows are numbered from 1 to *n* from top to bottom and the columns are numbered from 1 to *n* from left to right. Some cells (*n*<=-<=1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: 1. Swap *i*-th and *j*-th rows of the matrix; 1. Swap *i*-th and *j*-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the *i*-th row and of the *j*-th column, lies below the main diagonal if *i*<=&gt;<=*j*. Input Specification: The first line contains an integer *n* (2<=≤<=*n*<=≤<=1000) — the number of rows and columns. Then follow *n*<=-<=1 lines that contain one's positions, one per line. Each position is described by two integers *x**k*,<=*y**k* (1<=≤<=*x**k*,<=*y**k*<=≤<=*n*), separated by a space. A pair (*x**k*,<=*y**k*) means that the cell, which is located on the intersection of the *x**k*-th row and of the *y**k*-th column, contains one. It is guaranteed that all positions are distinct. Output Specification: Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer *m* (*m*<=≤<=105) — the number of actions. In each of the next *m* lines print three space-separated integers *t*,<=*i*,<=*j* (1<=≤<=*t*<=≤<=2,<=1<=≤<=*i*,<=*j*<=≤<=*n*,<=*i*<=≠<=*j*), where *t*<==<=1 if you want to swap rows, *t*<==<=2 if you want to swap columns, and *i* and *j* denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them. Demo Input: ['2\n1 2\n', '3\n3 1\n1 3\n', '3\n2 1\n3 2\n'] Demo Output: ['2\n2 1 2\n1 1 2\n', '3\n2 2 3\n1 1 3\n1 1 2\n', '0\n'] Note: none
759
Title: Effective Approach Time Limit: None seconds Memory Limit: None megabytes Problem Description: Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is. Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent. To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand. But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* distinct space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the elements of array. The third line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of queries. The last line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=*n*) — the search queries. Note that the queries can repeat. Output Specification: Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. 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. Demo Input: ['2\n1 2\n1\n1\n', '2\n2 1\n1\n1\n', '3\n3 1 2\n3\n1 2 3\n'] Demo Output: ['1 2\n', '2 1\n', '6 6\n'] Note: In the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element). In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
760
Title: Kefa and Park Time Limit: None seconds Memory Limit: None megabytes Problem Description: Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of *n* vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them. The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than *m* consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. Input Specification: The first line contains two integers, *n* and *m* (2<=≤<=*n*<=≤<=105, 1<=≤<=*m*<=≤<=*n*) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where each *a**i* either equals to 0 (then vertex *i* has no cat), or equals to 1 (then vertex *i* has a cat). Next *n*<=-<=1 lines contains the edges of the tree in the format "*x**i* *y**i*" (without the quotes) (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*, *x**i*<=≠<=*y**i*), where *x**i* and *y**i* are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. Output Specification: A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most *m* consecutive vertices with cats. Demo Input: ['4 1\n1 1 0 0\n1 2\n1 3\n1 4\n', '7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n'] Demo Output: ['2\n', '2\n'] Note: Let us remind you that a tree is a connected graph on *n* vertices and *n* - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children. Note to the first sample test: <img class="tex-graphics" src="https://espresso.codeforces.com/785114b4b3f5336f02078c25750f87c5a1d0b4be.png" style="max-width: 100.0%;max-height: 100.0%;"/> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2. Note to the second sample test: <img class="tex-graphics" src="https://espresso.codeforces.com/e5c07640680c837aec99126d94287872e69aa09a.png" style="max-width: 100.0%;max-height: 100.0%;"/> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
761
Title: Incorrect Flow Time Limit: None seconds Memory Limit: None megabytes Problem Description: At the entrance examination for the magistracy of the MSU Cyber-Mechanics Department Sasha got the question about Ford-Fulkerson algorithm. He knew the topic perfectly as he worked with it many times on programming competition. As the task for the question he was given a network with partially build flow that he had to use in order to demonstrate the workflow of the algorithm. He quickly finished to write the text and took a look at the problem only to understand that the given network is incorrect! Suppose you are given a directed graph *G*(*V*,<=*E*) with two special nodes *s* and *t* called source and sink. We denote as *n* the number of nodes in the graph, i.e. *n*<==<=|*V*| and *m* stands for the number of directed edges in the graph, i.e. *m*<==<=|*E*|. For the purpose of this problem we always consider node 1 to be the source and node *n* to be the sink. In addition, for each edge of the graph *e* we define the capacity function *c*(*e*) and flow function *f*(*e*). Function *f*(*e*) represents the correct flow if the following conditions are satisfied: 1. For each edge the flow is non-negative and does not exceed capacity *c*(*e*), i.e. 0<=≤<=*f*(*e*)<=≤<=*c*(*e*). 1. For each node , that is not source or sink (*v*<=≠<=*s* and *v*<=≠<=*t*) the sum of flows of all edges going in *v* is equal to the sum of the flows among all edges going out from *v*. In other words, there is no flow stuck in *v*. It was clear that as the exam was prepared last night and there are plenty of mistakes in the tasks. Sasha asked one of the professors to fix the network or give the correct task, but the reply was that the magistrate student should be able to fix the network himself. As the professor doesn't want the task to become easier, he asks Sasha to fix the network in a such way that the total number of changes is minimum possible. Sasha is not allowed to remove edges, add new ones or reverse the direction of existing edges. The only thing he is able to do is to change capacity function *c*(*e*) and flow function *f*(*e*). Moreover, all the values should remain non-negative integers. There is no requirement on the flow to be maximum in any sense. Find the minimum possible total change of the functions *f*(*e*) and *c*(*e*) that Sasha has to make in order to make the flow correct. The total change is defined as the sum of absolute differences, i.e. if new functions are *f*<=*<=(*e*) and *c*<=*<=(*e*), then the total change is . Input Specification: The first line of the input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=100, 0<=≤<=*m*<=≤<=100) — the number of nodes and edges in the graph respectively. Each of the following *m* lines contains the description of the edges, consisting of four integers *u**i*, *v**i*, *c**i* and *f**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*, 0<=≤<=*c**i*,<=*f**i*<=≤<=1<=000<=000) — index of the node the edges starts from, the index of the node the edge goes to, current capacity and flow value. Node number 1 is the source, and node number *n* is the sink. It's guaranteed that no edge goes to the source, and no edges starts in the sink. Given graph contains no self-loops but may contain multiple edges. Output Specification: Print one integer — the minimum total sum of changes that Sasha has to do in order to get the correct flow description. Demo Input: ['2 1\n1 2 2 1\n', '2 1\n1 2 1 2\n', '3 3\n1 2 1 1\n2 3 2 2\n1 3 3 3\n', '4 2\n2 3 1 1\n3 2 1 1\n'] Demo Output: ['0\n', '1\n', '1\n', '0\n'] Note: In the first sample, the flow is initially correct. Note, that the flow is not maximum, but this is not required. In the second sample, the flow value of the only edge is greater than its capacity. There are two ways to fix this: either increase the capacity up to 2 or reduce the flow down to 1. In the third sample, there is only 1 unit of flow coming to vertex 2, but there are 2 units going out of it. One of the possible solutions is to reduce the value of the flow on the second edge by 1. In the fourth sample, there is isolated circulation of flow, but this description is correct by definition.
762
Title: Road Construction Time Limit: None seconds Memory Limit: None megabytes Problem Description: A country has *n* cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given *m* pairs of cities — roads cannot be constructed between these pairs of cities. Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible. Input Specification: The first line consists of two integers *n* and *m* . Then *m* lines follow, each consisting of two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*), which means that it is not possible to construct a road connecting cities *a**i* and *b**i*. Consider the cities are numbered from 1 to *n*. It is guaranteed that every pair of cities will appear at most once in the input. Output Specification: You should print an integer *s*: the minimum number of roads that should be constructed, in the first line. Then *s* lines should follow, each consisting of two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*), which means that a road should be constructed between cities *a**i* and *b**i*. If there are several solutions, you may print any of them. Demo Input: ['4 1\n1 3\n'] Demo Output: ['3\n1 2\n4 2\n2 3\n'] Note: This is one possible solution of the example: These are examples of wrong solutions:
763
Title: Range Increments Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array *a* for all indexes in the segment [*l*,<=*r*]. In other words, this function does the following: Polycarpus knows the state of the array *a* after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105. Before calls of function rangeIncrement(l, r) all array elements equal zero. Input Specification: The first input line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the length of the array *a*[1... *n*]. The second line contains its integer space-separated elements, *a*[1],<=*a*[2],<=...,<=*a*[*n*] (0<=≤<=*a*[*i*]<=≤<=105) after some series of function calls rangeIncrement(l, r). It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r). Output Specification: Print on the first line *t* — the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105. Then print *t* lines — the descriptions of function calls, one per line. Each line should contain two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*) — the arguments of the *i*-th call rangeIncrement(l, r). Calls can be applied in any order. If there are multiple solutions, you are allowed to print any of them. Demo Input: ['6\n1 2 1 1 4 1\n', '5\n1 0 1 0 1\n'] Demo Output: ['5\n2 2\n5 5\n5 5\n5 5\n1 6\n', '3\n1 1\n3 3\n5 5\n'] Note: The first sample requires a call for the entire array, and four additional calls: - one for the segment [2,2] (i.e. the second element of the array), - three for the segment [5,5] (i.e. the fifth element of the array).
764
Title: BerSU Ball Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! *n* boys and *m* girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&amp;girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one. For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from *n* boys and *m* girls. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of boys. The second line contains sequence *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100), where *a**i* is the *i*-th boy's dancing skill. Similarly, the third line contains an integer *m* (1<=≤<=*m*<=≤<=100) — the number of girls. The fourth line contains sequence *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**j*<=≤<=100), where *b**j* is the *j*-th girl's dancing skill. Output Specification: Print a single number — the required maximum possible number of pairs. Demo Input: ['4\n1 4 6 2\n5\n5 1 5 7 9\n', '4\n1 2 3 4\n4\n10 11 12 13\n', '5\n1 1 1 1 1\n3\n1 2 3\n'] Demo Output: ['3\n', '0\n', '2\n'] Note: none
765
Title: Board Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are playing a board card game. In this game the player has two characteristics, *x* and *y* — the white magic skill and the black magic skill, respectively. There are *n* spell cards lying on the table, each of them has four characteristics, *a**i*, *b**i*, *c**i* and *d**i*. In one move a player can pick one of the cards and cast the spell written on it, but only if first two of it's characteristics meet the requirement *a**i*<=≤<=*x* and *b**i*<=≤<=*y*, i.e. if the player has enough magic skill to cast this spell. However, after casting the spell the characteristics of a player change and become equal to *x*<==<=*c**i* and *y*<==<=*d**i*. At the beginning of the game both characteristics of a player are equal to zero. The goal of the game is to cast the *n*-th spell. Your task is to make it in as few moves as possible. You are allowed to use spell in any order and any number of times (for example, you may not use some spells at all). Input Specification: The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of cards on the table. Each of the next *n* lines contains four integers *a**i*, *b**i*, *c**i*, *d**i* (0<=≤<=*a**i*,<=*b**i*,<=*c**i*,<=*d**i*<=≤<=109) — the characteristics of the corresponding card. Output Specification: In the first line print a single integer *k* — the minimum number of moves needed to cast the *n*-th spell and in the second line print *k* numbers — the indices of the cards in the order in which you should cast them. In case there are multiple possible solutions, print any of them. If it is impossible to cast the *n*-th spell, print <=-<=1. Demo Input: ['4\n0 0 3 4\n2 2 5 3\n4 1 1 7\n5 3 8 8\n', '2\n0 0 4 6\n5 1 1000000000 1000000000\n'] Demo Output: ['3\n1 2 4\n', '-1\n'] Note: none
766
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer *x*. You are given multiple queries consisting of pairs of integers *l* and *r*. For each query, find the *x*, such that *l*<=≤<=*x*<=≤<=*r*, and is maximum possible. If there are multiple such numbers find the smallest of them. Input Specification: The first line contains integer *n* — the number of queries (1<=≤<=*n*<=≤<=10000). Each of the following *n* lines contain two integers *l**i*,<=*r**i* — the arguments for the corresponding query (0<=≤<=*l**i*<=≤<=*r**i*<=≤<=1018). Output Specification: For each query print the answer in a separate line. Demo Input: ['3\n1 2\n2 4\n1 10\n'] Demo Output: ['1\n3\n7\n'] Note: The binary representations of numbers from 1 to 10 are listed below: 1<sub class="lower-index">10</sub> = 1<sub class="lower-index">2</sub> 2<sub class="lower-index">10</sub> = 10<sub class="lower-index">2</sub> 3<sub class="lower-index">10</sub> = 11<sub class="lower-index">2</sub> 4<sub class="lower-index">10</sub> = 100<sub class="lower-index">2</sub> 5<sub class="lower-index">10</sub> = 101<sub class="lower-index">2</sub> 6<sub class="lower-index">10</sub> = 110<sub class="lower-index">2</sub> 7<sub class="lower-index">10</sub> = 111<sub class="lower-index">2</sub> 8<sub class="lower-index">10</sub> = 1000<sub class="lower-index">2</sub> 9<sub class="lower-index">10</sub> = 1001<sub class="lower-index">2</sub> 10<sub class="lower-index">10</sub> = 1010<sub class="lower-index">2</sub>
767
Title: Transmitting Levels Time Limit: None seconds Memory Limit: None megabytes Problem Description: Optimizing the amount of data transmitted via a network is an important and interesting part of developing any network application. In one secret game developed deep in the ZeptoLab company, the game universe consists of *n* levels, located in a circle. You can get from level *i* to levels *i*<=-<=1 and *i*<=+<=1, also you can get from level 1 to level *n* and vice versa. The map of the *i*-th level description size is *a**i* bytes. In order to reduce the transmitted traffic, the game gets levels as follows. All the levels on the server are divided into *m* groups and each time a player finds himself on one of the levels of a certain group for the first time, the server sends all levels of the group to the game client as a single packet. Thus, when a player travels inside the levels of a single group, the application doesn't need any new information. Due to the technical limitations the packet can contain an arbitrary number of levels but their total size mustn't exceed *b* bytes, where *b* is some positive integer constant. Usual situation is that players finish levels one by one, that's why a decision was made to split *n* levels into *m* groups so that each group was a continuous segment containing multiple neighboring levels (also, the group can have two adjacent levels, *n* and 1). Specifically, if the descriptions of all levels have the total weight of at most *b* bytes, then they can all be united into one group to be sent in a single packet. Determine, what minimum number of groups do you need to make in order to organize the levels of the game observing the conditions above? As developing a game is a long process and technology never stagnates, it is yet impossible to predict exactly what value will take constant value *b* limiting the packet size when the game is out. That's why the developers ask you to find the answer for multiple values of *b*. Input Specification: The first line contains two integers *n*, *q* (2<=≤<=*n*<=≤<=106, 1<=≤<=*q*<=≤<=50) — the number of levels in the game universe and the number of distinct values of *b* that you need to process. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the sizes of the levels in bytes. The next *q* lines contain integers *b**j* (), determining the values of constant *b*, for which you need to determine the answer. Output Specification: For each value of *k**j* from the input print on a single line integer *m**j* (1<=≤<=*m**j*<=≤<=*n*), determining the minimum number of groups to divide game levels into for transmission via network observing the given conditions. Demo Input: ['6 3\n2 4 2 1 3 2\n7\n4\n6\n'] Demo Output: ['2\n4\n3\n'] Note: In the test from the statement you can do in the following manner. - at *b* = 7 you can divide into two segments: 2|421|32 (note that one of the segments contains the fifth, sixth and first levels); - at *b* = 4 you can divide into four segments: 2|4|21|3|2; - at *b* = 6 you can divide into three segments: 24|21|32|.
768
Title: About Bacteria Time Limit: None seconds Memory Limit: None megabytes Problem Description: Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high. At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into *k* bacteria. After that some abnormal effects create *b* more bacteria in the test tube. Thus, if at the beginning of some second the test tube had *x* bacteria, then at the end of the second it will have *kx*<=+<=*b* bacteria. The experiment showed that after *n* seconds there were exactly *z* bacteria and the experiment ended at this point. For the second experiment Qwerty is going to sterilize the test tube and put there *t* bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least *z* bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment. Help Qwerty and find the minimum number of seconds needed to get a tube with at least *z* bacteria in the second experiment. Input Specification: The first line contains four space-separated integers *k*, *b*, *n* and *t* (1<=≤<=*k*,<=*b*,<=*n*,<=*t*<=≤<=106) — the parameters of bacterial growth, the time Qwerty needed to grow *z* bacteria in the first experiment and the initial number of bacteria in the second experiment, correspondingly. Output Specification: Print a single number — the minimum number of seconds Qwerty needs to grow at least *z* bacteria in the tube. Demo Input: ['3 1 3 5\n', '1 4 4 7\n', '2 2 4 100\n'] Demo Output: ['2', '3', '0'] Note: none
769
Title: Find Pair Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing *n* (not necessarily different) integers *a*1, *a*2, ..., *a**n*. We are interested in all possible pairs of numbers (*a**i*, *a**j*), (1<=≤<=*i*,<=*j*<=≤<=*n*). In other words, let's consider all *n*2 pairs of numbers, picked from the given array. For example, in sequence *a*<==<={3,<=1,<=5} are 9 pairs of numbers: (3,<=3),<=(3,<=1),<=(3,<=5),<=(1,<=3),<=(1,<=1),<=(1,<=5),<=(5,<=3),<=(5,<=1),<=(5,<=5). Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair (*p*1, *q*1) is lexicographically less than pair (*p*2, *q*2) only if either *p*1 &lt; *p*2, or *p*1 = *p*2 and *q*1 &lt; *q*2. Then the sequence, mentioned above, will be sorted like that: (1,<=1),<=(1,<=3),<=(1,<=5),<=(3,<=1),<=(3,<=3),<=(3,<=5),<=(5,<=1),<=(5,<=3),<=(5,<=5) Let's number all the pair in the sorted list from 1 to *n*2. Your task is formulated like this: you should find the *k*-th pair in the ordered list of all possible pairs of the array you've been given. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=*n*2). The second line contains the array containing *n* integers *a*1, *a*2, ..., *a**n* (<=-<=109<=≤<=*a**i*<=≤<=109). The numbers in the array can coincide. All numbers are separated with spaces. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout, streams or the %I64d specificator instead. Output Specification: In the single line print two numbers — the sought *k*-th pair. Demo Input: ['2 4\n2 1\n', '3 2\n3 1 5\n'] Demo Output: ['2 2\n', '1 3\n'] Note: In the first sample the sorted sequence for the given array looks as: (1, 1), (1, 2), (2, 1), (2, 2). The 4-th of them is pair (2, 2). The sorted sequence for the array from the second sample is given in the statement. The 2-nd pair there is (1, 3).
770
Title: New Year Candles Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used like any other new candle. Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number. Input Specification: The single line contains two integers, *a* and *b* (1<=≤<=*a*<=≤<=1000; 2<=≤<=*b*<=≤<=1000). Output Specification: Print a single integer — the number of hours Vasily can light up the room for. Demo Input: ['4 2\n', '6 3\n'] Demo Output: ['7\n', '8\n'] Note: Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours.
771
Title: Race Against Time Time Limit: None seconds Memory Limit: None megabytes Problem Description: Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time *h* hours, *m* minutes, *s* seconds. Last time Misha talked with the coordinator at *t*1 o'clock, so now he stands on the number *t*1 on the clock face. The contest should be ready by *t*2 o'clock. In the terms of paradox it means that Misha has to go to number *t*2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction. Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way). Given the hands' positions, *t*1, and *t*2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from *t*1 to *t*2 by the clock face. Input Specification: Five integers *h*, *m*, *s*, *t*1, *t*2 (1<=≤<=*h*<=≤<=12, 0<=≤<=*m*,<=*s*<=≤<=59, 1<=≤<=*t*1,<=*t*2<=≤<=12, *t*1<=≠<=*t*2). Misha's position and the target time do not coincide with the position of any hand. Output Specification: Print "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES"). Demo Input: ['12 30 45 3 11\n', '12 0 1 12 1\n', '3 47 0 4 9\n'] Demo Output: ['NO\n', 'YES\n', 'YES\n'] Note: The three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the pictures are not exact, but are close to the exact and the answer is the same.
772
Title: Bits of merry old England Time Limit: None seconds Memory Limit: None megabytes Problem Description: Another feature of Shakespeare language is that the variables are named after characters of plays by Shakespeare, and all operations on them (value assignment, output etc.) look like a dialog with other characters. New values of variables are defined in a rather lengthy way, so a programmer should try to minimize their usage. You have to print the given sequence of *n* integers. To do this, you have *m* variables and two types of operations on them: - variable=integer - print(variable) Any of the *m* variables can be used as variable. Variables are denoted by lowercase letters between "a" and "z", inclusive. Any integer number can be used as integer. Let's say that the penalty for using first type of operations equals to the number of set bits in the number integer. There is no penalty on using second type of operations. Find and output the program which minimizes the penalty for printing the given sequence of numbers. Input Specification: The first line of input contains integers *n* and *m* (1<=≤<=*n*<=≤<=250, 1<=≤<=*m*<=≤<=26). The second line contains the sequence to be printed. Each element of the sequence is an integer between 1 and 109, inclusive. The sequence has to be printed in the given order (from left to right). Output Specification: Output the number of lines in the optimal program and the optimal penalty. Next, output the program itself, one command per line. If there are several programs with minimal penalty, output any of them (you have only to minimize the penalty). Demo Input: ['7 2\n1 2 2 4 2 1 2\n', '6 3\n1 2 3 1 2 3\n'] Demo Output: ['11 4\nb=1\nprint(b)\na=2\nprint(a)\nprint(a)\nb=4\nprint(b)\nprint(a)\nb=1\nprint(b)\nprint(a)\n', '9 4\nc=1\nprint(c)\nb=2\nprint(b)\na=3\nprint(a)\nprint(c)\nprint(b)\nprint(a)\n'] Note: none
773
Title: Intersection Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: You are given two set of points. The first set is determined by the equation *A*1*x*<=+<=*B*1*y*<=+<=*C*1<==<=0, and the second one is determined by the equation *A*2*x*<=+<=*B*2*y*<=+<=*C*2<==<=0. Write the program which finds the number of points in the intersection of two given sets. Input Specification: The first line of the input contains three integer numbers *A*1,<=*B*1,<=*C*1 separated by space. The second line contains three integer numbers *A*2,<=*B*2,<=*C*2 separated by space. All the numbers are between -100 and 100, inclusive. Output Specification: Print the number of points in the intersection or -1 if there are infinite number of points. Demo Input: ['1 1 0\n2 2 0\n', '1 1 0\n2 -2 0\n'] Demo Output: ['-1\n', '1\n'] Note: none
774
Title: Alice, Bob and Chocolate Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman. How many bars each of the players will consume? Input Specification: The first line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the amount of bars on the table. The second line contains a sequence *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=1000), where *t**i* is the time (in seconds) needed to consume the *i*-th bar (in the order from left to right). Output Specification: Print two numbers *a* and *b*, where *a* is the amount of bars consumed by Alice, and *b* is the amount of bars consumed by Bob. Demo Input: ['5\n2 9 8 2 7\n'] Demo Output: ['2 3\n'] Note: none
775
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: - There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. - There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. - Masculine adjectives end with -lios, and feminine adjectives end with -liala. - Masculine nouns end with -etr, and feminime nouns end with -etra. - Masculine verbs end with -initis, and feminime verbs end with -inites. - Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. - It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. - There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. - A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: - Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. - All words in the statement should have the same gender. After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language. Input Specification: The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language. Output Specification: If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). Demo Input: ['petr\n', 'etis atis animatis etis atis amatis\n', 'nataliala kataliala vetra feinites\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n'] Note: none
776
Title: Nearest Fraction Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given three positive integers *x*,<=*y*,<=*n*. Your task is to find the nearest fraction to fraction whose denominator is no more than *n*. Formally, you should find such pair of integers *a*,<=*b* (1<=≤<=*b*<=≤<=*n*; 0<=≤<=*a*) that the value is as minimal as possible. If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator. Input Specification: A single line contains three integers *x*,<=*y*,<=*n* (1<=≤<=*x*,<=*y*,<=*n*<=≤<=105). Output Specification: Print the required fraction in the format "*a*/*b*" (without quotes). Demo Input: ['3 7 6\n', '7 2 4\n'] Demo Output: ['2/5\n', '7/2\n'] Note: none
777
Title: Little Artem and Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it. That element can store information about the matrix of integers size *n*<=×<=*m*. There are *n*<=+<=*m* inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to *n* from top to bottom, while columns are numbered with integers from 1 to *m* from left to right. Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of *q* turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix. Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists. Input Specification: The first line of the input contains three integers *n*, *m* and *q* (1<=≤<=*n*,<=*m*<=≤<=100,<=1<=≤<=*q*<=≤<=10<=000) — dimensions of the matrix and the number of turns in the experiment, respectively. Next *q* lines contain turns descriptions, one per line. Each description starts with an integer *t**i* (1<=≤<=*t**i*<=≤<=3) that defines the type of the operation. For the operation of first and second type integer *r**i* (1<=≤<=*r**i*<=≤<=*n*) or *c**i* (1<=≤<=*c**i*<=≤<=*m*) follows, while for the operations of the third type three integers *r**i*, *c**i* and *x**i* (1<=≤<=*r**i*<=≤<=*n*, 1<=≤<=*c**i*<=≤<=*m*, <=-<=109<=≤<=*x**i*<=≤<=109) are given. Operation of the first type (*t**i*<==<=1) means that signal comes to the input corresponding to row *r**i*, that is it will shift cyclically. Operation of the second type (*t**i*<==<=2) means that column *c**i* will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row *r**i* and column *c**i* stores value *x**i*. Output Specification: Print the description of any valid initial matrix as *n* lines containing *m* integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them. Demo Input: ['2 2 6\n2 1\n2 2\n3 1 1 1\n3 2 2 2\n3 1 2 8\n3 2 1 8\n', '3 3 2\n1 2\n3 2 2 5\n'] Demo Output: ['8 2 \n1 8 \n', '0 0 0 \n0 0 5 \n0 0 0 \n'] Note: none
778
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases: 1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size *b*1 and *b*2, then one of the following is correct: *a*1 is equivalent to *b*1, and *a*2 is equivalent to *b*2 1. *a*1 is equivalent to *b*2, and *a*2 is equivalent to *b*1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent. Gerald has already completed this home task. Now it's your turn! Input Specification: The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200<=000 and consists of lowercase English letters. The strings have the same length. Output Specification: Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise. Demo Input: ['aaba\nabaa\n', 'aabb\nabab\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a". In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".
779
Title: Pacifist frogs Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much. One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to *n* and the number of a hill is equal to the distance in meters between it and the island. The distance between the *n*-th hill and the shore is also 1 meter. Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is *d*, the frog will jump from the island on the hill *d*, then — on the hill 2*d*, then 3*d* and so on until they get to the shore (i.e. find itself beyond the hill *n*). However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible. Input Specification: The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=109, 1<=≤<=*m*,<=*k*<=≤<=100) — the number of hills, frogs and mosquitoes respectively. The second line contains *m* integers *d**i* (1<=≤<=*d**i*<=≤<=109) — the lengths of the frogs’ jumps. The third line contains *k* integers — the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces. Output Specification: In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line — their numbers in increasing order separated by spaces. The frogs are numbered from 1 to *m* in the order of the jump length given in the input data. Demo Input: ['5 3 5\n2 3 4\n1 2 3 4 5\n', '1000000000 2 3\n2 5\n999999995 999999998 999999996\n'] Demo Output: ['2\n2 3\n', '1\n2\n'] Note: none
780
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget *a* is packed in the widget *b* if there exists a chain of widgets *a*<==<=*c*1,<=*c*2,<=...,<=*c**k*<==<=*b*, *k*<=≥<=2, for which *c**i* is packed directly to *c**i*<=+<=1 for any 1<=≤<=*i*<=&lt;<=*k*. In Vasya's library the situation when the widget *a* is packed in the widget *a* (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error. Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0<=×<=0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript. Input Specification: The first line contains an integer *n* — the number of instructions (1<=≤<=*n*<=≤<=100). Next *n* lines contain instructions in the language VasyaScript — one instruction per line. There is a list of possible instructions below. - "Widget [name]([x],[y])" — create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. - "HBox [name]" — create a new widget [name] of the type HBox. - "VBox [name]" — create a new widget [name] of the type VBox. - "[name1].pack([name2])" — pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. - "[name].set_border([x])" — set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. - "[name].set_spacing([x])" — set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data. All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget. Output Specification: For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator) Demo Input: ['12\nWidget me(50,40)\nVBox grandpa\nHBox father\ngrandpa.pack(father)\nfather.pack(me)\ngrandpa.set_border(10)\ngrandpa.set_spacing(20)\nWidget brother(30,60)\nfather.pack(brother)\nWidget friend(20,60)\nWidget uncle(100,20)\ngrandpa.pack(uncle)\n', '15\nWidget pack(10,10)\nHBox dummy\nHBox x\nVBox y\ny.pack(dummy)\ny.set_border(5)\ny.set_spacing(55)\ndummy.set_border(10)\ndummy.set_spacing(20)\nx.set_border(10)\nx.set_spacing(10)\nx.pack(pack)\nx.pack(dummy)\nx.pack(pack)\nx.set_border(0)\n'] Demo Output: ['brother 30 60\nfather 80 60\nfriend 20 60\ngrandpa 120 120\nme 50 40\nuncle 100 20\n', 'dummy 0 0\npack 10 10\nx 40 10\ny 10 10\n'] Note: In the first sample the widgets are arranged as follows:
781
Title: A Leapfrog in the Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that initially array contains *n* numbers from 1 to *n* and the number *i* is located in the cell with the index 2*i*<=-<=1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all *n* numbers will appear in the first *n* cells of the array. For example if *n*<==<=4, the array is changing as follows: You have to write a program that allows you to determine what number will be in the cell with index *x* (1<=≤<=*x*<=≤<=*n*) after Dima's algorithm finishes. Input Specification: The first line contains two integers *n* and *q* (1<=≤<=*n*<=≤<=1018, 1<=≤<=*q*<=≤<=200<=000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next *q* lines contain integers *x**i* (1<=≤<=*x**i*<=≤<=*n*), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes. Output Specification: For each of *q* queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes. Demo Input: ['4 3\n2\n3\n4\n', '13 4\n10\n5\n4\n8\n'] Demo Output: ['3\n2\n4\n', '13\n3\n8\n9\n'] Note: The first example is shown in the picture. In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7].
782
Title: Choosing Balls Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the *i*-th ball is *c**i* and the value of the *i*-th ball is *v**i*. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence. The value of the sequence is defined as the sum of following values for each ball (where *a* and *b* are given constants): - If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) <=×<= *a*. - Otherwise, add (the value of the ball) <=×<= *b*. You are given *q* queries. Each query contains two integers *a**i* and *b**i*. For each query find the maximal value of the sequence she can make when *a*<==<=*a**i* and *b*<==<=*b**i*. Note that the new sequence can be empty, and the value of an empty sequence is defined as zero. Input Specification: The first line contains two integers *n* and *q* (1<=≤<=*n*<=≤<=105; 1<=≤<=*q*<=≤<=500). The second line contains *n* integers: *v*1,<=*v*2,<=...,<=*v**n* (|*v**i*|<=≤<=105). The third line contains *n* integers: *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=*n*). The following *q* lines contain the values of the constants *a* and *b* for queries. The *i*-th of these lines contains two integers *a**i* and *b**i* (|*a**i*|,<=|*b**i*|<=≤<=105). In each line integers are separated by single spaces. Output Specification: For each query, output a line containing an integer — the answer to the query. The *i*-th line contains the answer to the *i*-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['6 3\n1 -2 3 4 0 -1\n1 2 1 2 1 1\n5 1\n-2 1\n1 0\n', '4 1\n-3 6 -1 2\n1 2 3 1\n1 -1\n'] Demo Output: ['20\n9\n4\n', '5\n'] Note: In the first example, to achieve the maximal value: - In the first query, you should select 1st, 3rd, and 4th ball. - In the second query, you should select 3rd, 4th, 5th and 6th ball. - In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value.
783
Title: Finding Team Member Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is a programing contest named SnakeUp, 2*n* people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct. Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people *A* and *B* may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate? Input Specification: There are 2*n* lines in the input. The first line contains an integer *n* (1<=≤<=*n*<=≤<=400) — the number of teams to be formed. The *i*-th line (*i*<=&gt;<=1) contains *i*<=-<=1 numbers *a**i*1, *a**i*2, ... , *a**i*(*i*<=-<=1). Here *a**ij* (1<=≤<=*a**ij*<=≤<=106, all *a**ij* are distinct) denotes the strength of a team consisting of person *i* and person *j* (people are numbered starting from 1.) Output Specification: Output a line containing 2*n* numbers. The *i*-th number should represent the number of teammate of *i*-th person. Demo Input: ['2\n6\n1 2\n3 4 5\n', '3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960\n'] Demo Output: ['2 1 4 3\n', '6 5 4 3 2 1\n'] Note: In the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
784
Title: Irrational problem Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Little Petya was given this problem for homework: You are given function (here represents the operation of taking the remainder). His task is to count the number of integers *x* in range [*a*;*b*] with property *f*(*x*)<==<=*x*. It is a pity that Petya forgot the order in which the remainders should be taken and wrote down only 4 numbers. Each of 24 possible orders of taking the remainder has equal probability of being chosen. For example, if Petya has numbers 1, 2, 3, 4 then he can take remainders in that order or first take remainder modulo 4, then modulo 2, 3, 1. There also are 22 other permutations of these numbers that represent orders in which remainder can be taken. In this problem 4 numbers wrote down by Petya will be pairwise distinct. Now it is impossible for Petya to complete the task given by teacher but just for fun he decided to find the number of integers with property that probability that *f*(*x*)<==<=*x* is not less than 31.4159265352718281828459045%. In other words, Petya will pick up the number *x* if there exist at least 7 permutations of numbers *p*1,<=*p*2,<=*p*3,<=*p*4, for which *f*(*x*)<==<=*x*. Input Specification: First line of the input will contain 6 integers, separated by spaces: *p*1,<=*p*2,<=*p*3,<=*p*4,<=*a*,<=*b* (1<=≤<=*p*1,<=*p*2,<=*p*3,<=*p*4<=≤<=1000,<=0<=≤<=*a*<=≤<=*b*<=≤<=31415). It is guaranteed that numbers *p*1,<=*p*2,<=*p*3,<=*p*4 will be pairwise distinct. Output Specification: Output the number of integers in the given range that have the given property. Demo Input: ['2 7 1 8 2 8\n', '20 30 40 50 0 100\n', '31 41 59 26 17 43\n'] Demo Output: ['0\n', '20\n', '9\n'] Note: none
785
Title: Photo Processing Time Limit: None seconds Memory Limit: None megabytes Problem Description: Evlampiy has found one more cool application to process photos. However the application has certain limitations. Each photo *i* has a contrast *v**i*. In order for the processing to be truly of high quality, the application must receive at least *k* photos with contrasts which differ as little as possible. Evlampiy already knows the contrast *v**i* for each of his *n* photos. Now he wants to split the photos into groups, so that each group contains at least *k* photos. As a result, each photo must belong to exactly one group. He considers a processing time of the *j*-th group to be the difference between the maximum and minimum values of *v**i* in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups. Split *n* photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=3·105) — number of photos and minimum size of a group. The second line contains *n* integers *v*1,<=*v*2,<=...,<=*v**n* (1<=≤<=*v**i*<=≤<=109), where *v**i* is the contrast of the *i*-th photo. Output Specification: Print the minimal processing time of the division into groups. Demo Input: ['5 2\n50 110 130 40 120\n', '4 1\n2 3 4 1\n'] Demo Output: ['20\n', '0\n'] Note: In the first example the photos should be split into 2 groups: [40, 50] and [110, 120, 130]. The processing time of the first group is 10, and the processing time of the second group is 20. Maximum among 10 and 20 is 20. It is impossible to split the photos into groups in a such way that the processing time of division is less than 20. In the second example the photos should be split into four groups, each containing one photo. So the minimal possible processing time of a division is 0.
786
Title: Soap Time! - 2 Time Limit: None seconds Memory Limit: None megabytes Problem Description: Imagine the Cartesian coordinate system. There are *k* different points containing subway stations. One can get from any subway station to any one instantly. That is, the duration of the transfer between any two subway stations can be considered equal to zero. You are allowed to travel only between subway stations, that is, you are not allowed to leave the subway somewhere in the middle of your path, in-between the stations. There are *n* dwarves, they are represented by their coordinates on the plane. The dwarves want to come together and watch a soap opera at some integer point on the plane. For that, they choose the gathering point and start moving towards it simultaneously. In one second a dwarf can move from point (*x*,<=*y*) to one of the following points: (*x*<=-<=1,<=*y*), (*x*<=+<=1,<=*y*), (*x*,<=*y*<=-<=1), (*x*,<=*y*<=+<=1). Besides, the dwarves can use the subway as many times as they want (the subway transfers the dwarves instantly). The dwarves do not interfere with each other as they move (that is, the dwarves move simultaneously and independently from each other). Help the dwarves and find the minimum time they need to gather at one point. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105; 0<=≤<=*k*<=≤<=105) — the number of dwarves and the number of subway stations, correspondingly. The next *n* lines contain the coordinates of the dwarves. The *i*-th line contains two space-separated integers *x**i* and *y**i* (|*x**i*|,<=|*y**i*|<=≤<=108) — the coordinates of the *i*-th dwarf. It is guaranteed that all dwarves are located at different points. The next *k* lines contain the coordinates of the subway stations. The *t*-th line contains two space-separated integers *x**t* and *y**t* (|*x**t*|,<=|*y**t*|<=≤<=108) — the coordinates of the *t*-th subway station. It is guaranteed that all subway stations are located at different points. Output Specification: Print a single number — the minimum time, in which all dwarves can gather together at one point to watch the soap. Demo Input: ['1 0\n2 -2\n', '2 2\n5 -3\n-4 -5\n-4 0\n-3 -2\n'] Demo Output: ['0\n', '6\n'] Note: none
787
Title: T-shirt Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are going to work in Codeforces as an intern in a team of *n* engineers, numbered 1 through *n*. You want to give each engineer a souvenir: a T-shirt from your country (T-shirts are highly desirable in Codeforces). Unfortunately you don't know the size of the T-shirt each engineer fits in. There are *m* different sizes, numbered 1 through *m*, and each engineer will fit in a T-shirt of exactly one size. You don't know the engineers' exact sizes, so you asked your friend, Gerald. Unfortunately, he wasn't able to obtain the exact sizes either, but he managed to obtain for each engineer *i* and for all sizes *j*, the probability that the size of the T-shirt that fits engineer *i* is *j*. Since you're planning to give each engineer one T-shirt, you are going to bring with you exactly *n* T-shirts. For those *n* T-shirts, you can bring any combination of sizes (you can bring multiple T-shirts with the same size too!). You don't know the sizes of T-shirts for each engineer when deciding what sizes to bring, so you have to pick this combination based only on the probabilities given by your friend, Gerald. Your task is to maximize the expected number of engineers that receive a T-shirt of his size. This is defined more formally as follows. When you finally arrive at the office, you will ask each engineer his T-shirt size. Then, if you still have a T-shirt of that size, you will give him one of them. Otherwise, you don't give him a T-shirt. You will ask the engineers in order starting from engineer 1, then engineer 2, and so on until engineer *n*. Input Specification: The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*<=≤<=3000,<=1<=≤<=*m*<=≤<=300), denoting the number of engineers and the number of T-shirt sizes, respectively. Then *n* lines follow, each line contains *m* space-separated integers. The *j*-th integer in the *i*-th line represents the probability that the *i*-th engineer fits in a T-shirt of size *j*. Each probability will be given as an integer between 0 and 1000, inclusive. The actual probability should be calculated as the given number divided by 1000. It is guaranteed that for any engineer, the sum of the probabilities for all *m* T-shirts is equal to one. Output Specification: Print a single real number denoting the maximum possible expected number of engineers that will receive a T-shirt. For the answer the absolute or relative error of 10<=-<=9 is acceptable. Demo Input: ['2 2\n500 500\n500 500\n', '3 3\n1000 0 0\n1000 0 0\n0 1000 0\n', '1 4\n100 200 300 400\n'] Demo Output: ['1.500000000000\n', '3.000000000000\n', '0.400000000000\n'] Note: For the first example, bring one T-shirt of each size. With 0.5 chance, either both engineers fit inside T-shirts of size 1 or both fit inside T-shirts of size 2. With the other 0.5 chance, one engineer fits inside a T-shirt of size 1 and the other inside a T-shirt of size 2. If the first is true, the number of engineers that receive a T-shirt is one. If the second is true, the number of such engineers is two. Hence, the expected number of engineers who receive a T-shirt is 1.5. This is maximum possible expected number of engineers for all sets of T-shirts. For the second example, bring two T-shirts of size 1 and one T-shirt of size 2. This way, each engineer will definitely receive a T-shirt of his size. For the third example, bring one T-shirt of size 4.
788
Title: Crazy Computer Time Limit: None seconds Memory Limit: None megabytes Problem Description: ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear! More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≤<=*c*, just the new word is appended to other words on the screen. If *b*<=-<=*a*<=&gt;<=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen. For example, if *c*<==<=5 and you typed words at seconds 1,<=3,<=8,<=14,<=19,<=20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen. You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything. Input Specification: The first line contains two integers *n* and *c* (1<=≤<=*n*<=≤<=100<=000,<=1<=≤<=*c*<=≤<=109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t*1<=&lt;<=*t*2<=&lt;<=...<=&lt;<=*t**n*<=≤<=109), where *t**i* denotes the second when ZS the Coder typed the *i*-th word. Output Specification: Print a single positive integer, the number of words that remain on the screen after all *n* words was typed, in other words, at the second *t**n*. Demo Input: ['6 5\n1 3 8 14 19 20\n', '6 1\n1 3 5 7 9 10\n'] Demo Output: ['3', '2'] Note: The first sample is already explained in the problem statement. For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
789
Title: Congruence Equation Time Limit: None seconds Memory Limit: None megabytes Problem Description: Given an integer $x$. Your task is to find out how many positive integers $n$ ($1 \leq n \leq x$) satisfy $$n \cdot a^n \equiv b \quad (\textrm{mod}\;p),$$ where $a, b, p$ are all known constants. Input Specification: The only line contains four integers $a,b,p,x$ ($2 \leq p \leq 10^6+3$, $1 \leq a,b &lt; p$, $1 \leq x \leq 10^{12}$). It is guaranteed that $p$ is a prime. Output Specification: Print a single integer: the number of possible answers $n$. Demo Input: ['2 3 5 8\n', '4 6 7 13\n', '233 233 10007 1\n'] Demo Output: ['2\n', '1\n', '1\n'] Note: In the first sample, we can see that $n=2$ and $n=8$ are possible answers.
790
Title: Berserk Robot Time Limit: None seconds Memory Limit: None megabytes Problem Description: Help! A robot escaped our lab and we need help finding it. The lab is at the point (0,<=0) of the coordinate plane, at time 0 the robot was there. The robot's movements are defined by a program — a string of length *l*, consisting of characters U, L, D, R. Each second the robot executes the next command in his program: if the current coordinates of the robot are (*x*,<=*y*), then commands U, L, D, R move it to cells (*x*,<=*y*<=+<=1), (*x*<=-<=1,<=*y*), (*x*,<=*y*<=-<=1), (*x*<=+<=1,<=*y*) respectively. The execution of the program started at time 0. The program is looped, i.e. each *l* seconds of executing the program start again from the first character. Unfortunately, we don't know what program was loaded into the robot when he left the lab. Our radars managed to find out the position of the robot at *n* moments of time: we know that at the moment of time *t**i* the robot is at the point (*x**i*,<=*y**i*). Given this data, either help to determine what program could be loaded into the robot, or determine that no possible program meets the data and the robot must have broken down. Input Specification: The first line of the input contains two space-separated integers *n* and *l* (1<=≤<=*n*<=≤<=2·105, 1<=≤<=*l*<=≤<=2·106). Next *n* lines contain three space-separated integers — *t**i*, *x**i*, *y**i* (1<=≤<=*t**i*<=≤<=1018, <=-<=1018<=≤<=*x**i*,<=*y**i*<=≤<=1018). The radar data is given chronologically, i.e. *t**i*<=&lt;<=*t**i*<=+<=1 for all *i* from 1 to *n*<=-<=1. Output Specification: Print any of the possible programs that meet the data. If no program meets the data, print a single word 'NO' (without the quotes). Demo Input: ['3 3\n1 1 0\n2 1 -1\n3 0 -1\n', '2 2\n1 1 0\n999 1 0\n', '2 5\n10 10 0\n20 0 0\n'] Demo Output: ['RDL\n', 'RL\n', 'NO\n'] Note: none
791
Title: Olya and Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: Olya has got a directed non-weighted graph, consisting of *n* vertexes and *m* edges. We will consider that the graph vertexes are indexed from 1 to *n* in some manner. Then for any graph edge that goes from vertex *v* to vertex *u* the following inequation holds: *v*<=&lt;<=*u*. Now Olya wonders, how many ways there are to add an arbitrary (possibly zero) number of edges to the graph so as the following conditions were met: 1. You can reach vertexes number *i*<=+<=1,<=*i*<=+<=2,<=...,<=*n* from any vertex number *i* (*i*<=&lt;<=*n*). 1. For any graph edge going from vertex *v* to vertex *u* the following inequation fulfills: *v*<=&lt;<=*u*. 1. There is at most one edge between any two vertexes. 1. The shortest distance between the pair of vertexes *i*,<=*j* (*i*<=&lt;<=*j*), for which *j*<=-<=*i*<=≤<=*k* holds, equals *j*<=-<=*i* edges. 1. The shortest distance between the pair of vertexes *i*,<=*j* (*i*<=&lt;<=*j*), for which *j*<=-<=*i*<=&gt;<=*k* holds, equals either *j*<=-<=*i* or *j*<=-<=*i*<=-<=*k* edges. We will consider two ways distinct, if there is the pair of vertexes *i*,<=*j* (*i*<=&lt;<=*j*), such that first resulting graph has an edge from *i* to *j* and the second one doesn't have it. Help Olya. As the required number of ways can be rather large, print it modulo 1000000007 (109<=+<=7). Input Specification: The first line contains three space-separated integers *n*,<=*m*,<=*k* (2<=≤<=*n*<=≤<=106,<=0<=≤<=*m*<=≤<=105,<=1<=≤<=*k*<=≤<=106). The next *m* lines contain the description of the edges of the initial graph. The *i*-th line contains a pair of space-separated integers *u**i*,<=*v**i* (1<=≤<=*u**i*<=&lt;<=*v**i*<=≤<=*n*) — the numbers of vertexes that have a directed edge from *u**i* to *v**i* between them. It is guaranteed that any pair of vertexes *u**i*,<=*v**i* has at most one edge between them. It also is guaranteed that the graph edges are given in the order of non-decreasing *u**i*. If there are multiple edges going from vertex *u**i*, then it is guaranteed that these edges are given in the order of increasing *v**i*. Output Specification: Print a single integer — the answer to the problem modulo 1000000007 (109<=+<=7). Demo Input: ['7 8 2\n1 2\n2 3\n3 4\n3 6\n4 5\n4 7\n5 6\n6 7\n', '7 0 2\n', '7 2 1\n1 3\n3 5\n'] Demo Output: ['2\n', '12\n', '0\n'] Note: In the first sample there are two ways: the first way is not to add anything, the second way is to add a single edge from vertex 2 to vertex 5.
792
Title: Strictly Positive Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have matrix *a* of size *n*<=×<=*n*. Let's number the rows of the matrix from 1 to *n* from top to bottom, let's number the columns from 1 to *n* from left to right. Let's use *a**ij* to represent the element on the intersection of the *i*-th row and the *j*-th column. Matrix *a* meets the following two conditions: - for any numbers *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) the following inequality holds: *a**ij*<=≥<=0; - . Matrix *b* is strictly positive, if for any numbers *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) the inequality *b**ij*<=&gt;<=0 holds. You task is to determine if there is such integer *k*<=≥<=1, that matrix *a**k* is strictly positive. Input Specification: The first line contains integer *n* (2<=≤<=*n*<=≤<=2000) — the number of rows and columns in matrix *a*. The next *n* lines contain the description of the rows of matrix *a*. The *i*-th line contains *n* non-negative integers *a**i*1,<=*a**i*2,<=...,<=*a**in* (0<=≤<=*a**ij*<=≤<=50). It is guaranteed that . Output Specification: If there is a positive integer *k*<=≥<=1, such that matrix *a**k* is strictly positive, print "YES" (without the quotes). Otherwise, print "NO" (without the quotes). Demo Input: ['2\n1 0\n0 1\n', '5\n4 5 6 1 2\n1 2 3 4 5\n6 4 1 2 4\n1 1 1 1 1\n4 4 4 4 4\n'] Demo Output: ['NO\n', 'YES\n'] Note: none
793
Title: Lomsat gelral Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour. Let's call colour *c* dominating in the subtree of vertex *v* if there are no other colours that appear in the subtree of vertex *v* more times than colour *c*. So it's possible that two or more colours will be dominating in the subtree of some vertex. The subtree of vertex *v* is the vertex *v* and all other vertices that contains vertex *v* in each path to the root. For each vertex *v* find the sum of all dominating colours in the subtree of vertex *v*. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of vertices in the tree. The second line contains *n* integers *c**i* (1<=≤<=*c**i*<=≤<=*n*), *c**i* — the colour of the *i*-th vertex. Each of the next *n*<=-<=1 lines contains two integers *x**j*,<=*y**j* (1<=≤<=*x**j*,<=*y**j*<=≤<=*n*) — the edge of the tree. The first vertex is the root of the tree. Output Specification: Print *n* integers — the sums of dominating colours for each vertex. Demo Input: ['4\n1 2 3 4\n1 2\n2 3\n2 4\n', '15\n1 2 3 1 2 3 3 1 1 3 2 2 1 2 3\n1 2\n1 3\n1 4\n1 14\n1 15\n2 5\n2 6\n2 7\n3 8\n3 9\n3 10\n4 11\n4 12\n4 13\n'] Demo Output: ['10 9 3 4\n', '6 5 4 3 2 3 3 1 1 3 2 2 1 2 3\n'] Note: none
794
Title: Mischievous Mess Makers Time Limit: None seconds Memory Limit: None megabytes Problem Description: It is a balmy spring afternoon, and Farmer John's *n* cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through *n*, are arranged so that the *i*-th cow occupies the *i*-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his *k* minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making no more than one swap each minute. Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the *k* minutes that they have. We denote as *p**i* the label of the cow in the *i*-th stall. The messiness of an arrangement of cows is defined as the number of pairs (*i*,<=*j*) such that *i*<=&lt;<=*j* and *p**i*<=&gt;<=*p**j*. Input Specification: The first line of the input contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100<=000) — the number of cows and the length of Farmer John's nap, respectively. Output Specification: Output a single integer, the maximum messiness that the Mischievous Mess Makers can achieve by performing no more than *k* swaps. Demo Input: ['5 2\n', '1 10\n'] Demo Output: ['10\n', '0\n'] Note: In the first sample, the Mischievous Mess Makers can swap the cows in the stalls 1 and 5 during the first minute, then the cows in stalls 2 and 4 during the second minute. This reverses the arrangement of cows, giving us a total messiness of 10. In the second sample, there is only one cow, so the maximum possible messiness is 0.
795
Title: Reverses Time Limit: None seconds Memory Limit: None megabytes Problem Description: Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse. You are given a string *s* — original state of your string and string *t* — state of the string after hurricane. You should select *k* non-intersecting substrings of *t* in such a way that after reverse of these substrings string will be equal *s* and *k* is minimum possible. Input Specification: First line of input contains string *s* and second line contains string *t*. Both strings have same length and consist of lowercase English letters. 1<=≤<=|*s*|<==<=|*t*|<=≤<=5·105 Output Specification: In first line print *k* — minimum number of substrings you should reverse. Next output *k* lines. Each line should contain two integers *l**i*, *r**i* meaning that you should reverse substring from symbol number *l**i* to symbol *r**i* (strings are 1-indexed). These substrings shouldn't intersect. If there are multiple answers print any. If it's impossible to restore string output -1. Demo Input: ['abcxxxdef\ncbaxxxfed\n'] Demo Output: ['2\n7 9\n1 3\n'] Note: none
796
Title: Valera and Fools Time Limit: None seconds Memory Limit: None megabytes Problem Description: One fine morning, *n* fools lined up in a row. After that, they numbered each other with numbers from 1 to *n*, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun. Every fool has exactly *k* bullets and a pistol. In addition, the fool number *i* has probability of *p**i* (in percent) that he kills the fool he shoots at. The fools decided to have several rounds of the fun. Each round of the fun looks like this: each currently living fool shoots at another living fool with the smallest number (a fool is not stupid enough to shoot at himself). All shots of the round are perfomed at one time (simultaneously). If there is exactly one living fool, he does not shoot. Let's define a situation as the set of numbers of all the living fools at the some time. We say that a situation is possible if for some integer number *j* (0<=≤<=*j*<=≤<=*k*) there is a nonzero probability that after *j* rounds of the fun this situation will occur. Valera knows numbers *p*1,<=*p*2,<=...,<=*p**n* and *k*. Help Valera determine the number of distinct possible situations. Input Specification: The first line contains two integers *n*,<=*k* (1<=≤<=*n*,<=*k*<=≤<=3000) — the initial number of fools and the number of bullets for each fool. The second line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* (0<=≤<=*p**i*<=≤<=100) — the given probabilities (in percent). Output Specification: Print a single number — the answer to the problem. Demo Input: ['3 3\n50 50 50\n', '1 1\n100\n', '2 1\n100 100\n', '3 3\n0 0 0\n'] Demo Output: ['7\n', '1\n', '2\n', '1\n'] Note: In the first sample, any situation is possible, except for situation {1, 2}. In the second sample there is exactly one fool, so he does not make shots. In the third sample the possible situations are {1, 2} (after zero rounds) and the "empty" situation {} (after one round). In the fourth sample, the only possible situation is {1, 2, 3}.
797
Title: Icicles Time Limit: None seconds Memory Limit: None megabytes Problem Description: Andrew's favourite Krakozyabra has recenly fled away and now he's eager to bring it back! At the moment the refugee is inside an icy cave with *n* icicles dangling from the ceiling located in integer coordinates numbered from 1 to *n*. The distance between floor and the *i*-th icicle is equal to *a**i*. Andrew is free to choose an arbitrary integer point *T* in range from 1 to *n* inclusive and at time instant 0 launch a sound wave spreading into both sides (left and right) at the speed of one point per second. Any icicle touched by the wave starts falling at the same speed (that means that in a second the distance from floor to icicle decreases by one but cannot become less that zero). While distance from icicle to floor is more than zero, it is considered passable; as soon as it becomes zero, the icicle blocks the path and prohibits passing. Krakozyabra is initially (i.e. at time instant 0) is located at point and starts running in the right direction at the speed of one point per second. You can assume that events in a single second happen in the following order: first Krakozyabra changes its position, and only then the sound spreads and icicles fall; in particular, that means that if Krakozyabra is currently at point and the falling (i.e. already touched by the sound wave) icicle at point *i* is 1 point from the floor, then Krakozyabra will pass it and find itself at and only after that the icicle will finally fall and block the path. Krakozyabra is considered entrapped if there are fallen (i.e. with *a**i*<==<=0) icicles both to the left and to the right of its current position. Help Andrew find the minimum possible time it takes to entrap Krakozyabra by choosing the optimal value of *T* or report that this mission is impossible. Input Specification: The first line contains the number of icicles *n* (2<=≤<=*n*<=≤<=105). The next line contains *n* space-separated numbers *a**i* (1<=≤<=*a**i*<=≤<=105) — the distances from floor to icicles. Output Specification: Print an only integer — the minimum time it takes to entrap Krakozyabra between two fallen icicles. If it is impossible, print <=-<=1. Demo Input: ['5\n1 4 3 5 1\n', '4\n1 2 1 1\n', '2\n2 1\n', '2\n1 2\n'] Demo Output: ['3\n', '2\n', '3\n', '-1\n'] Note: In sample case one it's optimal to launch the sound wave from point 3. Then in two seconds icicles 1 and 5 will start falling, and in one more seconds they will block the paths. Krakozyabra will be located at <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/36de0b98a41a7a3c26317908808c214e6d4ac3ff.png" style="max-width: 100.0%;max-height: 100.0%;"/> at that time. Note that icicle number 3 will also be fallen, so there will actually be two icicles blocking the path to the left. In sample case two it is optimal to launch the wave from point 2 and entrap Krakozyabra in 2 seconds. In sample case four the answer is impossible.
798
Title: Cyclic Coloring Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a directed graph *G* with *n* vertices and *m* arcs (multiple arcs and self-loops are allowed). You have to paint each vertex of the graph into one of the *k* (*k*<=≤<=*n*) colors in such way that for all arcs of the graph leading from a vertex *u* to vertex *v*, vertex *v* is painted with the next color of the color used to paint vertex *u*. The colors are numbered cyclically 1 through *k*. This means that for each color *i* (*i*<=&lt;<=*k*) its next color is color *i*<=+<=1. In addition, the next color of color *k* is color 1. Note, that if *k*<==<=1, then the next color for color 1 is again color 1. Your task is to find and print the largest possible value of *k* (*k*<=≤<=*n*) such that it's possible to color *G* as described above with *k* colors. Note that you don't necessarily use all the *k* colors (that is, for each color *i* there does not necessarily exist a vertex that is colored with color *i*). Input Specification: The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105), denoting the number of vertices and the number of arcs of the given digraph, respectively. Then *m* lines follow, each line will contain two space-separated integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*), which means that the *i*-th arc goes from vertex *a**i* to vertex *b**i*. Multiple arcs and self-loops are allowed. Output Specification: Print a single integer — the maximum possible number of the colors that can be used to paint the digraph (i.e. *k*, as described in the problem statement). Note that the desired value of *k* must satisfy the inequality 1<=≤<=*k*<=≤<=*n*. Demo Input: ['4 4\n1 2\n2 1\n3 4\n4 3\n', '5 2\n1 4\n2 5\n', '4 5\n1 2\n2 3\n3 1\n2 4\n4 1\n', '4 4\n1 1\n1 2\n2 1\n1 2\n'] Demo Output: ['2\n', '5\n', '3\n', '1\n'] Note: For the first example, with *k* = 2, this picture depicts the two colors (arrows denote the next color of that color). With *k* = 2 a possible way to paint the graph is as follows. It can be proven that no larger value for *k* exists for this test case. For the second example, here's the picture of the *k* = 5 colors. A possible coloring of the graph is: For the third example, here's the picture of the *k* = 3 colors. A possible coloring of the graph is:
799