task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: Paint it really, really dark gray Time Limit: None seconds Memory Limit: None megabytes Problem Description: I see a pink boar and I want it painted black. Black boars look much more awesome and mighty than the pink ones. Since Jaggy became the ruler of the forest, he has been trying his best to improve the diplomatic relations between the forest region and the nearby ones. Some other rulers, however, have requested too much in return for peace between their two regions, so he realized he has to resort to intimidation. Once a delegate for diplomatic relations of a neighboring region visits Jaggy’s forest, if they see a whole bunch of black boars, they might suddenly change their mind about attacking Jaggy. Black boars are really scary, after all. Jaggy’s forest can be represented as a tree (connected graph without cycles) with *n* vertices. Each vertex represents a boar and is colored either black or pink. Jaggy has sent a squirrel to travel through the forest and paint all the boars black. The squirrel, however, is quite unusually trained and while it traverses the graph, it changes the color of every vertex it visits, regardless of its initial color: pink vertices become black and black vertices become pink. Since Jaggy is too busy to plan the squirrel’s route, he needs your help. He wants you to construct a walk through the tree starting from vertex 1 such that in the end all vertices are black. A walk is a sequence of vertices, such that every consecutive pair has an edge between them in a tree. Input Specification: The first line of input contains integer *n* (2<=≀<=*n*<=≀<=200<=000), denoting the number of vertices in the tree. The following *n* lines contains *n* integers, which represent the color of the nodes. If the *i*-th integer is 1, if the *i*-th vertex is black and <=-<=1 if the *i*-th vertex is pink. Each of the next *n*<=-<=1 lines contains two integers, which represent the indexes of the vertices which are connected by the edge. Vertices are numbered starting with 1. Output Specification: Output path of a squirrel: output a sequence of visited nodes' indexes in order of visiting. In case of all the nodes are initially black, you should print 1. Solution is guaranteed to exist. If there are multiple solutions to the problem you can output any of them provided length of sequence is not longer than 107. Demo Input: ['5\n1\n1\n-1\n1\n-1\n2 5\n4 3\n2 4\n4 1\n'] Demo Output: ['1 4 2 5 2 4 3 4 1 4 1\n'] Note: At the beginning squirrel is at node 1 and its color is black. Next steps are as follows: - From node 1 we walk to node 4 and change its color to pink. - From node 4 we walk to node 2 and change its color to pink. - From node 2 we walk to node 5 and change its color to black. - From node 5 we return to node 2 and change its color to black. - From node 2 we walk to node 4 and change its color to black. - We visit node 3 and change its color to black. - We visit node 4 and change its color to pink. - We visit node 1 and change its color to pink. - We visit node 4 and change its color to black. - We visit node 1 and change its color to black.
1,600
Title: Weird journey Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherlandΒ β€” Uzhlyandia. It is widely known that Uzhlyandia has *n* cities connected with *m* bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over *m*<=-<=2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help IgorΒ β€” calculate the number of good paths. Input Specification: The first line contains two integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=106)Β β€” the number of cities and roads in Uzhlyandia, respectively. Each of the next *m* lines contains two integers *u* and *v* (1<=≀<=*u*,<=*v*<=≀<=*n*) that mean that there is road between cities *u* and *v*. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Specification: Print out the only integerΒ β€” the number of good paths in Uzhlyandia. Demo Input: ['5 4\n1 2\n1 3\n1 4\n1 5\n', '5 3\n1 2\n2 3\n4 5\n', '2 2\n1 1\n1 2\n'] Demo Output: ['6', '0', '1'] Note: In first sample test case the good paths are: - 2 → 1 → 3 → 1 → 4 → 1 → 5, - 2 → 1 → 3 → 1 → 5 → 1 → 4, - 2 → 1 → 4 → 1 → 5 → 1 → 3, - 3 → 1 → 2 → 1 → 4 → 1 → 5, - 3 → 1 → 2 → 1 → 5 → 1 → 4, - 4 → 1 → 2 → 1 → 3 → 1 → 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: - 2 → 1 → 4 → 1 → 3 → 1 → 5, - 2 → 1 → 5 → 1 → 3 → 1 → 4, - 2 → 1 → 5 → 1 → 4 → 1 → 3, - 3 → 1 → 4 → 1 → 2 → 1 → 5, - 3 → 1 → 5 → 1 → 2 → 1 → 4, - 4 → 1 → 3 → 1 → 2 → 1 → 5, - and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road.
1,601
Title: Yet Another Number Sequence Time Limit: None seconds Memory Limit: None megabytes Problem Description: Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation: We'll define a new number sequence *A**i*(*k*) by the formula: In this problem, your task is to calculate the following sum: *A*1(*k*)<=+<=*A*2(*k*)<=+<=...<=+<=*A**n*(*k*). The answer can be very large, so print it modulo 1000000007 (109<=+<=7). Input Specification: The first line contains two space-separated integers *n*, *k* (1<=≀<=*n*<=≀<=1017;Β 1<=≀<=*k*<=≀<=40). Output Specification: Print a single integer β€” the sum of the first *n* elements of the sequence *A**i*(*k*) modulo 1000000007 (109<=+<=7). Demo Input: ['1 1\n', '4 1\n', '5 2\n', '7 4\n'] Demo Output: ['1\n', '34\n', '316\n', '73825\n'] Note: none
1,602
Title: Lucky Sum Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let *next*(*x*) be the minimum lucky number which is larger than or equals *x*. Petya is interested what is the value of the expression *next*(*l*)<=+<=*next*(*l*<=+<=1)<=+<=...<=+<=*next*(*r*<=-<=1)<=+<=*next*(*r*). Help him solve this problem. Input Specification: The single line contains two integers *l* and *r* (1<=≀<=*l*<=≀<=*r*<=≀<=109) β€” the left and right interval limits. Output Specification: In the single line print the only number β€” the sum *next*(*l*)<=+<=*next*(*l*<=+<=1)<=+<=...<=+<=*next*(*r*<=-<=1)<=+<=*next*(*r*). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Demo Input: ['2 7\n', '7 7\n'] Demo Output: ['33\n', '7\n'] Note: In the first sample: *next*(2) + *next*(3) + *next*(4) + *next*(5) + *next*(6) + *next*(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: *next*(7) = 7
1,603
Title: Industrial Nim Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: There are *n* stone quarries in Petrograd. Each quarry owns *m**i* dumpers (1<=≀<=*i*<=≀<=*n*). It is known that the first dumper of the *i*-th quarry has *x**i* stones in it, the second dumper has *x**i*<=+<=1 stones in it, the third has *x**i*<=+<=2, and the *m**i*-th dumper (the last for the *i*-th quarry) has *x**i*<=+<=*m**i*<=-<=1 stones in it. Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses. Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone Β«tolikΒ» and the other one Β«bolikΒ». Input Specification: The first line of the input contains one integer number *n* (1<=≀<=*n*<=≀<=105) β€” the amount of quarries. Then there follow *n* lines, each of them contains two space-separated integers *x**i* and *m**i* (1<=≀<=*x**i*,<=*m**i*<=≀<=1016) β€” the amount of stones in the first dumper of the *i*-th quarry and the number of dumpers at the *i*-th quarry. Output Specification: Output Β«tolikΒ» if the oligarch who takes a stone first wins, and Β«bolikΒ» otherwise. Demo Input: ['2\n2 1\n3 2\n', '4\n1 1\n1 1\n1 1\n1 1\n'] Demo Output: ['tolik\n', 'bolik\n'] Note: none
1,604
Title: Relay Race Time Limit: None seconds Memory Limit: None megabytes Problem Description: Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of *n* meters. The given square is split into *n*<=Γ—<=*n* cells (represented as unit squares), each cell has some number. At the beginning of the race Furik stands in a cell with coordinates (1,<=1), and Rubik stands in a cell with coordinates (*n*,<=*n*). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (*i*,<=*j*), then he can move to cell (*i*<=+<=1,<=*j*) or (*i*,<=*j*<=+<=1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (*n*,<=*n*) to cell with coordinates (1,<=1). If Rubik stands in cell (*i*,<=*j*), then he can move to cell (*i*<=-<=1,<=*j*) or (*i*,<=*j*<=-<=1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum. Print the maximum number of points Furik and Rubik can earn on the relay race. Input Specification: The first line contains a single integer (1<=≀<=*n*<=≀<=300). The next *n* lines contain *n* integers each: the *j*-th number on the *i*-th line *a**i*,<=*j* (<=-<=1000<=≀<=*a**i*,<=*j*<=≀<=1000) is the number written in the cell with coordinates (*i*,<=*j*). Output Specification: On a single line print a single number β€” the answer to the problem. Demo Input: ['1\n5\n', '2\n11 14\n16 12\n', '3\n25 16 25\n12 18 19\n11 13 8\n'] Demo Output: ['5\n', '53\n', '136\n'] Note: Comments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample:
1,605
Title: Make a Square Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros. Determine the minimum number of operations that you need to consistently apply to the given integer $n$ to make from it the square of some positive integer or report that it is impossible. An integer $x$ is the square of some positive integer if and only if $x=y^2$ for some positive integer $y$. Input Specification: The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{9}$). The number is given without leading zeroes. Output Specification: If it is impossible to make the square of some positive integer from $n$, print -1. In the other case, print the minimal number of operations required to do it. Demo Input: ['8314\n', '625\n', '333\n'] Demo Output: ['2\n', '0\n', '-1\n'] Note: In the first example we should delete from $8314$ the digits $3$ and $4$. After that $8314$ become equals to $81$, which is the square of the integer $9$. In the second example the given $625$ is the square of the integer $25$, so you should not delete anything. In the third example it is impossible to make the square from $333$, so the answer is -1.
1,606
Title: Brand New Easy Problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β€” a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept. You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs. You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words. The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as , where *n* is the number of words in Lesha's problem and *x* is the number of inversions in the chosen permutation. Note that the "similarity" *p* is always a positive integer. The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence. Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=4) β€” the number of words in Lesha's problem. The second line contains *n* space-separated words β€” the short description of the problem. The third line contains a single integer *m* (1<=≀<=*m*<=≀<=10) β€” the number of problems in the Torcoder.com archive. Next *m* lines contain the descriptions of the problems as "*k* *s*1 *s*2 ... *s**k*", where *k* (1<=≀<=*k*<=≀<=20) is the number of words in the problem and *s**i* is a word of the problem description. All words from all problem descriptions contain no more than 10 lowercase English letters. Output Specification: If Lesha's problem is brand new, print string "Brand new problem!" (without quotes). Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated *p* times, and characters :], where *p* is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input. Demo Input: ['4\nfind the next palindrome\n1\n10 find the previous palindrome or print better luck next time\n', '3\nadd two numbers\n3\n1 add\n2 two two\n3 numbers numbers numbers\n', '4\nthese papers are formulas\n3\n6 what are these formulas and papers\n5 papers are driving me crazy\n4 crazy into the night\n', '3\nadd two decimals\n5\n4 please two decimals add\n5 decimals want to be added\n4 two add decimals add\n4 add one two three\n7 one plus two plus three equals six\n'] Demo Output: ['1\n[:||||||:]\n', 'Brand new problem!\n', '1\n[:||||:]\n', '3\n[:|||:]\n'] Note: Let us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions β€” pairs of words "numbers" and "add", "numbers" and "two". Sequence *b*<sub class="lower-index">1</sub>,  *b*<sub class="lower-index">2</sub>,  ...,  *b*<sub class="lower-index">*k*</sub> is a subsequence of sequence *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>,  ...,  *a*<sub class="lower-index">*n*</sub> if there exists such a set of indices 1 ≀ *i*<sub class="lower-index">1</sub> &lt;  *i*<sub class="lower-index">2</sub> &lt; ...   &lt; *i*<sub class="lower-index">*k*</sub> ≀ *n* that *a*<sub class="lower-index">*i*<sub class="lower-index">*j*</sub></sub>  =  *b*<sub class="lower-index">*j*</sub> (in other words, if sequence *b* can be obtained from *a* by deleting some of its elements). In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next"). In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence.
1,607
Title: Labyrinth-10 Time Limit: None seconds Memory Limit: None megabytes Problem Description: See the problem statement here: [http://codeforces.com/contest/921/problem/01](//codeforces.com/contest/921/problem/01). Input Specification: none Output Specification: none Note: none
1,608
Title: Lucky Tickets Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: In Walrusland public transport tickets are characterized by two integers: by the number of the series and by the number of the ticket in the series. Let the series number be represented by *a* and the ticket number β€” by *b*, then a ticket is described by the ordered pair of numbers (*a*,<=*b*). The walruses believe that a ticket is lucky if *a*<=*<=*b*<==<=*rev*(*a*)<=*<=*rev*(*b*). The function *rev*(*x*) reverses a number written in the decimal system, at that the leading zeroes disappear. For example, *rev*(12343)<==<=34321, *rev*(1200)<==<=21. The Public Transport Management Committee wants to release *x* series, each containing *y* tickets, so that at least *w* lucky tickets were released and the total number of released tickets (*x*<=*<=*y*) were minimum. The series are numbered from 1 to *x* inclusive. The tickets in each series are numbered from 1 to *y* inclusive. The Transport Committee cannot release more than *max**x* series and more than *max**y* tickets in one series. Input Specification: The first line contains three integers *max**x*, *max**y*, *w* (1<=≀<=*max**x*,<=*max**y*<=≀<=105, 1<=≀<=*w*<=≀<=107). Output Specification: Print on a single line two space-separated numbers, the *x* and the *y*. If there are several possible variants, print any of them. If such *x* and *y* do not exist, print a single number <=-<=1. Demo Input: ['2 2 1\n', '132 10 35\n', '5 18 1000\n', '48 132 235\n'] Demo Output: ['1 1', '7 5', '-1\n', '22 111'] Note: none
1,609
Title: New Year Transportation Time Limit: None seconds Memory Limit: None megabytes Problem Description: New Year is coming in Line World! In this world, there are *n* cells numbered by integers from 1 to *n*, as a 1<=Γ—<=*n* board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells. So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of *n*<=-<=1 positive integers *a*1,<=*a*2,<=...,<=*a**n*<=-<=1. For every integer *i* where 1<=≀<=*i*<=≀<=*n*<=-<=1 the condition 1<=≀<=*a**i*<=≀<=*n*<=-<=*i* holds. Next, he made *n*<=-<=1 portals, numbered by integers from 1 to *n*<=-<=1. The *i*-th (1<=≀<=*i*<=≀<=*n*<=-<=1) portal connects cell *i* and cell (*i*<=+<=*a**i*), and one can travel from cell *i* to cell (*i*<=+<=*a**i*) using the *i*-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (*i*<=+<=*a**i*) to cell *i* using the *i*-th portal. It is easy to see that because of condition 1<=≀<=*a**i*<=≀<=*n*<=-<=*i* one can't leave the Line World using portals. Currently, I am standing at cell 1, and I want to go to cell *t*. However, I don't know whether it is possible to go there. Please determine whether I can go to cell *t* by only using the construted transportation system. Input Specification: The first line contains two space-separated integers *n* (3<=≀<=*n*<=≀<=3<=Γ—<=104) and *t* (2<=≀<=*t*<=≀<=*n*) β€” the number of cells, and the index of the cell which I want to go to. The second line contains *n*<=-<=1 space-separated integers *a*1,<=*a*2,<=...,<=*a**n*<=-<=1 (1<=≀<=*a**i*<=≀<=*n*<=-<=*i*). It is guaranteed, that using the given transportation system, one cannot leave the Line World. Output Specification: If I can go to cell *t* using the transportation system, print "YES". Otherwise, print "NO". Demo Input: ['8 4\n1 2 1 2 1 2 1\n', '8 5\n1 2 1 2 1 1 1\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4. In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
1,610
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Santa Claus likes palindromes very much. There was his birthday recently. *k* of his friends came to him to congratulate him, and each of them presented to him a string *s**i* having the same length *n*. We denote the beauty of the *i*-th string by *a**i*. It can happen that *a**i* is negativeΒ β€” that means that Santa doesn't find this string beautiful at all. Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length *n*. Recall that a palindrome is a string that doesn't change after one reverses it. Since the empty string is a palindrome too, the answer can't be negative. Even if all *a**i*'s are negative, Santa can obtain the empty string. Input Specification: The first line contains two positive integers *k* and *n* divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1<=≀<=*k*,<=*n*<=≀<=100<=000; *n*Β·*k*Β <=≀<=100<=000). *k* lines follow. The *i*-th of them contains the string *s**i* and its beauty *a**i* (<=-<=10<=000<=≀<=*a**i*<=≀<=10<=000). The string consists of *n* lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties. Output Specification: In the only line print the required maximum possible beauty. Demo Input: ['7 3\nabb 2\naaa -3\nbba -1\nzyz -4\nabb 5\naaa 7\nxyx 4\n', '3 1\na 1\na 2\na 3\n', '2 5\nabcde 10000\nabcde 10000\n'] Demo Output: ['12\n', '6\n', '0\n'] Note: In the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order).
1,611
Title: DZY Loves Strings Time Limit: None seconds Memory Limit: None megabytes Problem Description: DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where Now DZY has a string *s*. He wants to insert *k* lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get? Input Specification: The first line contains a single string *s*Β (1<=≀<=|*s*|<=≀<=103). The second line contains a single integer *k*Β (0<=≀<=*k*<=≀<=103). The third line contains twenty-six integers from *w**a* to *w**z*. Each such number is non-negative and doesn't exceed 1000. Output Specification: Print a single integer β€” the largest possible value of the resulting string DZY could get. Demo Input: ['abc\n3\n1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n'] Demo Output: ['41\n'] Note: In the test sample DZY can obtain "abcbbc", *value* = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
1,612
Title: Restore Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: Valera had an undirected connected graph without self-loops and multiple edges consisting of *n* vertices. The graph had an interesting property: there were at most *k* edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to *n*. One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array *d*. Thus, element *d*[*i*] of the array shows the shortest distance from the vertex Valera chose to vertex number *i*. Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array *d*. Help him restore the lost graph. Input Specification: The first line contains two space-separated integers *n* and *k* (1<=≀<=*k*<=&lt;<=*n*<=≀<=105). Number *n* shows the number of vertices in the original graph. Number *k* shows that at most *k* edges were adjacent to each vertex in the original graph. The second line contains space-separated integers *d*[1],<=*d*[2],<=...,<=*d*[*n*] (0<=≀<=*d*[*i*]<=&lt;<=*n*). Number *d*[*i*] shows the shortest distance from the vertex Valera chose to the vertex number *i*. Output Specification: If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer *m* (0<=≀<=*m*<=≀<=106) β€” the number of edges in the found graph. In each of the next *m* lines print two space-separated integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*;Β *a**i*<=β‰ <=*b**i*), denoting the edge that connects vertices with numbers *a**i* and *b**i*. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them. Demo Input: ['3 2\n0 1 1\n', '4 2\n2 0 1 3\n', '3 1\n0 0 0\n'] Demo Output: ['3\n1 2\n1 3\n3 2\n', '3\n1 3\n1 4\n2 3\n', '-1\n'] Note: none
1,613
Title: Opening Portals Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pavel plays a famous computer game. A player is responsible for a whole country and he can travel there freely, complete quests and earn experience. This country has *n* cities connected by *m* bidirectional roads of different lengths so that it is possible to get from any city to any other one. There are portals in *k* of these cities. At the beginning of the game all portals are closed. When a player visits a portal city, the portal opens. Strange as it is, one can teleport from an open portal to an open one. The teleportation takes no time and that enables the player to travel quickly between rather remote regions of the country. At the beginning of the game Pavel is in city number 1. He wants to open all portals as quickly as possible. How much time will he need for that? Input Specification: The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*<=≀<=105, 0<=≀<=*m*<=≀<=105) that show how many cities and roads are in the game. Each of the next *m* lines contains the description of a road as three space-separated integers *x**i*, *y**i*, *w**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*, *x**i*<=β‰ <=*y**i*, 1<=≀<=*w**i*<=≀<=109) β€” the numbers of the cities connected by the *i*-th road and the time needed to go from one city to the other one by this road. Any two cities are connected by no more than one road. It is guaranteed that we can get from any city to any other one, moving along the roads of the country. The next line contains integer *k* (1<=≀<=*k*<=≀<=*n*) β€” the number of portals. The next line contains *k* space-separated integers *p*1, *p*2, ..., *p**k* β€” numbers of the cities with installed portals. Each city has no more than one portal. Output Specification: Print a single number β€” the minimum time a player needs to open all portals. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['3 3\n1 2 1\n1 3 1\n2 3 1\n3\n1 2 3\n', '4 3\n1 2 1\n2 3 5\n2 4 10\n3\n2 3 4\n', '4 3\n1 2 1000000000\n2 3 1000000000\n3 4 1000000000\n4\n1 2 3 4\n'] Demo Output: ['2\n', '16\n', '3000000000\n'] Note: In the second sample the player has to come to city 2, open a portal there, then go to city 3, open a portal there, teleport back to city 2 and finally finish the journey in city 4.
1,614
Title: Colorful Stones Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are two sequences of colorful stones. The color of each stone is one of red, green, or blue. You are given two strings *s* and *t*. The *i*-th (1-based) character of *s* represents the color of the *i*-th stone of the first sequence. Similarly, the *i*-th (1-based) character of *t* represents the color of the *i*-th stone of the second sequence. 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 of the first sequence and Cat Vasya is standing on the first stone of the second sequence. You can perform the following instructions zero or more times. Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction *c*, the animals standing on stones whose colors are *c* will move one stone forward. For example, if you perform an instruction Β«REDΒ», the animals standing on red stones will move one stone forward. You are not allowed to perform instructions that lead some animals out of the sequences. In other words, if some animals are standing on the last stones, you can't perform the instructions of the colors of those stones. A pair of positions (position of Liss, position of Vasya) is called a state. A state is called reachable if the state is reachable by performing instructions zero or more times from the initial state (1, 1). Calculate the number of distinct reachable states. Input Specification: The input contains two lines. The first line contains the string *s* (1<=≀<=|*s*|<=≀<=106). The second line contains the string *t* (1<=≀<=|*t*|<=≀<=106). The characters of each string will be one of "R", "G", or "B". Output Specification: Print the number of distinct reachable states in a single line. 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: ['RBR\nRGG\n', 'RGBB\nBRRBRR\n', 'RRRRRRRRRR\nRRRRRRRR\n'] Demo Output: ['5\n', '19\n', '8\n'] Note: In the first example, there are five reachable states: (1, 1), (2, 2), (2, 3), (3, 2), and (3, 3). For example, the state (3, 3) is reachable because if you perform instructions "RED", "GREEN", and "BLUE" in this order from the initial state, the state will be (3, 3). The following picture shows how the instructions work in this case.
1,615
Title: Vladik and Courtesy Time Limit: None seconds Memory Limit: None megabytes Problem Description: At regular competition Vladik and Valera won *a* and *b* candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each other one candy more than they received in the previous turn. This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy. Input Specification: Single line of input data contains two space-separated integers *a*, *b* (1<=≀<=*a*,<=*b*<=≀<=109) β€” number of Vladik and Valera candies respectively. Output Specification: Pring a single line "Vladik’’ in case, if Vladik first who can’t give right amount of candy, or "Valera’’ otherwise. Demo Input: ['1 1\n', '7 6\n'] Demo Output: ['Valera\n', 'Vladik\n'] Note: Illustration for first test case: <img class="tex-graphics" src="https://espresso.codeforces.com/ad9b7d0e481208de8e3a585aa1d96b9e1dda4fd7.png" style="max-width: 100.0%;max-height: 100.0%;"/> Illustration for second test case: <img class="tex-graphics" src="https://espresso.codeforces.com/9f4836d2ccdffaee5a63898e5d4e6caf2ed4678c.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,616
Title: Jzzhu and Cities Time Limit: None seconds Memory Limit: None megabytes Problem Description: Jzzhu is the president of country A. There are *n* cities numbered from 1 to *n* in his country. City 1 is the capital of A. Also there are *m* roads connecting the cities. One can go from city *u**i* to *v**i* (and vise versa) using the *i*-th road, the length of this road is *x**i*. Finally, there are *k* train routes in the country. One can use the *i*-th train route to go from capital of the country to city *s**i* (and vise versa), the length of this route is *y**i*. Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. Input Specification: The first line contains three integers *n*,<=*m*,<=*k* (2<=≀<=*n*<=≀<=105;Β 1<=≀<=*m*<=≀<=3Β·105;Β 1<=≀<=*k*<=≀<=105). Each of the next *m* lines contains three integers *u**i*,<=*v**i*,<=*x**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*;Β *u**i*<=β‰ <=*v**i*;Β 1<=≀<=*x**i*<=≀<=109). Each of the next *k* lines contains two integers *s**i* and *y**i* (2<=≀<=*s**i*<=≀<=*n*;Β 1<=≀<=*y**i*<=≀<=109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. Output Specification: Output a single integer representing the maximum number of the train routes which can be closed. Demo Input: ['5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5\n', '2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3\n'] Demo Output: ['2\n', '2\n'] Note: none
1,617
Title: Greed Time Limit: None seconds Memory Limit: None megabytes Problem Description: Jafar has *n* cans of cola. Each can is described by two integers: remaining volume of cola *a**i* and can's capacity *b**i* (*a**i* <=≀<= *b**i*). Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not! Input Specification: The first line of the input contains one integer *n* (2<=≀<=*n*<=≀<=100<=000)Β β€” number of cola cans. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109) β€” volume of remaining cola in cans. The third line contains *n* space-separated integers that *b*1,<=*b*2,<=...,<=*b**n* (*a**i*<=≀<=*b**i*<=≀<=109) β€” capacities of the cans. Output Specification: Print "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower). Demo Input: ['2\n3 5\n3 6\n', '3\n6 8 9\n6 10 12\n', '5\n0 0 5 0 0\n1 1 8 10 5\n', '4\n4 1 0 3\n5 2 2 3\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n', 'YES\n'] Note: In the first sample, there are already 2 cans, so the answer is "YES".
1,618
Title: Karen and Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with *n* rows and *m* columns. Each cell originally contains the number 0. One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column. To win the level, after all the moves, the number in the cell at the *i*-th row and *j*-th column should be equal to *g**i*,<=*j*. Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! Input Specification: The first line of input contains two integers, *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100), the number of rows and the number of columns in the grid, respectively. The next *n* lines each contain *m* integers. In particular, the *j*-th integer in the *i*-th of these rows contains *g**i*,<=*j* (0<=≀<=*g**i*,<=*j*<=≀<=500). Output Specification: If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer *k*, the minimum number of moves necessary to beat the level. The next *k* lines should each contain one of the following, describing the moves in the order they must be done: - row *x*, (1<=≀<=*x*<=≀<=*n*) describing a move of the form "choose the *x*-th row". - col *x*, (1<=≀<=*x*<=≀<=*m*) describing a move of the form "choose the *x*-th column". If there are multiple optimal solutions, output any one of them. Demo Input: ['3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1\n', '3 3\n0 0 0\n0 1 0\n0 0 0\n', '3 3\n1 1 1\n1 1 1\n1 1 1\n'] Demo Output: ['4\nrow 1\nrow 1\ncol 4\nrow 3\n', '-1\n', '3\nrow 1\nrow 2\nrow 3\n'] Note: In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center. In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.
1,619
Title: Substring Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a graph with $n$ nodes and $m$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $3$. Your task is find a path whose value is the largest. Input Specification: The first line contains two positive integers $n, m$ ($1 \leq n, m \leq 300\,000$), denoting that the graph has $n$ nodes and $m$ directed edges. The second line contains a string $s$ with only lowercase English letters. The $i$-th character is the letter assigned to the $i$-th node. Then $m$ lines follow. Each line contains two integers $x, y$ ($1 \leq x, y \leq n$), describing a directed edge from $x$ to $y$. Note that $x$ can be equal to $y$ and there can be multiple edges between $x$ and $y$. Also the graph can be not connected. Output Specification: Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead. Demo Input: ['5 4\nabaca\n1 2\n1 3\n3 4\n4 5\n', '6 6\nxzyabc\n1 2\n3 1\n2 3\n5 4\n4 3\n6 4\n', '10 14\nxzyzyzyzqx\n1 2\n2 4\n3 5\n4 5\n2 6\n6 8\n6 5\n2 10\n3 9\n10 9\n4 6\n1 10\n2 8\n3 7\n'] Demo Output: ['3\n', '-1\n', '4\n'] Note: In the first sample, the path with largest value is $1 \to 3 \to 4 \to 5$. The value is $3$ because the letter 'a' appears $3$ times.
1,620
Title: Transferring Pyramid Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya and Petya are using an interesting data storing structure: a pyramid. The pyramid consists of *n* rows, the *i*-th row contains *i* cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to as shown on the picture below. An example of a pyramid at *n*<==<=5 is: This data structure can perform operations of two types: 1. Change the value of a specific cell. It is described by three integers: "*t* *i* *v*", where *t*<==<=1 (the type of operation), *i* β€” the number of the cell to change and *v* the value to assign to the cell. 1. Change the value of some subpyramid. The picture shows a highlighted subpyramid with the top in cell 5. It is described by *s*<=+<=2 numbers: "*t* *i* *v*1 *v*2 ... *v**s*", where *t*<==<=2, *i* β€” the number of the top cell of the pyramid, *s* β€” the size of the subpyramid (the number of cells it has), *v**j* β€” the value you should assign to the *j*-th cell of the subpyramid. Formally: a subpyramid with top at the *i*-th cell of the *k*-th row (the 5-th cell is the second cell of the third row) will contain cells from rows from *k* to *n*, the (*k*<=+<=*p*)-th row contains cells from the *i*-th to the (*i*<=+<=*p*)-th (0<=≀<=*p*<=≀<=*n*<=-<=*k*). Vasya and Petya had two identical pyramids. Vasya changed some cells in his pyramid and he now wants to send his changes to Petya. For that, he wants to find a sequence of operations at which Petya can repeat all Vasya's changes. Among all possible sequences, Vasya has to pick the minimum one (the one that contains the fewest numbers). You have a pyramid of *n* rows with *k* changed cells. Find the sequence of operations which result in each of the *k* changed cells being changed by at least one operation. Among all the possible sequences pick the one that contains the fewest numbers. Input Specification: The first line contains two integers *n* and *k* (1<=≀<=*n*,<=*k*<=≀<=105). The next *k* lines contain the coordinates of the modified cells *r**i* and *c**i* (1<=≀<=*c**i*<=≀<=*r**i*<=≀<=*n*) β€” the row and the cell's number in the row. All cells are distinct. Output Specification: Print a single number showing how many numbers the final sequence has. Demo Input: ['4 5\n3 1\n3 3\n4 1\n4 3\n4 4\n', '7 11\n2 2\n3 1\n4 3\n5 1\n5 2\n5 5\n6 4\n7 2\n7 3\n7 4\n7 5\n'] Demo Output: ['10\n', '26\n'] Note: One of the possible solutions of the first sample consists of two operations: 2 4 *v*<sub class="lower-index">4</sub> *v*<sub class="lower-index">7</sub> *v*<sub class="lower-index">8</sub> 2 6 *v*<sub class="lower-index">6</sub> *v*<sub class="lower-index">9</sub> *v*<sub class="lower-index">10</sub> The picture shows the changed cells color-highlighted. The subpyramid used by the first operation is highlighted blue and the subpyramid used by the first operation is highlighted yellow:
1,621
Title: Mother of Dragons Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself. Sir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has *k* liters of a strange liquid. He wants to distribute that liquid among the castles, so each castle may contain some liquid (possibly zero or non-integer number of liters). After that the stability of a wall is defined as follows: if the wall connects two castles *a* and *b*, and they contain *x* and *y* liters of that liquid, respectively, then the strength of that wall is *x*Β·*y*. Your task is to print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve. Input Specification: The first line of the input contains two integers *n* and *k* (1<=≀<=*n*<=≀<=40, 1<=≀<=*k*<=≀<=1000). Then *n* lines follows. The *i*-th of these lines contains *n* integers *a**i*,<=1,<=*a**i*,<=2,<=...,<=*a**i*,<=*n* (). If castles *i* and *j* are connected by a wall, then *a**i*,<=*j*<==<=1. Otherwise it is equal to 0. It is guaranteed that *a**i*,<=*j*<==<=*a**j*,<=*i* and *a**i*,<=*i*<==<=0 for all 1<=≀<=*i*,<=*j*<=≀<=*n*. Output Specification: Print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve. 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 1\n0 1 0\n1 0 0\n0 0 0\n', '4 4\n0 1 0 1\n1 0 1 0\n0 1 0 1\n1 0 1 0\n'] Demo Output: ['0.250000000000\n', '4.000000000000\n'] Note: In the first sample, we can assign 0.5, 0.5, 0 liters of liquid to castles 1, 2, 3, respectively, to get the maximum sum (0.25). In the second sample, we can assign 1.0, 1.0, 1.0, 1.0 liters of liquid to castles 1, 2, 3, 4, respectively, to get the maximum sum (4.0)
1,622
Title: Cola Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: To celebrate the opening of the Winter Computer School the organizers decided to buy in *n* liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly *a* bottles 0.5 in volume, *b* one-liter bottles and *c* of two-liter ones. The organizers have enough money to buy any amount of cola. What did cause the heated arguments was how many bottles of every kind to buy, as this question is pivotal for the distribution of cola among the participants (and organizers as well). Thus, while the organizers are having the argument, discussing different variants of buying cola, the Winter School can't start. Your task is to count the number of all the possible ways to buy exactly *n* liters of cola and persuade the organizers that this number is too large, and if they keep on arguing, then the Winter Computer School will have to be organized in summer. All the bottles of cola are considered indistinguishable, i.e. two variants of buying are different from each other only if they differ in the number of bottles of at least one kind. Input Specification: The first line contains four integers β€” *n*, *a*, *b*, *c* (1<=≀<=*n*<=≀<=10000, 0<=≀<=*a*,<=*b*,<=*c*<=≀<=5000). Output Specification: Print the unique number β€” the solution to the problem. If it is impossible to buy exactly *n* liters of cola, print 0. Demo Input: ['10 5 5 5\n', '3 0 0 2\n'] Demo Output: ['9\n', '0\n'] Note: none
1,623
Title: Roland and Rose Time Limit: None seconds Memory Limit: None megabytes Problem Description: Roland loves growing flowers. He has recently grown a beautiful rose at point (0,<=0) of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it. To protect the rose, Roland wants to build *n* watch towers. Let's assume that a tower is a point on the plane at the distance of at most *r* from the rose. Besides, Roland assumes that the towers should be built at points with integer coordinates and the sum of squares of distances between all pairs of towers must be as large as possible. Note, that Roland may build several towers at the same point, also he may build some of them at point (0,<=0). Help Roland build the towers at the integer points so that the sum of squares of distances between all towers is maximum possible. Note that the distance in this problem is defined as the Euclidian distance between points. Input Specification: The first line contains two integers, *n* and *r* (2<=≀<=*n*<=≀<=8;Β 1<=≀<=*r*<=≀<=30). Output Specification: In the first line print an integer β€” the maximum possible sum of squared distances. In the *i*-th of the following *n* lines print two integers, *x**i*,<=*y**i* β€” the coordinates of the *i*-th tower. Each tower must be inside or on the border of the circle with radius *r*. Note that there may be several towers located at the same point of the plane, also some towers can be located at point (0,<=0). If there are multiple valid optimal arrangements, choose any of them. Demo Input: ['4 1\n', '3 6\n'] Demo Output: ['16\n0 1\n0 1\n0 -1\n0 -1\n', '312\n0 6\n5 -3\n-5 -3\n'] Note: none
1,624
Title: Fox And Two Dots Time Limit: None seconds Memory Limit: None megabytes Problem Description: Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size *n*<=Γ—<=*m* cells, like this: Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors. The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots *d*1,<=*d*2,<=...,<=*d**k* a cycle if and only if it meets the following condition: 1. These *k* dots are different: if *i*<=β‰ <=*j* then *d**i* is different from *d**j*. 1. *k* is at least 4. 1. All dots belong to the same color. 1. For all 1<=≀<=*i*<=≀<=*k*<=-<=1: *d**i* and *d**i*<=+<=1 are adjacent. Also, *d**k* and *d*1 should also be adjacent. Cells *x* and *y* are called adjacent if they share an edge. Determine if there exists a cycle on the field. Input Specification: The first line contains two integers *n* and *m* (2<=≀<=*n*,<=*m*<=≀<=50): the number of rows and columns of the board. Then *n* lines follow, each line contains a string consisting of *m* characters, expressing colors of dots in each line. Each character is an uppercase Latin letter. Output Specification: Output "Yes" if there exists a cycle, and "No" otherwise. Demo Input: ['3 4\nAAAA\nABCA\nAAAA\n', '3 4\nAAAA\nABCA\nAADA\n', '4 4\nYYYR\nBYBY\nBBBY\nBBBY\n', '7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB\n', '2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ\n'] Demo Output: ['Yes\n', 'No\n', 'Yes\n', 'Yes\n', 'No\n'] Note: In first sample test all 'A' form a cycle. In second sample there is no such cycle. The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
1,625
Title: Byteland coins Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* types of coins in Byteland. Conveniently, the denomination of the coin type *k* divides the denomination of the coin type *k*<=+<=1, the denomination of the coin type 1 equals 1 tugrick. The ratio of the denominations of coin types *k*<=+<=1 and *k* equals *a**k*. It is known that for each *x* there are at most 20 coin types of denomination *x*. Byteasar has *b**k* coins of type *k* with him, and he needs to pay exactly *m* tugricks. It is known that Byteasar never has more than 3Β·105 coins with him. Byteasar want to know how many ways there are to pay exactly *m* tugricks. Two ways are different if there is an integer *k* such that the amount of coins of type *k* differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo 109<=+<=7. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=3Β·105)Β β€” the number of coin types. The second line contains *n*<=-<=1 integers *a*1, *a*2, ..., *a**n*<=-<=1 (1<=≀<=*a**k*<=≀<=109)Β β€” the ratios between the coin types denominations. It is guaranteed that for each *x* there are at most 20 coin types of denomination *x*. The third line contains *n* non-negative integers *b*1, *b*2, ..., *b**n*Β β€” the number of coins of each type Byteasar has. It is guaranteed that the sum of these integers doesn't exceed 3Β·105. The fourth line contains single integer *m* (0<=≀<=*m*<=&lt;<=1010000)Β β€” the amount in tugricks Byteasar needs to pay. Output Specification: Print single integerΒ β€” the number of ways to pay exactly *m* tugricks modulo 109<=+<=7. Demo Input: ['1\n\n4\n2\n', '2\n1\n4 4\n2\n', '3\n3 3\n10 10 10\n17\n'] Demo Output: ['1\n', '3\n', '6\n'] Note: In the first example Byteasar has 4 coins of denomination 1, and he has to pay 2 tugricks. There is only one way. In the second example Byteasar has 4 coins of each of two different types of denomination 1, he has to pay 2 tugricks. There are 3 ways: pay one coin of the first type and one coin of the other, pay two coins of the first type, and pay two coins of the second type. In the third example the denominations are equal to 1, 3, 9.
1,626
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side length equal to 2*k* (*k* is an integer, *k*<=β‰₯<=0) units. A magical box *v* can be put inside a magical box *u*, if side length of *v* is strictly less than the side length of *u*. In particular, Emuskald can put 4 boxes of side length 2*k*<=-<=1 into one box of side length 2*k*, or as in the following figure: Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes. Input Specification: The first line of input contains an integer *n* (1<=≀<=*n*<=≀<=105), the number of different sizes of boxes Emuskald has. Each of following *n* lines contains two integers *k**i* and *a**i* (0<=≀<=*k**i*<=≀<=109, 1<=≀<=*a**i*<=≀<=109), which means that Emuskald has *a**i* boxes with side length 2*k**i*. It is guaranteed that all of *k**i* are distinct. Output Specification: Output a single integer *p*, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2*p*. Demo Input: ['2\n0 3\n1 5\n', '1\n0 4\n', '2\n1 10\n2 2\n'] Demo Output: ['3\n', '1\n', '3\n'] Note: Picture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture. In the second test case, we can put all four small boxes into a box with side length 2.
1,627
Title: Sereja and Squares Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sereja painted *n* points on the plane, point number *i* (1<=≀<=*i*<=≀<=*n*) has coordinates (*i*,<=0). Then Sereja marked each point with a small or large English letter. Sereja don't like letter "x", so he didn't use it to mark points. Sereja thinks that the points are marked beautifully if the following conditions holds: - all points can be divided into pairs so that each point will belong to exactly one pair; - in each pair the point with the lesser abscissa will be marked with a small English letter and the point with the larger abscissa will be marked with the same large English letter; - if we built a square on each pair, the pair's points will be the square's opposite points and the segment between them will be the square's diagonal, then among the resulting squares there won't be any intersecting or touching ones. Little Petya erased some small and all large letters marking the points. Now Sereja wonders how many ways are there to return the removed letters so that the points were marked beautifully. Input Specification: The first line contains integer *n* the number of points (1<=≀<=*n*<=≀<=105). The second line contains a sequence consisting of *n* small English letters and question marks β€” the sequence of letters, that mark points, in order of increasing *x*-coordinate of points. Question marks denote the points without letters (Petya erased them). It is guaranteed that the input string doesn't contain letter "x". Output Specification: In a single line print the answer to the problem modulo 4294967296. If there is no way to return the removed letters, print number 0. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['4\na???\n', '4\nabc?\n', '6\nabc???\n'] Demo Output: ['50\n', '0\n', '1\n'] Note: none
1,628
Title: My pretty girl Noora Time Limit: None seconds Memory Limit: None megabytes Problem Description: In Pavlopolis University where Noora studies it was decided to hold beauty contest "Miss Pavlopolis University". Let's describe the process of choosing the most beautiful girl in the university in more detail. The contest is held in several stages. Suppose that exactly *n* girls participate in the competition initially. All the participants are divided into equal groups, *x* participants in each group. Furthermore the number *x* is chosen arbitrarily, i. e. on every stage number *x* can be different. Within each group the jury of the contest compares beauty of the girls in the format "each with each". In this way, if group consists of *x* girls, then comparisons occur. Then, from each group, the most beautiful participant is selected. Selected girls enter the next stage of the competition. Thus if *n* girls were divided into groups, *x* participants in each group, then exactly participants will enter the next stage. The contest continues until there is exactly one girl left who will be "Miss Pavlopolis University" But for the jury this contest is a very tedious task. They would like to divide the girls into groups in each stage so that the total number of pairwise comparisons of the girls is as few as possible. Let *f*(*n*) be the minimal total number of comparisons that should be made to select the most beautiful participant, if we admit *n* girls to the first stage. The organizers of the competition are insane. They give Noora three integers *t*, *l* and *r* and ask the poor girl to calculate the value of the following expression: *t*0Β·*f*(*l*)<=+<=*t*1Β·*f*(*l*<=+<=1)<=+<=...<=+<=*t**r*<=-<=*l*Β·*f*(*r*). However, since the value of this expression can be quite large the organizers ask her to calculate it modulo 109<=+<=7. If Noora can calculate the value of this expression the organizers promise her to help during the beauty contest. But the poor girl is not strong in mathematics, so she turned for help to Leha and he turned to you. Input Specification: The first and single line contains three integers *t*, *l* and *r* (1<=≀<=*t*<=&lt;<=109<=+<=7,<=2<=≀<=*l*<=≀<=*r*<=≀<=5Β·106). Output Specification: In the first line print single integer β€” the value of the expression modulo 109<=+<=7. Demo Input: ['2 2 4\n'] Demo Output: ['19\n'] Note: Consider the sample. It is necessary to find the value of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3ecc798906ae9e9852061ba2dd5cf6b8fce7753b.png" style="max-width: 100.0%;max-height: 100.0%;"/>. *f*(2) = 1. From two girls you can form only one group of two people, in which there will be one comparison. *f*(3) = 3. From three girls you can form only one group of three people, in which there will be three comparisons. *f*(4) = 3. From four girls you can form two groups of two girls each. Then at the first stage there will be two comparisons, one in each of the two groups. In the second stage there will be two girls and there will be one comparison between them. Total 2 + 1 = 3 comparisons. You can also leave all girls in same group in the first stage. Then <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/fcc6c9e72a1525cc01abbfb89094669a9d37d3b1.png" style="max-width: 100.0%;max-height: 100.0%;"/> comparisons will occur. Obviously, it's better to split girls into groups in the first way. Then the value of the expression is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2c5a0f75c9d910ec77b2fe675e690de453060631.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
1,629
Title: Quasi-palindrome Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String *t* is called a palindrome, if it reads the same from left to right and from right to left. For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes. You are given some integer number *x*. Check if it's a quasi-palindromic number. Input Specification: The first line contains one integer number *x* (1<=≀<=*x*<=≀<=109). This number is given without any leading zeroes. Output Specification: Print "YES" if number *x* is quasi-palindromic. Otherwise, print "NO" (without quotes). Demo Input: ['131\n', '320\n', '2010200\n'] Demo Output: ['YES\n', 'NO\n', 'YES\n'] Note: none
1,630
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring *s*[*l*... *r*] (1<=≀<=*l*<=≀<=*r*<=≀<=|*s*|) of string *s*<==<=*s*1*s*2... *s*|*s*| (where |*s*| is the length of string *s*) is the string *s**l**s**l*<=+<=1... *s**r*. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets Β«[Β» as possible. Input Specification: The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output Specification: In the first line print a single integer β€” the number of brackets Β«[Β» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Demo Input: ['([])\n', '(((\n'] Demo Output: ['1\n([])\n', '0\n\n'] Note: none
1,631
Title: Vacuum Π‘leaner Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: One winter evening the Hedgehog was relaxing at home in his cozy armchair and clicking through the TV channels. Stumbled on an issue of Β«TopShopΒ», the Hedgehog was about to change the channel when all of a sudden he was stopped by an advertisement of a new wondrous invention. Actually, a vacuum cleaner was advertised there. It was called Marvellous Vacuum and it doesn't even need a human to operate it while it cleans! The vacuum cleaner can move around the flat on its own: it moves in some direction and if it hits an obstacle there, it automatically chooses a new direction. Sooner or later this vacuum cleaner will travel through all the room and clean it all. Having remembered how much time the Hedgehog spends every time on cleaning (surely, no less than a half of the day), he got eager to buy this wonder. However, the Hedgehog quickly understood that the cleaner has at least one weak point: it won't clean well in the room's corners because it often won't able to reach the corner due to its shape. To estimate how serious is this drawback in practice, the Hedgehog asked you to write for him the corresponding program. You will be given the cleaner's shape in the top view. We will consider only the cases when the vacuum cleaner is represented as a convex polygon. The room is some infinitely large rectangle. We consider one corner of this room and want to find such a rotation of the vacuum cleaner so that it, being pushed into this corner, will leave the minimum possible area in the corner uncovered. Input Specification: The first line contains an integer *N* which represents the number of vertices of the vacuum cleaner's polygon (3<=≀<=*N*<=≀<=4Β·104). Then follow *N* lines each containing two numbers β€” the coordinates of a vertex of the polygon. All the coordinates are integer and their absolute values do not exceed 106. It is guaranteed that the given polygon is nondegenerate and convex (no three points lie on the same line). The polygon vertices are given in a clockwise or counter-clockwise direction. Output Specification: Print the minimum possible uncovered area. The answer will be accepted if it is within 10<=-<=6 of absolute or relative error from the correct answer. Demo Input: ['4\n0 0\n1 0\n1 1\n0 1\n', '8\n1 2\n2 1\n2 -1\n1 -2\n-1 -2\n-2 -1\n-2 1\n-1 2\n'] Demo Output: ['0.00000000000000000000', '0.50000000000000000000'] Note: none
1,632
Title: Funky Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as , where *k* is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers. A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number *n*, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)! Input Specification: The first input line contains an integer *n* (1<=≀<=*n*<=≀<=109). Output Specification: Print "YES" (without the quotes), if *n* can be represented as a sum of two triangular numbers, otherwise print "NO" (without the quotes). Demo Input: ['256\n', '512\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample number <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/92095692c6ea93e9e3b837a0408ba7543549d5b2.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample number 512 can not be represented as a sum of two triangular numbers.
1,633
Title: Mister B and Flight to the Moon Time Limit: None seconds Memory Limit: None megabytes Problem Description: In order to fly to the Moon Mister B just needs to solve the following problem. There is a complete indirected graph with *n* vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles. We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you? Input Specification: The only line contains single integer *n* (3<=≀<=*n*<=≀<=300). Output Specification: If there is no answer, print -1. Otherwise, in the first line print *k* (1<=≀<=*k*<=≀<=*n*2)Β β€” the number of cycles in your solution. In each of the next *k* lines print description of one cycle in the following format: first print integer *m* (3<=≀<=*m*<=≀<=4)Β β€” the length of the cycle, then print *m* integers *v*1,<=*v*2,<=...,<=*v**m* (1<=≀<=*v**i*<=≀<=*n*)Β β€” the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles. Demo Input: ['3\n', '5\n'] Demo Output: ['2\n3 1 2 3\n3 1 2 3\n', '6\n3 5 4 2\n3 3 1 5\n4 4 5 2 3\n4 4 3 2 1\n3 4 2 1\n3 3 1 5\n'] Note: none
1,634
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $4$ rows and $n$ ($n \le 50$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $k$ ($k \le 2n$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $20000$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. Input Specification: The first line of the input contains two space-separated integers $n$ and $k$ ($1 \le n \le 50$, $1 \le k \le 2n$), representing the number of columns and the number of cars, respectively. The next four lines will contain $n$ integers each between $0$ and $k$ inclusive, representing the initial state of the parking lot. The rows are numbered $1$ to $4$ from top to bottom and the columns are numbered $1$ to $n$ from left to right. In the first and last line, an integer $1 \le x \le k$ represents a parking spot assigned to car $x$ (you can only move this car to this place), while the integer $0$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $1 \le x \le k$ represents initial position of car $x$, while the integer $0$ represents an empty space (you can move any car to this place). Each $x$ between $1$ and $k$ appears exactly once in the second and third line, and exactly once in the first and fourth line. Output Specification: If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $20000$ car moves, then print $m$, the number of moves, on the first line. On the following $m$ lines, print the moves (one move per line) in the format $i$ $r$ $c$, which corresponds to Allen moving car $i$ to the neighboring space at row $r$ and column $c$. If it is not possible for Allen to move all the cars to the correct spaces with at most $20000$ car moves, print a single line with the integer $-1$. Demo Input: ['4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3\n', '1 2\n1\n2\n1\n2\n', '1 2\n1\n1\n2\n2\n'] Demo Output: ['6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2\n', '-1\n', '2\n1 1 1\n2 4 1\n'] Note: In the first sample test case, all cars are in front of their spots except car $5$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $20000$ will be accepted. In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
1,635
Title: Leha and another game about graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: Leha plays a computer game, where is on each level is given a connected graph with *n* vertices and *m* edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer *d**i*, which can be equal to 0, 1 or <=-<=1. To pass the level, he needs to find a Β«goodΒ» subset of edges of the graph or say, that it doesn't exist. Subset is called Β«goodΒ», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, *d**i*<==<=<=-<=1 or it's degree modulo 2 is equal to *d**i*. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input Specification: The first line contains two integers *n*, *m* (1<=≀<=*n*<=≀<=3Β·105, *n*<=-<=1<=≀<=*m*<=≀<=3Β·105) β€” number of vertices and edges. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (<=-<=1<=≀<=*d**i*<=≀<=1) β€” numbers on the vertices. Each of the next *m* lines contains two integers *u* and *v* (1<=≀<=*u*,<=*v*<=≀<=*n*) β€” edges. It's guaranteed, that graph in the input is connected. Output Specification: Print <=-<=1 in a single line, if solution doesn't exist. Otherwise in the first line *k* β€” number of edges in a subset. In the next *k* lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Demo Input: ['1 0\n1\n', '4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4\n', '2 1\n1 1\n1 2\n', '3 3\n0 -1 1\n1 2\n2 3\n1 3\n'] Demo Output: ['-1\n', '0\n', '1\n1\n', '1\n2\n'] Note: In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
1,636
Title: Array Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of *n*, containing only integers from 1 to *n*. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions: - each elements, starting from the second one, is no more than the preceding one - each element, starting from the second one, is no less than the preceding one Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last. Input Specification: The single line contains an integer *n* which is the size of the array (1<=≀<=*n*<=≀<=105). Output Specification: You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007. Demo Input: ['2\n', '3\n'] Demo Output: ['4\n', '17\n'] Note: none
1,637
Title: Moon Craters Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: There are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes. An extraterrestrial intelligence research specialist professor Okulov (the namesake of the Okulov, the author of famous textbooks on programming) put forward an alternate hypothesis. Guess what kind of a hypothesis it was –– sure, the one including extraterrestrial mind involvement. Now the professor is looking for proofs of his hypothesis. Professor has data from the moon robot that moves linearly in one direction along the Moon surface. The moon craters are circular in form with integer-valued radii. The moon robot records only the craters whose centers lay on his path and sends to the Earth the information on the distance from the centers of the craters to the initial point of its path and on the radii of the craters. According to the theory of professor Okulov two craters made by an extraterrestrial intelligence for the aims yet unknown either are fully enclosed one in the other or do not intersect at all. Internal or external tangency is acceptable. However the experimental data from the moon robot do not confirm this theory! Nevertheless, professor Okulov is hopeful. He perfectly understands that to create any logical theory one has to ignore some data that are wrong due to faulty measuring (or skillful disguise by the extraterrestrial intelligence that will be sooner or later found by professor Okulov!) That’s why Okulov wants to choose among the available crater descriptions the largest set that would satisfy his theory. Input Specification: The first line has an integer *n* (1<=≀<=*n*<=≀<=2000) β€” the number of discovered craters. The next *n* lines contain crater descriptions in the "*c**i* *r**i*" format, where *c**i* is the coordinate of the center of the crater on the moon robot’s path, *r**i* is the radius of the crater. All the numbers *c**i* and *r**i* are positive integers not exceeding 109. No two craters coincide. Output Specification: In the first line output the number of craters in the required largest set. In the next line output space-separated numbers of craters that this set consists of. The craters are numbered from 1 to *n* in the order in which they were given in the input data. The numbers may be output in any order. If the result is not unique, output any. Demo Input: ['4\n1 1\n2 2\n4 1\n5 1\n'] Demo Output: ['3\n1 2 4\n'] Note: none
1,638
Title: Infinity Gauntlet Time Limit: None seconds Memory Limit: None megabytes Problem Description: You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: - the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems. Input Specification: In the first line of input there is one integer $n$ ($0 \le n \le 6$)Β β€” the number of Gems in Infinity Gauntlet. In next $n$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters. Output Specification: In the first line output one integer $m$ ($0 \le m \le 6$)Β β€” the number of absent Gems. Then in $m$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase. Demo Input: ['4\nred\npurple\nyellow\norange\n', '0\n'] Demo Output: ['2\nSpace\nTime\n', '6\nTime\nMind\nSoul\nPower\nReality\nSpace\n'] Note: In the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space. In the second sample Thanos doesn't have any Gems, so he needs all six.
1,639
Title: Cows and Primitive Roots Time Limit: None seconds Memory Limit: None megabytes Problem Description: The cows have just learned what a primitive root is! Given a prime *p*, a primitive root is an integer *x* (1<=≀<=*x*<=&lt;<=*p*) such that none of integers *x*<=-<=1,<=*x*2<=-<=1,<=...,<=*x**p*<=-<=2<=-<=1 are divisible by *p*, but *x**p*<=-<=1<=-<=1 is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime *p*, help the cows find the number of primitive roots . Input Specification: The input contains a single line containing an integer *p* (2<=≀<=*p*<=&lt;<=2000). It is guaranteed that *p* is a prime. Output Specification: Output on a single line the number of primitive roots . Demo Input: ['3\n', '5\n'] Demo Output: ['1\n', '2\n'] Note: The only primitive root <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3722298ba062e95b18705d1253eb4e5d31e3b2d1.png" style="max-width: 100.0%;max-height: 100.0%;"/> is 2. The primitive roots <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1d85c6a17ef1c42b53cf94d00bc49a7ac458fd58.png" style="max-width: 100.0%;max-height: 100.0%;"/> are 2 and 3.
1,640
Title: Polycarp's phone book Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct. There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: - if he enters 00 two numbers will show up: 100000000 and 100123456, - if he enters 123 two numbers will show up 123456789 and 100123456, - if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=70000) β€” the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct. Output Specification: Print exactly *n* lines: the *i*-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the *i*-th number from the contacts. If there are several such sequences, print any of them. Demo Input: ['3\n123456789\n100000000\n100123456\n', '4\n123456789\n193456789\n134567819\n934567891\n'] Demo Output: ['9\n000\n01\n', '2\n193\n81\n91\n'] Note: none
1,641
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1. Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers. Given this information, is it possible to restore the exact floor for flat *n*? Input Specification: The first line contains two integers *n* and *m* (1<=≀<=*n*<=≀<=100, 0<=≀<=*m*<=≀<=100), where *n* is the number of the flat you need to restore floor for, and *m* is the number of flats in Polycarp's memory. *m* lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers *k**i*,<=*f**i* (1<=≀<=*k**i*<=≀<=100, 1<=≀<=*f**i*<=≀<=100), which means that the flat *k**i* is on the *f**i*-th floor. All values *k**i* are distinct. It is guaranteed that the given information is not self-contradictory. Output Specification: Print the number of the floor in which the *n*-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor. Demo Input: ['10 3\n6 2\n2 1\n7 3\n', '8 4\n3 1\n6 2\n5 2\n2 1\n'] Demo Output: ['4\n', '-1\n'] Note: In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor. In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
1,642
Title: Random Task Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer *n*, that among numbers *n*<=+<=1, *n*<=+<=2, ..., 2Β·*n* there are exactly *m* numbers which binary representation contains exactly *k* digits one". The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018. Input Specification: The first line contains two space-separated integers, *m* and *k* (0<=≀<=*m*<=≀<=1018; 1<=≀<=*k*<=≀<=64). Output Specification: Print the required number *n* (1<=≀<=*n*<=≀<=1018). If there are multiple answers, print any of them. Demo Input: ['1 1\n', '3 2\n'] Demo Output: ['1\n', '5\n'] Note: none
1,643
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor. There are *n* citizens in Kekoland, each person has *c**i* coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in *k* days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after *k* days. Note that the choosing at random among richest and poorest doesn't affect the answer. Input Specification: The first line of the input contains two integers *n* and *k* (1<=≀<=*n*<=≀<=500<=000,<=0<=≀<=*k*<=≀<=109)Β β€” the number of citizens in Kekoland and the number of days left till Robin Hood's retirement. The second line contains *n* integers, the *i*-th of them is *c**i* (1<=≀<=*c**i*<=≀<=109)Β β€” initial wealth of the *i*-th person. Output Specification: Print a single line containing the difference between richest and poorest peoples wealth. Demo Input: ['4 1\n1 1 4 2\n', '3 1\n2 2 2\n'] Demo Output: ['2\n', '0\n'] Note: Lets look at how wealth changes through day in the first sample. 1. [1, 1, 4, 2] 1. [2, 1, 3, 2] or [1, 2, 3, 2] So the answer is 3 - 1 = 2 In second sample wealth will remain the same for each person.
1,644
Title: Alyona and a tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alyona has a tree with *n* vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex *i* she wrote *a**i*. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges). Let's define *dist*(*v*,<=*u*) as the sum of the integers written on the edges of the simple path from *v* to *u*. The vertex *v* controls the vertex *u* (*v*<=β‰ <=*u*) if and only if *u* is in the subtree of *v* and *dist*(*v*,<=*u*)<=≀<=*a**u*. Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex *v* what is the number of vertices *u* such that *v* controls *u*. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=2Β·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109)Β β€” the integers written in the vertices. The next (*n*<=-<=1) lines contain two integers each. The *i*-th of these lines contains integers *p**i* and *w**i* (1<=≀<=*p**i*<=≀<=*n*, 1<=≀<=*w**i*<=≀<=109)Β β€” the parent of the (*i*<=+<=1)-th vertex in the tree and the number written on the edge between *p**i* and (*i*<=+<=1). It is guaranteed that the given graph is a tree. Output Specification: Print *n* integersΒ β€” the *i*-th of these numbers should be equal to the number of vertices that the *i*-th vertex controls. Demo Input: ['5\n2 5 1 4 6\n1 7\n1 1\n3 5\n3 6\n', '5\n9 7 8 6 5\n1 1\n2 1\n3 1\n4 1\n'] Demo Output: ['1 0 1 0 0\n', '4 3 2 1 0\n'] Note: In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
1,645
Title: Launch of Collider Time Limit: None seconds Memory Limit: None megabytes Problem Description: There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, *x**i* is the coordinate of the *i*-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers. You know the direction of each particle movementΒ β€” it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time. Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point. Input Specification: The first line contains the positive integer *n* (1<=≀<=*n*<=≀<=200<=000)Β β€” the number of particles. The second line contains *n* symbols "L" and "R". If the *i*-th symbol equals "L", then the *i*-th particle will move to the left, otherwise the *i*-th symbol equals "R" and the *i*-th particle will move to the right. The third line contains the sequence of pairwise distinct even integers *x*1,<=*x*2,<=...,<=*x**n* (0<=≀<=*x**i*<=≀<=109)Β β€” the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order. Output Specification: In the first line print the only integerΒ β€” the first moment (in microseconds) when two particles are at the same point and there will be an explosion. Print the only integer -1, if the collision of particles doesn't happen. Demo Input: ['4\nRLRL\n2 4 6 10\n', '3\nLLR\n40 50 60\n'] Demo Output: ['1\n', '-1\n'] Note: In the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3. In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point.
1,646
Title: Valera and X Time Limit: None seconds Memory Limit: None megabytes Problem Description: Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet. Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if: - on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him. Input Specification: The first line contains integer *n* (3<=≀<=*n*<=&lt;<=300; *n* is odd). Each of the next *n* lines contains *n* small English letters β€” the description of Valera's paper. Output Specification: Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes. Demo Input: ['5\nxooox\noxoxo\nsoxoo\noxoxo\nxooox\n', '3\nwsw\nsws\nwsw\n', '3\nxpx\npxp\nxpe\n'] Demo Output: ['NO\n', 'YES\n', 'NO\n'] Note: none
1,647
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Instructors of Some Informatics School make students go to bed. The house contains *n* rooms, in each room exactly *b* students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to *n*. Initially, in *i*-th room there are *a**i* students. All students are currently somewhere in the house, therefore *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*. Also 2 instructors live in this house. The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room *n*, while the second instructor starts near room *n* and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if *n* is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends. When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to *b*, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students. While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most *d* rooms, that is she can move to a room with number that differs my at most *d*. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously. Formally, here is what's happening: - A curfew is announced, at this point in room *i* there are *a**i* students. - Each student can run to another room but not further than *d* rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed. - Instructors enter room 1 and room *n*, they count students there and lock the room (after it no one can enter or leave this room). - Each student from rooms with numbers from 2 to *n*<=-<=1 can run to another room but not further than *d* rooms away from her current room, or stay in place. Each student can optionally hide under a bed. - Instructors move from room 1 to room 2 and from room *n* to room *n*<=-<=1. - This process continues until all rooms are processed. Let *x*1 denote the number of rooms in which the first instructor counted the number of non-hidden students different from *b*, and *x*2 be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers *x**i*. Help them find this value if they use the optimal strategy. Input Specification: The first line contains three integers *n*, *d* and *b* (2<=≀<=*n*<=≀<=100<=000, 1<=≀<=*d*<=≀<=*n*<=-<=1, 1<=≀<=*b*<=≀<=10<=000), number of rooms in the house, running distance of a student, official number of students in a room. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109), *i*-th of which stands for the number of students in the *i*-th room before curfew announcement. It is guaranteed that *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*. Output Specification: Output one integer, the minimal possible value of the maximum of *x**i*. Demo Input: ['5 1 1\n1 0 0 0 4\n', '6 1 2\n3 8 0 1 0 0\n'] Demo Output: ['1\n', '2\n'] Note: In the first sample the first three rooms are processed by the first instructor, and the last two are processed by the second instructor. One of the optimal strategies is the following: firstly three students run from room 5 to room 4, on the next stage two of them run to room 3, and one of those two hides under a bed. This way, the first instructor writes down room 2, and the second writes down nothing. In the second sample one of the optimal strategies is the following: firstly all students in room 1 hide, all students from room 2 run to room 3. On the next stage one student runs from room 3 to room 4, and 5 students hide. This way, the first instructor writes down rooms 1 and 2, the second instructor writes down rooms 5 and 6.
1,648
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Felix the Robot is preparing for a probability theory exam. Unfortunately, during the semester, he took a course of the belles-lettres instead of studying the subject, so now he does not know the answer to any of the upcoming exam's questions. One thing is for sure: Felix needs help! The exam for robots is an online event. It consists of *n*<==<=5000 questions each of which has only two possible answers: "yes" and "no". A robot can attempt to pass the exam at most *x*<==<=100 times. The questions, their order and right answers don't change from one attempt to another. Once the exam starts, Felix will get just a few seconds for all his attempts, and he can't learn the right answers so fast. The robot will try to pass the exam in the following way. First, Felix fixes the answers for all questions. The result is a string of *n* bits: answers for the first, second, ..., *n*-th questions. In this string, 0 means that the answer is "no", and 1 is for "yes". Then he answers the questions according to this string, spending one attempt. After that, Felix can fix another string of *n* bits and make another attempt, and so on until there are no more attempts. In the online system for exam, the following optimization is implemented: if at some moment of time, the examinee already got *k*<==<=2000 answers wrong, the attempt is immediately terminated with the corresponding message. For Felix, this means that the remaining bits in the string he fixed are ignored. If there were strictly less than *k* wrong answers for all *n* questions, the exam is considered passed. The result of an attempt is a number from *k* to *n* inclusive: the number of questions after which the attempt was terminated. If the exam is passed, this number is considered to be *n*<=+<=1. The exam result is the highest result among all attempts. If there were no attempts, the exam result is zero. Your task is to write a program which will determine the bit strings for all attempts Felix makes. After each attempt, your program will get its result immediately. Help Felix get the highest exam result you can! Interaction Protocol Your solution can make from 0 to *x* attempts inclusive. To make an attempt, print a string to the standard output. The string must consist of exactly *n* binary digits without spaces and end with a newline character. To prevent output buffering, after printing a string, insert a command to flush the buffer: for example, it can be fflushΒ (stdout) in C or C++, System.out.flushΒ () in Java, flushΒ (output) in Pascal or sys.stdout.flushΒ () in Python. After each attempt you make, you can immediately read its result from the standard input. The result is an integer from *k* to *n*<=+<=1 inclusive, followed by a newline character. Scoring System A test is defined by a string of *n* binary digits: the right answers to *n* questions. This string is kept secret from the solution. Each test is evaluated separately. If a solution followed the interaction protocol and terminated correctly on a test, it gets a score of *max* (0,<=*S*<=-<=4000) where *S* is the exam result. Otherwise, the solution gets zero score for the test. Testing Your solution will be checked on sets of tests generated in advance. Each test is created using a pseudo-random number generator. You can consider that the answers are uniformly distributed (the probabilities of digits 0 and 1 are the same) and mutually independent (the probabilities of all 2*n* possible strings are the same). A solution gets the score which is the sum of its score on all the tests. During the main phase of the contest, there are two ways to send a solution for checking. - The first one is to check on examples. There are 10 example tests which are also available for local testing. As soon as the solution is checked, you can see reports for all examples by clicking on the submission result.- The second way is to check on preliminary tests. There are 100 preliminary tests which are generated in advance but kept secret. The score for preliminary tests (but not for example tests) is used in the preliminary scoreboard. This score does not affect the final results, but nevertheless allows to roughly compare a solution with others. After the main phase ends, for each participant, the system chooses the final solution: - consider all solutions sent for preliminary testing; - choose the ones which got a total score strictly greater than zero; - define the final solution as the one of chosen solutions which has the latest submission time. Note that the solutions sent only to be checked on examples are not considered when choosing the final solution. During the final testing, all final solutions will be checked on the same large set of a large number (<=β‰ˆ<=1000) of final tests. The score for final tests determines the final scoreboard. The winner is the contestant whose solution gets the highest total score. In case two or more participants have equal total score, the contestants with such score tie for the same place. A package for local development is available on GitHub at the following address: [https://github.com/GassaFM/online-exam](https://github.com/GassaFM/online-exam). You can download sources or the latest release: [https://github.com/GassaFM/online-exam/releases](https://github.com/GassaFM/online-exam/releases). Example To have an example which fits into the problem statement, let *n*<==<=10, *k*<==<=2, and *x*<==<=3 (recall that in the real problem, *n*<==<=5000, *k*<==<=2000, and *x*<==<=100, so this example is not a correct test for the problem). Let the right answers be defined by the string 1010001111. Before any attempts are made, the exam result is zero. Consider a solution making three attempts. Let the first attempt be defined by the string 0100100100. The result of this attempt is the number 2: the first wrong answer is the answer to the first question, and the second is to the second question. The exam result at this moment is 2. Let the second attempt be defined by the string 1010101010. The result of this attempt is the number 8: the first wrong answer is the answer to the fifth question, and the second is to the eighth question. The exam result at this moment is 8. Let the second attempt be defined by the string 1001011001. The result of this attempt is the number 4: the first wrong answer is the answer to the third question, and the second is to the fourth question. The exam result at this moment is still 8. As *x*<==<=3 in our example, further attempts are impossible, so if the solution terminates correctly, the exam result is 8. Now consider another solution making two attempts. Let the first attempt be defined by the string 1010001110. Its result is the number 11: the first and only wrong answer is the answer to the tenth question, *k*<==<=2, so the exam is considered passed. Let the first attempt be defined by the string 0000011111. Its result is the number 3: the first wrong answer is the answer to the first question, and the second one is to the third question. If the solution terminates correctly after the above two attempts, the exam result is 11. Input Specification: none Output Specification: none Note: none
1,649
Title: Grasshopper And the String Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump. Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from 1 to the value of his jump ability. The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'. Input Specification: The first line contains non-empty string consisting of capital English letters. It is guaranteed that the length of the string does not exceed 100. Output Specification: Print single integer *a*Β β€” the minimum jump ability of the Grasshopper (in the number of symbols) that is needed to overcome the given string, jumping only on vowels. Demo Input: ['ABABBBACFEYUKOTT\n', 'AAA\n'] Demo Output: ['4', '1'] Note: none
1,650
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alyona has a tree with *n* vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex *i* she wrote *a**i*. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges). Let's define *dist*(*v*,<=*u*) as the sum of the integers written on the edges of the simple path from *v* to *u*. The vertex *v* controls the vertex *u* (*v*<=β‰ <=*u*) if and only if *u* is in the subtree of *v* and *dist*(*v*,<=*u*)<=≀<=*a**u*. Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex *v* what is the number of vertices *u* such that *v* controls *u*. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=2Β·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109)Β β€” the integers written in the vertices. The next (*n*<=-<=1) lines contain two integers each. The *i*-th of these lines contains integers *p**i* and *w**i* (1<=≀<=*p**i*<=≀<=*n*, 1<=≀<=*w**i*<=≀<=109)Β β€” the parent of the (*i*<=+<=1)-th vertex in the tree and the number written on the edge between *p**i* and (*i*<=+<=1). It is guaranteed that the given graph is a tree. Output Specification: Print *n* integersΒ β€” the *i*-th of these numbers should be equal to the number of vertices that the *i*-th vertex controls. Demo Input: ['5\n2 5 1 4 6\n1 7\n1 1\n3 5\n3 6\n', '5\n9 7 8 6 5\n1 1\n2 1\n3 1\n4 1\n'] Demo Output: ['1 0 1 0 0\n', '4 3 2 1 0\n'] Note: In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
1,651
Title: Hyperdrive Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In a far away galaxy there are *n* inhabited planets, numbered with numbers from 1 to *n*. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number 1 a hyperdrive was invented. As soon as this significant event took place, *n*<=-<=1 spaceships were built on the planet number 1, and those ships were sent to other planets to inform about the revolutionary invention. Paradoxical thought it may be, but the hyperspace is represented as simple three-dimensional Euclidean space. The inhabited planets may be considered fixed points in it, and no two points coincide and no three points lie on the same straight line. The movement of a ship with a hyperdrive between two planets is performed along a straight line at the constant speed, the same for all the ships. That's why the distance in the hyperspace are measured in hyperyears (a ship with a hyperdrive covers a distance of *s* hyperyears in *s* years). When the ship reaches an inhabited planet, the inhabitants of the planet dissemble it, make *n*<=-<=2 identical to it ships with a hyperdrive and send them to other *n*<=-<=2 planets (except for the one from which the ship arrived). The time to make a new ship compared to the time in which they move from one planet to another is so small that it can be disregarded. New ships are absolutely identical to the ones sent initially: they move at the same constant speed along a straight line trajectory and, having reached a planet, perform the very same mission, i.e. are dissembled to build new *n*<=-<=2 ships and send them to all the planets except for the one from which the ship arrived. Thus, the process of spreading the important news around the galaxy continues. However the hyperdrive creators hurried to spread the news about their invention so much that they didn't study completely what goes on when two ships collide in the hyperspace. If two moving ships find themselves at one point, they provoke an explosion of colossal power, leading to the destruction of the galaxy! Your task is to find the time the galaxy will continue to exist from the moment of the ships' launch from the first planet. Input Specification: The first line contains a number *n* (3<=≀<=*n*<=≀<=5000) β€” the number of inhabited planets in the galaxy. The next *n* lines contain integer coordinates of the planets in format "*x**i* *y**i* *z**i*" (<=-<=104<=≀<=*x**i*,<=*y**i*,<=*z**i*<=≀<=104). Output Specification: Print the single number β€” the solution to the task with an absolute or relative error not exceeding 10<=-<=6. Demo Input: ['4\n0 0 0\n0 0 1\n0 1 0\n1 0 0\n'] Demo Output: ['1.7071067812\n'] Note: none
1,652
Title: Tanya and Postcard Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message β€” string *s* of length *n*, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string *s*. The newspaper contains string *t*, consisting of uppercase and lowercase English letters. We know that the length of string *t* greater or equal to the length of the string *s*. The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some *n* letters out of the newspaper and make a message of length exactly *n*, so that it looked as much as possible like *s*. If the letter in some position has correct value and correct letter case (in the string *s* and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS". Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message. Input Specification: The first line contains line *s* (1<=≀<=|*s*|<=≀<=2Β·105), consisting of uppercase and lowercase English letters β€” the text of Tanya's message. The second line contains line *t* (|*s*|<=≀<=|*t*|<=≀<=2Β·105), consisting of uppercase and lowercase English letters β€” the text written in the newspaper. Here |*a*| means the length of the string *a*. Output Specification: Print two integers separated by a space: - the first number is the number of times Tanya shouts "YAY!" while making the message, - the second number is the number of times Tanya says "WHOOPS" while making the message. Demo Input: ['AbC\nDCbA\n', 'ABC\nabc\n', 'abacaba\nAbaCaBA\n'] Demo Output: ['3 0\n', '0 3\n', '3 4\n'] Note: none
1,653
Title: Lucky Interval Time Limit: 4 seconds Memory Limit: 512 megabytes Problem Description: Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya came across an interval of numbers [*a*,<=*a*<=+<=*l*<=-<=1]. Let *F*(*x*) be the number of lucky digits of number *x*. Find the minimum *b* (*a*<=&lt;<=*b*) such, that *F*(*a*) = *F*(*b*), *F*(*a*<=+<=1) = *F*(*b*<=+<=1), ..., *F*(*a*<=+<=*l*<=-<=1) = *F*(*b*<=+<=*l*<=-<=1). Input Specification: The single line contains two integers *a* and *l* (1<=≀<=*a*,<=*l*<=≀<=109) β€” the interval's first number and the interval's length correspondingly. Output Specification: On the single line print number *b* β€” the answer to the problem. Demo Input: ['7 4\n', '4 7\n'] Demo Output: ['17\n', '14\n'] Note: Consider that [*a*, *b*] denotes an interval of integers; this interval includes the boundaries. That is, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/18b4a6012d95ad18891561410f0314497a578d63.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,654
Title: Log Stream Analysis Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got a list of program warning logs. Each record of a log stream is a string in this format: String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format. The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description). Your task is to print the first moment of time, when the number of warnings for the last *n* seconds was not less than *m*. Input Specification: The first line of the input contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5Β·106 (in particular, this means that the length of some line does not exceed 5Β·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty. Output Specification: If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) β€” the first moment of time when the number of warnings for the last *n* seconds got no less than *m*. Demo Input: ['60 3\n2012-03-16 16:15:25: Disk size is\n2012-03-16 16:15:25: Network failute\n2012-03-16 16:16:29: Cant write varlog\n2012-03-16 16:16:42: Unable to start process\n2012-03-16 16:16:43: Disk size is too small\n2012-03-16 16:16:53: Timeout detected\n', '1 2\n2012-03-16 23:59:59:Disk size\n2012-03-17 00:00:00: Network\n2012-03-17 00:00:01:Cant write varlog\n', '2 2\n2012-03-16 23:59:59:Disk size is too sm\n2012-03-17 00:00:00:Network failute dete\n2012-03-17 00:00:01:Cant write varlogmysq\n'] Demo Output: ['2012-03-16 16:16:43\n', '-1\n', '2012-03-17 00:00:00\n'] Note: none
1,655
Title: Cut 'em all! Time Limit: None seconds Memory Limit: None megabytes Problem Description: You're given a tree with $n$ vertices. Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size. Input Specification: The first line contains an integer $n$ ($1 \le n \le 10^5$) denoting the size of the tree. The next $n - 1$ lines contain two integers $u$, $v$ ($1 \le u, v \le n$) each, describing the vertices connected by the $i$-th edge. It's guaranteed that the given edges form a tree. Output Specification: Output a single integer $k$ β€” the maximum number of edges that can be removed to leave all connected components with even size, or $-1$ if it is impossible to remove edges in order to satisfy this property. Demo Input: ['4\n2 4\n4 1\n3 1\n', '3\n1 2\n1 3\n', '10\n7 1\n8 4\n8 10\n4 7\n6 5\n9 3\n3 5\n2 10\n2 5\n', '2\n1 2\n'] Demo Output: ['1', '-1', '4', '0'] Note: In the first example you can remove the edge between vertices $1$ and $4$. The graph after that will have two connected components with two vertices in each. In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $-1$.
1,656
Title: MUH and Sticks Time Limit: None seconds Memory Limit: None megabytes Problem Description: Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: - Four sticks represent the animal's legs, these sticks should have the same length. - Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks. Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it. Input Specification: The single line contains six space-separated integers *l**i* (1<=≀<=*l**i*<=≀<=9) β€” the lengths of the six sticks. It is guaranteed that the input is such that you cannot make both animals from the sticks. Output Specification: If you can make a bear from the given set, print string "Bear" (without the quotes). If you can make an elephant, print string "Elephant" (wΔ±thout the quotes). If you can make neither a bear nor an elephant, print string "Alien" (without the quotes). Demo Input: ['4 2 5 4 4 4\n', '4 4 5 4 4 5\n', '1 2 3 4 5 6\n'] Demo Output: ['Bear', 'Elephant', 'Alien'] Note: If you're out of creative ideas, see instructions below which show how to make a bear and an elephant in the first two samples. The stick of length 2 is in red, the sticks of length 4 are in green, the sticks of length 5 are in blue.
1,657
Title: National Property Time Limit: None seconds Memory Limit: None megabytes Problem Description: You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library. Some long and uninteresting story was removed... The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter *x* is denoted by *x*'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2<=&lt;<=3, 2'<=&lt;<=3', 3'<=&lt;<=2. A word *x*1,<=*x*2,<=...,<=*x**a* is not lexicographically greater than *y*1,<=*y*2,<=...,<=*y**b* if one of the two following conditions holds: - *a*<=≀<=*b* and *x*1<==<=*y*1,<=...,<=*x**a*<==<=*y**a*, i.e. the first word is the prefix of the second word; - there is a position 1<=≀<=*j*<=≀<=*min*(*a*,<=*b*), such that *x*1<==<=*y*1,<=...,<=*x**j*<=-<=1<==<=*y**j*<=-<=1 and *x**j*<=&lt;<=*y**j*, i.e. at the first position where the words differ the first word has a smaller letter than the second word has. For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence. Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet. Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible. Note that some words can be equal. Input Specification: The first line contains two integers *n* and *m* (2<=≀<=*n*<=≀<=100<=000, 1<=≀<=*m*<=≀<=100<=000)Β β€” the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to *m*. Each of the next *n* lines contains a description of one word in format *l**i*,<=*s**i*,<=1,<=*s**i*,<=2,<=...,<=*s**i*,<=*l**i* (1<=≀<=*l**i*<=≀<=100<=000, 1<=≀<=*s**i*,<=*j*<=≀<=*m*), where *l**i* is the length of the word, and *s**i*,<=*j* is the sequence of letters in the word. The words are given in the order Denis has them in the sequence. It is guaranteed that the total length of all words is not greater than 100<=000. Output Specification: In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes). If the required is possible, in the second line print *k*Β β€” the number of letters Denis has to capitalize (make large), and in the third line print *k* distinct integersΒ β€” these letters. Note that you don't need to minimize the value *k*. You can print the letters in any order. If there are multiple answers, print any of them. Demo Input: ['4 3\n1 2\n1 1\n3 1 3 2\n2 1 1\n', '6 5\n2 1 2\n2 1 2\n3 1 2 3\n2 1 5\n2 4 4\n2 4 4\n', '4 3\n4 3 2 2 1\n3 1 1 3\n3 2 3 3\n2 3 1\n'] Demo Output: ['Yes\n2\n2 3 ', 'Yes\n0\n', 'No\n'] Note: In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following: - 2' - 1 - 1 3' 2' - 1 1 The condition 2' &lt; 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' &lt; 1, then the third word is not lexicographically larger than the fourth word. In the second example the words are in lexicographical order from the beginning, so Denis can do nothing. In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
1,658
Title: Graphic Settings Time Limit: None seconds Memory Limit: None megabytes Problem Description: Recently Ivan bought a new computer. Excited, he unpacked it and installed his favourite game. With his old computer Ivan had to choose the worst possible graphic settings (because otherwise the framerate would be really low), but now he wants to check, maybe his new computer can perform well even with the best possible graphics? There are *m* graphics parameters in the game. *i*-th parameter can be set to any positive integer from 1 to *a**i*, and initially is set to *b**i* (*b**i*<=≀<=*a**i*). So there are different combinations of parameters. Ivan can increase or decrease any of these parameters by 1; after that the game will be restarted with new parameters (and Ivan will have the opportunity to check chosen combination of parameters). Ivan wants to try all *p* possible combinations. Also he wants to return to the initial settings after trying all combinations, because he thinks that initial settings can be somehow best suited for his hardware. But Ivan doesn't really want to make a lot of restarts. So he wants you to tell the following: - If there exists a way to make exactly *p* changes (each change either decreases or increases some parameter by 1) to try all possible combinations and return to initial combination, then Ivan wants to know this way. - Otherwise, if there exists a way to make exactly *p*<=-<=1 changes to try all possible combinations (including the initial one), then Ivan wants to know this way. Help Ivan by showing him the way to change parameters! Input Specification: The first line of input contains one integer number *m* (1<=≀<=*m*<=≀<=6). The second line contains *m* integer numbers *a*1,<=*a*2,<=...,<=*a**m* (2<=≀<=*a**i*<=≀<=1000). It is guaranteed that . The third line contains *m* integer numbers *b*1,<=*b*2,<=...,<=*b**m* (1<=≀<=*b**i*<=≀<=*a**i*). Output Specification: If there is a way to make exactly *p* changes (each change either decreases or increases some parameter by 1) to try all possible combinations and return to initial combination, then output Cycle in the first line. Then *p* lines must follow, each desribing a change. The line must be either inc x (increase parameter *x* by 1) or dec x (decrease it). Otherwise, if there is a way to make exactly *p*<=-<=1 changes to try all possible combinations (including the initial one), then output Path in the first line. Then *p*<=-<=1 lines must follow, each describing the change the same way as mentioned above. Otherwise, output No. Demo Input: ['1\n3\n1\n', '1\n3\n2\n', '2\n3 2\n1 1\n'] Demo Output: ['Path\ninc 1\ninc 1\n', 'No\n', 'Cycle\ninc 1\ninc 1\ninc 2\ndec 1\ndec 1\ndec 2\n'] Note: none
1,659
Title: Petya and Pipes Time Limit: None seconds Memory Limit: None megabytes Problem Description: A little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in. The Berland capital has *n* water tanks numbered from 1 to *n*. These tanks are connected by unidirectional pipes in some manner. Any pair of water tanks is connected by at most one pipe in each direction. Each pipe has a strictly positive integer width. Width determines the number of liters of water per a unit of time this pipe can transport. The water goes to the city from the main water tank (its number is 1). The water must go through some pipe path and get to the sewer tank with cleaning system (its number is *n*). Petya wants to increase the width of some subset of pipes by at most *k* units in total so that the width of each pipe remains integer. Help him determine the maximum amount of water that can be transmitted per a unit of time from the main tank to the sewer tank after such operation is completed. Input Specification: The first line contains two space-separated integers *n* and *k* (2<=≀<=*n*<=≀<=50, 0<=≀<=*k*<=≀<=1000). Then follow *n* lines, each line contains *n* integers separated by single spaces. The *i*<=+<=1-th row and *j*-th column contain number *c**ij* β€” the width of the pipe that goes from tank *i* to tank *j* (0<=≀<=*c**ij*<=≀<=106,<=*c**ii*<==<=0). If *c**ij*<==<=0, then there is no pipe from tank *i* to tank *j*. Output Specification: Print a single integer β€” the maximum amount of water that can be transmitted from the main tank to the sewer tank per a unit of time. Demo Input: ['5 7\n0 1 0 2 0\n0 0 4 10 0\n0 0 0 0 5\n0 0 0 0 10\n0 0 0 0 0\n', '5 10\n0 1 0 0 0\n0 0 2 0 0\n0 0 0 3 0\n0 0 0 0 4\n100 0 0 0 0\n'] Demo Output: ['10\n', '5\n'] Note: In the first test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 7 units. In the second test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 4 units, from the 2nd to the 3rd water tank by 3 units, from the 3rd to the 4th water tank by 2 units and from the 4th to 5th water tank by 1 unit.
1,660
Title: Beautiful Set Time Limit: None seconds Memory Limit: None megabytes Problem Description: We'll call a set of positive integers *a* beautiful if the following condition fulfills: for any prime *p*, if , then . In other words, if one number from the set is divisible by prime *p*, then at least half of numbers from the set is divisible by *p*. Your task is to find any beautiful set, where the number of elements is equal to *k* and each element doesn't exceed 2*k*2. Input Specification: The first line contains integer *k* (10<=≀<=*k*<=≀<=5000) that shows how many numbers the required beautiful set should have. Output Specification: In the first line print *k* space-separated integers that are a beautiful set. If there are multiple such sets, you are allowed to print any of them. Demo Input: ['10\n'] Demo Output: ['16 18 24 27 36 48 54 72 108 144 \n'] Note: none
1,661
Title: Sum of Digits Time Limit: 2 seconds Memory Limit: 265 megabytes Problem Description: Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit? Input Specification: The first line contains the only integer *n* (0<=≀<=*n*<=≀<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes. Output Specification: Print the number of times a number can be replaced by the sum of its digits until it only contains one digit. Demo Input: ['0\n', '10\n', '991\n'] Demo Output: ['0\n', '1\n', '3\n'] Note: In the first sample the number already is one-digit β€” Herald can't cast a spell. The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once. The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.
1,662
Title: Work Group Time Limit: None seconds Memory Limit: None megabytes Problem Description: One Big Software Company has *n* employees numbered from 1 to *n*. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior. We will call person *a* a subordinates of another person *b*, if either *b* is an immediate supervisor of *a*, or the immediate supervisor of *a* is a subordinate to person *b*. In particular, subordinates of the head are all other employees of the company. To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer *a**i*, where *i* is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it. The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even. Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=2Β·105) β€” the number of workers of the Big Software Company. Then *n* lines follow, describing the company employees. The *i*-th line contains two integers *p**i*,<=*a**i* (1<=≀<=*a**i*<=≀<=105) β€” the number of the person who is the *i*-th employee's immediate superior and *i*-th employee's efficiency. For the director *p*1<==<=<=-<=1, for all other people the condition 1<=≀<=*p**i*<=&lt;<=*i* is fulfilled. Output Specification: Print a single integer β€” the maximum possible efficiency of the workgroup. Demo Input: ['7\n-1 3\n1 2\n1 1\n1 4\n4 5\n4 3\n5 2\n'] Demo Output: ['17\n'] Note: In the sample test the most effective way is to make a workgroup from employees number 1, 2, 4, 5, 6.
1,663
Title: Time to Raid Cowavans Time Limit: 4 seconds Memory Limit: 70 megabytes Problem Description: As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row. If we number all cows in the cowavan with positive integers from 1 to *n*, then we can formalize the popular model of abduction, known as the (*a*,<=*b*)-Cowavan Raid: first they steal a cow number *a*, then number *a*<=+<=*b*, then β€” number *a*<=+<=2Β·*b*, and so on, until the number of an abducted cow exceeds *n*. During one raid the cows are not renumbered. The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made *p* scenarios of the (*a*,<=*b*)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen. Input Specification: The first line contains the only positive integer *n* (1<=≀<=*n*<=≀<=3Β·105) β€” the number of cows in the cowavan. The second number contains *n* positive integer *w**i*, separated by spaces, where the *i*-th number describes the mass of the *i*-th cow in the cowavan (1<=≀<=*w**i*<=≀<=109). The third line contains the only positive integer *p* β€” the number of scenarios of (*a*,<=*b*)-raids (1<=≀<=*p*<=≀<=3Β·105). Each following line contains integer parameters *a* and *b* of the corresponding scenario (1<=≀<=*a*,<=*b*<=≀<=*n*). Output Specification: Print for each scenario of the (*a*,<=*b*)-raid the total mass of cows, that can be stolen using only this scenario. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams of the %I64d specificator. Demo Input: ['3\n1 2 3\n2\n1 1\n1 2\n', '4\n2 3 5 7\n3\n1 3\n2 3\n2 2\n'] Demo Output: ['6\n4\n', '9\n3\n10\n'] Note: none
1,664
Title: Set Theory Time Limit: None seconds Memory Limit: None megabytes Problem Description: Masha and Grisha like studying sets of positive integers. One day Grisha has written a set *A* containing *n* different integers *a**i* on a blackboard. Now he asks Masha to create a set *B* containing *n* different integers *b**j* such that all *n*2 integers that can be obtained by summing up *a**i* and *b**j* for all possible pairs of *i* and *j* are different. Both Masha and Grisha don't like big numbers, so all numbers in *A* are from 1 to 106, and all numbers in *B* must also be in the same range. Help Masha to create the set *B* that satisfies Grisha's requirement. Input Specification: Input data contains multiple test cases. The first line contains an integer *t*Β β€” the number of test cases (1<=≀<=*t*<=≀<=100). Each test case is described in the following way: the first line of the description contains one integer *n*Β β€” the number of elements in *A* (1<=≀<=*n*<=≀<=100). The second line contains *n* integers *a**i*Β β€” the elements of *A* (1<=≀<=*a**i*<=≀<=106). Output Specification: For each test first print the answer: - NO, if Masha's task is impossible to solve, there is no way to create the required set *B*. - YES, if there is the way to create the required set. In this case the second line must contain *n* different positive integers *b**j*Β β€” elements of *B* (1<=≀<=*b**j*<=≀<=106). If there are several possible sets, output any of them. Demo Input: ['3\n3\n1 10 100\n1\n1\n2\n2 4\n'] Demo Output: ['YES\n1 2 3 \nYES\n1 \nYES\n1 2 \n'] Note: none
1,665
Title: Hostname Aliases Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://&lt;hostname&gt;[/&lt;path&gt;], where: - &lt;hostname&gt;Β β€” server name (consists of words and maybe some dots separating them), - /&lt;path&gt;Β β€” optional part, where &lt;path&gt; consists of words separated by slashes. We consider two &lt;hostname&gt; to correspond to one website if for each query to the first &lt;hostname&gt; there will be exactly the same query to the second one and vice versaΒ β€” for each query to the second &lt;hostname&gt; there will be the same query to the first one. Take a look at the samples for further clarifications. Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name. Please note, that according to the above definition queries http://&lt;hostname&gt; and http://&lt;hostname&gt;/ are different. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the number of page queries. Then follow *n* lines each containing exactly one address. Each address is of the form http://&lt;hostname&gt;[/&lt;path&gt;], where: - &lt;hostname&gt; consists of lowercase English letters and dots, there are no two consecutive dots, &lt;hostname&gt; doesn't start or finish with a dot. The length of &lt;hostname&gt; is positive and doesn't exceed 20. - &lt;path&gt; consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, &lt;path&gt; doesn't start with a slash and its length doesn't exceed 20. Addresses are not guaranteed to be distinct. Output Specification: First print *k*Β β€” the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next *k* lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order. Demo Input: ['10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test\n', '14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a.c/aba..b/a\nhttp://abc/\nhttp://a.c/\nhttp://ccc.bbbb\nhttp://ab.ac.bc.aa/\nhttp://a.a.a/\nhttp://ccc.bbbb/\nhttp://cba.com/\nhttp://cba.com/aba..b\nhttp://a.a.a/aba..b/a\nhttp://abc/aba..b/a\n'] Demo Output: ['1\nhttp://abacaba.de http://abacaba.ru \n', '2\nhttp://cba.com http://ccc.bbbb \nhttp://a.a.a http://a.c http://abc \n'] Note: none
1,666
Title: Weird Chess Time Limit: None seconds Memory Limit: None megabytes Problem Description: Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous. Igor's chessboard is a square of size *n*<=Γ—<=*n* cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves. Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to *n*. Let's assign to each square a pair of integers (*x*,<=*y*)Β β€” the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (*dx*,<=*dy*); using this move, the piece moves from the field (*x*,<=*y*) to the field (*x*<=+<=*dx*,<=*y*<=+<=*dy*). You can perform the move if the cell (*x*<=+<=*dx*,<=*y*<=+<=*dy*) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (*x*,<=*y*) and (*x*<=+<=*dx*,<=*y*<=+<=*dy*) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess). Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=50). The next *n* lines contain *n* characters each describing the position offered by Igor. The *j*-th character of the *i*-th string can have the following values: - o β€” in this case the field (*i*,<=*j*) is occupied by a piece and the field may or may not be attacked by some other piece;- x β€” in this case field (*i*,<=*j*) is attacked by some piece;- . β€” in this case field (*i*,<=*j*) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board. Output Specification: If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2*n*<=-<=1)<=Γ—<=(2*n*<=-<=1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'. Demo Input: ['5\noxxxx\nx...x\nx...x\nx...x\nxxxxo\n', '6\n.x.x..\nx.x.x.\n.xo..x\nx..ox.\n.x.x.x\n..x.x.\n', '3\no.x\noxx\no.x\n'] Demo Output: ['YES\n....x....\n....x....\n....x....\n....x....\nxxxxoxxxx\n....x....\n....x....\n....x....\n....x....\n', 'YES\n...........\n...........\n...........\n....x.x....\n...x...x...\n.....o.....\n...x...x...\n....x.x....\n...........\n...........\n...........\n', 'NO\n'] Note: In the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight.
1,667
Title: Reposts Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed. Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke. Input Specification: The first line of the input contains integer *n* (1<=≀<=*n*<=≀<=200) β€” the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user. Output Specification: Print a single integer β€” the maximum length of a repost chain. Demo Input: ['5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya\n', '6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp\n', '1\nSoMeStRaNgEgUe reposted PoLyCaRp\n'] Demo Output: ['6\n', '2\n', '2\n'] Note: none
1,668
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array of positive integers *a*1,<=*a*2,<=...,<=*a**n*<=Γ—<=*T* of length *n*<=Γ—<=*T*. We know that for any *i*<=&gt;<=*n* it is true that *a**i*<==<=*a**i*<=-<=*n*. Find the length of the longest non-decreasing sequence of the given array. Input Specification: The first line contains two space-separated integers: *n*, *T* (1<=≀<=*n*<=≀<=100, 1<=≀<=*T*<=≀<=107). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=300). Output Specification: Print a single number β€” the length of a sought sequence. Demo Input: ['4 3\n3 1 4 2\n'] Demo Output: ['5\n'] Note: The array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.
1,669
Title: Mice and Holes Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Masha came home and noticed *n* mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor. The corridor can be represeted as a numeric axis with *n* mice and *m* holes on it. *i*th mouse is at the coordinate *x**i*, and *j*th hole β€” at coordinate *p**j*. *j*th hole has enough room for *c**j* mice, so not more than *c**j* mice can enter this hole. What is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If *i*th mouse goes to the hole *j*, then its distance is |*x**i*<=-<=*p**j*|. Print the minimum sum of distances. Input Specification: The first line contains two integer numbers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=5000) β€” the number of mice and the number of holes, respectively. The second line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=109<=≀<=*x**i*<=≀<=109), where *x**i* is the coordinate of *i*th mouse. Next *m* lines contain pairs of integer numbers *p**j*,<=*c**j* (<=-<=109<=≀<=*p**j*<=≀<=109,<=1<=≀<=*c**j*<=≀<=5000), where *p**j* is the coordinate of *j*th hole, and *c**j* is the maximum number of mice that can hide in the hole *j*. Output Specification: Print one integer number β€” the minimum sum of distances. If there is no solution, print -1 instead. Demo Input: ['4 5\n6 2 8 9\n3 6\n2 1\n3 6\n4 7\n4 7\n', '7 2\n10 20 30 40 50 45 35\n-1000000000 10\n1000000000 1\n'] Demo Output: ['11\n', '7000000130\n'] Note: none
1,670
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sasha and Kolya decided to get drunk with Coke, again. This time they have *k* types of Coke. *i*-th type is characterised by its carbon dioxide concentration . Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration . The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration . Assume that the friends have unlimited amount of each Coke type. Input Specification: The first line contains two integers *n*, *k* (0<=≀<=*n*<=≀<=1000, 1<=≀<=*k*<=≀<=106)Β β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains *k* integers *a*1,<=*a*2,<=...,<=*a**k* (0<=≀<=*a**i*<=≀<=1000)Β β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Specification: Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration , or -1 if it is impossible. Demo Input: ['400 4\n100 300 450 500\n', '50 2\n100 25\n'] Demo Output: ['2\n', '3\n'] Note: In the first sample case, we can achieve concentration <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bed0f5c3640139492194728ccc3ac55accf16a8e.png" style="max-width: 100.0%;max-height: 100.0%;"/> using one liter of Coke of types <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9b37ab6b0795f08ffcc699d9101a9efb89374478.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d82574f3d78c4bd9d8ab9bda103e05a51e1b3161.png" style="max-width: 100.0%;max-height: 100.0%;"/>: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b23f59a536403f9a2364e971aa0bfc9a3411b366.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second case, we can achieve concentration <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/46aa9afb7ee4d932ca2c3f0d6535a9955fc8f0a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> using two liters of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/69b8967d23533c2caada3910f564294509450a59.png" style="max-width: 100.0%;max-height: 100.0%;"/> type and one liter of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/abf5cbf9e8a81a0eff83ff53574dcabb097df44e.png" style="max-width: 100.0%;max-height: 100.0%;"/> type: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4d2331fc733efc58d37745ff9a495a116ebd7e8a.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
1,671
Title: Lightsabers (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission. Heidi has *n* Jedi Knights standing in front of her, each one with a lightsaber of one of *m* possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly *k*1 knights with lightsabers of the first color, *k*2 knights with lightsabers of the second color, ..., *k**m* knights with lightsabers of the *m*-th color. However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights. Input Specification: The first line of the input contains *n* (1<=≀<=*n*<=≀<=2Β·105) and *m* (1<=≀<=*m*<=≀<=*n*). The second line contains *n* integers in the range {1,<=2,<=...,<=*m*} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains *m* integers *k*1,<=*k*2,<=...,<=*k**m* (with ) – the desired counts of Jedi Knights with lightsabers of each color from 1 to *m*. Output Specification: Output one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output <=-<=1. Demo Input: ['8 3\n3 3 1 2 2 1 1 3\n3 1 1\n'] Demo Output: ['1\n'] Note: none
1,672
Title: Pairs Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: There are *n* students in Polycarp's class (including himself). A few days ago all students wrote an essay "My best friend". Each student's essay was dedicated to one of the students of class, to his/her best friend. Note that student *b*'s best friend is not necessarily student *a*, if *a*'s best friend is *b*. And now the teacher leads the whole class to the museum of the history of sports programming. Exciting stories of legendary heroes await the students: tourist, Petr, tomek, SnapDragon β€” that's who they will hear about! The teacher decided to divide students into pairs so that each pair consisted of a student and his best friend. She may not be able to split all the students into pairs, it's not a problem β€” she wants to pick out the maximum number of such pairs. If there is more than one variant of doing so, she wants to pick out the pairs so that there were as much boy-girl pairs as possible. Of course, each student must not be included in more than one pair. Input Specification: The first line contains an integer *n* (2<=≀<=*n*<=≀<=105), *n* is the number of students per class. Next, *n* lines contain information about the students, one per line. Each line contains two integers *f**i*,<=*s**i* (1<=≀<=*f**i*<=≀<=*n*,<=*f**i*<=β‰ <=*i*,<=1<=≀<=*s**i*<=≀<=2), where *f**i* is the number of *i*-th student's best friend and *s**i* denotes the *i*-th pupil's sex (*s**i*<==<=1 for a boy and *s**i*<==<=2 for a girl). Output Specification: Print on the first line two numbers *t*, *e*, where *t* is the maximum number of formed pairs, and *e* is the maximum number of boy-girl type pairs among them. Then print *t* lines, each line must contain a pair *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*), they are numbers of pupils in the *i*-th pair. Print the pairs in any order. Print the numbers in pairs in any order. If there are several solutions, output any of them. Demo Input: ['5\n5 2\n3 2\n5 1\n2 1\n4 2\n', '6\n5 2\n3 2\n5 1\n2 1\n4 2\n3 1\n', '8\n2 2\n3 2\n5 1\n3 1\n6 1\n5 1\n8 2\n7 1\n'] Demo Output: ['2 2\n5 3\n4 2\n', '3 1\n4 2\n5 1\n3 6\n', '4 1\n5 6\n3 4\n2 1\n7 8\n'] Note: The picture corresponds to the first sample. On the picture rhomb stand for boys, squares stand for girls, arrows lead from a pupil to his/her best friend. Bold non-dashed arrows stand for pairs in the answer.
1,673
Title: Escaping on Beaveractor Time Limit: None seconds Memory Limit: None megabytes Problem Description: Don't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a *b*<=Γ—<=*b* square on a plane. Each point *x*,<=*y* (0<=≀<=*x*,<=*y*<=≀<=*b*) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transport. The campus obeys traffic rules: there are *n* arrows, parallel to the coordinate axes. The arrows do not intersect and do not touch each other. When the Beaveractor reaches some arrow, it turns in the arrow's direction and moves on until it either reaches the next arrow or gets outside the campus. The Beaveractor covers exactly one unit of space per one unit of time. You can assume that there are no obstacles to the Beaveractor. The BSA scientists want to transport the brand new Beaveractor to the "Academic Tractor" research institute and send the Smart Beaver to do his postgraduate studies and sharpen pencils. They have *q* plans, representing the Beaveractor's initial position (*x**i*,<=*y**i*), the initial motion vector *w**i* and the time *t**i* that have passed after the escape started. Your task is for each of the *q* plans to determine the Smart Beaver's position after the given time. Input Specification: The first line contains two integers: the number of traffic rules *n* and the size of the campus *b*, 0<=≀<=*n*, 1<=≀<=*b*. Next *n* lines contain the rules. Each line of the rules contains four space-separated integers *x*0, *y*0, *x*1, *y*1 β€” the beginning and the end of the arrow. It is guaranteed that all arrows are parallel to the coordinate axes and have no common points. All arrows are located inside the campus, that is, 0<=≀<=*x*0,<=*y*0,<=*x*1,<=*y*1<=≀<=*b* holds. Next line contains integer *q* β€” the number of plans the scientists have, 1<=≀<=*q*<=≀<=105. The *i*-th plan is represented by two integers, *x**i*, *y**i* are the Beaveractor's coordinates at the initial time, 0<=≀<=*x**i*,<=*y**i*<=≀<=*b*, character *w**i*, that takes value U, D, L, R and sets the initial direction up, down, to the left or to the right correspondingly (the Y axis is directed upwards), and *t**i* β€” the time passed after the escape started, 0<=≀<=*t**i*<=≀<=1015. - to get 30 points you need to solve the problem with constraints *n*,<=*b*<=≀<=30 (subproblem D1); - to get 60 points you need to solve the problem with constraints *n*,<=*b*<=≀<=1000 (subproblems D1+D2); - to get 100 points you need to solve the problem with constraints *n*,<=*b*<=≀<=105 (subproblems D1+D2+D3). Output Specification: Print *q* lines. Each line should contain two integers β€” the Beaveractor's coordinates at the final moment of time for each plan. If the Smart Beaver manages to leave the campus in time *t**i*, print the coordinates of the last point in the campus he visited. Demo Input: ['3 3\n0 0 0 1\n0 2 2 2\n3 3 2 3\n12\n0 0 L 0\n0 0 L 1\n0 0 L 2\n0 0 L 3\n0 0 L 4\n0 0 L 5\n0 0 L 6\n2 0 U 2\n2 0 U 3\n3 0 U 5\n1 3 D 2\n1 3 R 2\n'] Demo Output: ['0 0\n0 1\n0 2\n1 2\n2 2\n3 2\n3 2\n2 2\n3 2\n1 3\n2 2\n1 3\n'] Note: none
1,674
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value. However, all Mike has is lots of identical resistors with unit resistance *R*0<==<=1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements: 1. one resistor; 1. an element and one resistor plugged in sequence; 1. an element and one resistor plugged in parallel. With the consecutive connection the resistance of the new element equals *R*<==<=*R**e*<=+<=*R*0. With the parallel connection the resistance of the new element equals . In this case *R**e* equals the resistance of the element being connected. Mike needs to assemble an element with a resistance equal to the fraction . Determine the smallest possible number of resistors he needs to make such an element. Input Specification: The single input line contains two space-separated integers *a* and *b* (1<=≀<=*a*,<=*b*<=≀<=1018). It is guaranteed that the fraction is irreducible. It is guaranteed that a solution always exists. Output Specification: Print a single number β€” the answer to the problem. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier. Demo Input: ['1 1\n', '3 2\n', '199 200\n'] Demo Output: ['1\n', '3\n', '200\n'] Note: In the first sample, one resistor is enough. In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5305da389756aab6423d918a08ced468f05604df.png" style="max-width: 100.0%;max-height: 100.0%;"/>. We cannot make this element using two resistors.
1,675
Title: Chemistry Experiment Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found *n* test tubes with mercury numbered from 1 to *n* and decided to conduct an experiment. The experiment consists of *q* steps. On each step, one of the following actions occurs: 1. Diana pours all the contents from tube number *p**i* and then pours there exactly *x**i* liters of mercury. 1. Let's consider all the ways to add *v**i* liters of water into the tubes; for each way let's count the volume of liquid (water and mercury) in the tube with water with maximum amount of liquid; finally let's find the minimum among counted maximums. That is the number the students want to count. At that, the students don't actually pour the mercury. They perform calculations without changing the contents of the tubes. Unfortunately, the calculations proved to be too complex and the students asked you to help them. Help them conduct the described experiment. Input Specification: The first line contains two integers *n* and *q* (1<=≀<=*n*,<=*q*<=≀<=105) β€” the number of tubes ans the number of experiment steps. The next line contains *n* space-separated integers: *h*1,<=*h*2,<=...,<=*h**n* (0<=≀<=*h**i*<=≀<=109), where *h**i* is the volume of mercury in the *Ρ–*-th tube at the beginning of the experiment. The next *q* lines contain the game actions in the following format: - A line of form "1 *p**i* *x**i*" means an action of the first type (1<=≀<=*p**i*<=≀<=*n*;Β 0<=≀<=*x**i*<=≀<=109). - A line of form "2 *v**i*" means an action of the second type (1<=≀<=*v**i*<=≀<=1015). It is guaranteed that there is at least one action of the second type. It is guaranteed that all numbers that describe the experiment are integers. Output Specification: For each action of the second type print the calculated value. The answer will be considered correct if its relative or absolute error doesn't exceed 10<=-<=4. Demo Input: ['3 3\n1 2 0\n2 2\n1 2 1\n2 3\n', '4 5\n1 3 0 1\n2 3\n2 1\n1 3 2\n2 3\n2 4\n'] Demo Output: ['1.50000\n1.66667\n', '1.66667\n1.00000\n2.33333\n2.66667\n'] Note: none
1,676
Title: Power Defence Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya plays the Power Defence. He must pass the last level of the game. In order to do this he must kill the Main Villain, who moves in a straight line at speed 1 meter per second from the point (<=-<=∞,<=0) to the point (<=+<=∞,<=0) of the game world. In the points (*x*,<=1) and (*x*,<=<=-<=1), where *x* is an integer number, Vasya can build towers of three types: fire-tower, electric-tower or freezing-tower. However, it is not allowed to build two towers at the same point. Towers of each type have a certain action radius and the value of damage per second (except freezing-tower). If at some point the Main Villain is in the range of action of *k* freezing towers then his speed is decreased by *k*<=+<=1 times. The allowed number of towers of each type is known. It is necessary to determine the maximum possible damage we can inflict on the Main Villain. All distances in the problem are given in meters. The size of the Main Villain and the towers are so small, that they can be considered as points on the plane. The Main Villain is in the action radius of a tower if the distance between him and tower is less than or equal to the action radius of the tower. Input Specification: The first line contains three integer numbers *nf*,<=*ne* and *ns* β€” the maximum number of fire-towers, electric-towers and freezing-towers that can be built (0<=≀<=*nf*,<=*ne*,<=*ns*<=≀<=20,<=1<=≀<=*nf*<=+<=*ne*<=+<=*ns*<=≀<=20). The numbers are separated with single spaces. The second line contains three integer numbers *rf*,<=*re* and *rs* (1<=≀<=*rf*,<=*re*,<=*rs*<=≀<=1000) β€” the action radii of fire-towers, electric-towers and freezing-towers. The numbers are separated with single spaces. The third line contains two integer numbers *df* and *de* (1<=≀<=*df*,<=*de*<=≀<=1000) β€” the damage a fire-tower and an electronic-tower can inflict on the Main Villain per second (in the case when the Main Villain is in the action radius of the tower). The numbers are separated with single space. Output Specification: Print the only real number β€” the maximum possible damage to the Main Villain with absolute or relative error not more than 10<=-<=6. Demo Input: ['1 0 0\n10 10 10\n100 100\n', '1 0 1\n10 10 10\n100 100\n'] Demo Output: ['1989.97487421', '3979.94974843'] Note: In the first sample we've got one fire-tower that always inflicts the same damage, independently of its position. In the second sample we've got another freezing-tower of the same action radius. If we build the two towers opposite each other, then the Main Villain's speed will be two times lower, whenever he enters the fire-tower's action radius. That means that the enemy will be inflicted with twice more damage.
1,677
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user. The social network contains *n* registered profiles, numbered from 1 to *n*. Some pairs there are friends (the "friendship" relationship is mutual, that is, if *i* is friends with *j*, then *j* is also friends with *i*). Let's say that profiles *i* and *j* (*i*<=β‰ <=*j*) are doubles, if for any profile *k* (*k*<=β‰ <=*i*, *k*<=β‰ <=*j*) one of the two statements is true: either *k* is friends with *i* and *j*, or *k* isn't friends with either of them. Also, *i* and *j* can be friends or not be friends. Your task is to count the number of different unordered pairs (*i*,<=*j*), such that the profiles *i* and *j* are doubles. Note that the pairs are unordered, that is, pairs (*a*,<=*b*) and (*b*,<=*a*) are considered identical. Input Specification: The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*<=≀<=106, 0<=≀<=*m*<=≀<=106), β€” the number of profiles and the number of pairs of friends, correspondingly. Next *m* lines contains descriptions of pairs of friends in the format "*v* *u*", where *v* and *u* (1<=≀<=*v*,<=*u*<=≀<=*n*,<=*v*<=β‰ <=*u*) are numbers of profiles that are friends with each other. It is guaranteed that each unordered pair of friends occurs no more than once and no profile is friends with itself. Output Specification: Print the single integer β€” the number of unordered pairs of profiles that are doubles. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the %I64d specificator. Demo Input: ['3 3\n1 2\n2 3\n1 3\n', '3 0\n', '4 1\n1 3\n'] Demo Output: ['3\n', '3\n', '2\n'] Note: In the first and second sample any two profiles are doubles. In the third sample the doubles are pairs of profiles (1, 3) and (2, 4).
1,678
Title: Pasha and Phone Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly *n* digits. Also Pasha has a number *k* and two sequences of length *n*<=/<=*k* (*n* is divisible by *k*) *a*1,<=*a*2,<=...,<=*a**n*<=/<=*k* and *b*1,<=*b*2,<=...,<=*b**n*<=/<=*k*. Let's split the phone number into blocks of length *k*. The first block will be formed by digits from the phone number that are on positions 1, 2,..., *k*, the second block will be formed by digits from the phone number that are on positions *k*<=+<=1, *k*<=+<=2, ..., 2Β·*k* and so on. Pasha considers a phone number good, if the *i*-th block doesn't start from the digit *b**i* and is divisible by *a**i* if represented as an integer. To represent the block of length *k* as an integer, let's write it out as a sequence *c*1, *c*2,...,*c**k*. Then the integer is calculated as the result of the expression *c*1Β·10*k*<=-<=1<=+<=*c*2Β·10*k*<=-<=2<=+<=...<=+<=*c**k*. Pasha asks you to calculate the number of good phone numbers of length *n*, for the given *k*, *a**i* and *b**i*. As this number can be too big, print it modulo 109<=+<=7. Input Specification: The first line of the input contains two integers *n* and *k* (1<=≀<=*n*<=≀<=100<=000, 1<=≀<=*k*<=≀<=*min*(*n*,<=9))Β β€” the length of all phone numbers and the length of each block, respectively. It is guaranteed that *n* is divisible by *k*. The second line of the input contains *n*<=/<=*k* space-separated positive integersΒ β€” sequence *a*1,<=*a*2,<=...,<=*a**n*<=/<=*k* (1<=≀<=*a**i*<=&lt;<=10*k*). The third line of the input contains *n*<=/<=*k* space-separated positive integersΒ β€” sequence *b*1,<=*b*2,<=...,<=*b**n*<=/<=*k* (0<=≀<=*b**i*<=≀<=9). Output Specification: Print a single integerΒ β€” the number of good phone numbers of length *n* modulo 109<=+<=7. Demo Input: ['6 2\n38 56 49\n7 3 4\n', '8 2\n1 22 3 44\n5 4 3 2\n'] Demo Output: ['8\n', '32400\n'] Note: In the first test sample good phone numbers are: 000000, 000098, 005600, 005698, 380000, 380098, 385600, 385698.
1,679
Title: Longest Regular Bracket Sequence Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting Β«+Β» and Β«1Β» into it we can get a correct mathematical expression. For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are regular, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not. You are given a string of Β«(Β» and Β«)Β» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well. Input Specification: The first line of the input file contains a non-empty string, consisting of Β«(Β» and Β«)Β» characters. Its length does not exceed 106. Output Specification: Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1". Demo Input: [')((())))(()())\n', '))(\n'] Demo Output: ['6 2\n', '0 1\n'] Note: none
1,680
Title: A Simple Task Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges. Input Specification: The first line of input contains two integers *n* and *m* (1<=≀<=*n*<=≀<=19, 0<=≀<=*m*) – respectively the number of vertices and edges of the graph. Each of the subsequent *m* lines contains two integers *a* and *b*, (1<=≀<=*a*,<=*b*<=≀<=*n*, *a*<=β‰ <=*b*) indicating that vertices *a* and *b* are connected by an undirected edge. There is no more than one edge connecting any pair of vertices. Output Specification: Output the number of cycles in the given graph. Demo Input: ['4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n'] Demo Output: ['7\n'] Note: The example graph is a clique and contains four cycles of length 3 and three cycles of length 4.
1,681
Title: Opponents Time Limit: None seconds Memory Limit: None megabytes Problem Description: Arya has *n* opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya. For each opponent Arya knows his scheduleΒ β€” whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents. Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents. Input Specification: The first line of the input contains two integers *n* and *d* (1<=≀<=*n*,<=*d*<=≀<=100)Β β€” the number of opponents and the number of days, respectively. The *i*-th of the following *d* lines contains a string of length *n* consisting of characters '0' and '1'. The *j*-th character of this string is '0' if the *j*-th opponent is going to be absent on the *i*-th day. Output Specification: Print the only integerΒ β€” the maximum number of consecutive days that Arya will beat all present opponents. Demo Input: ['2 2\n10\n00\n', '4 1\n0100\n', '4 5\n1101\n1111\n0110\n1011\n1111\n'] Demo Output: ['2\n', '1\n', '2\n'] Note: In the first and the second samples, Arya will beat all present opponents each of the *d* days. In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4.
1,682
Title: Bus Time Limit: None seconds Memory Limit: None megabytes Problem Description: A bus moves along the coordinate line *Ox* from the point *x*<==<=0 to the point *x*<==<=*a*. After starting from the point *x*<==<=0, it reaches the point *x*<==<=*a*, immediately turns back and then moves to the point *x*<==<=0. After returning to the point *x*<==<=0 it immediately goes back to the point *x*<==<=*a* and so on. Thus, the bus moves from *x*<==<=0 to *x*<==<=*a* and back. Moving from the point *x*<==<=0 to *x*<==<=*a* or from the point *x*<==<=*a* to *x*<==<=0 is called a bus journey. In total, the bus must make *k* journeys. The petrol tank of the bus can hold *b* liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank. There is a gas station in point *x*<==<=*f*. This point is between points *x*<==<=0 and *x*<==<=*a*. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain *b* liters of gasoline. What is the minimum number of times the bus needs to refuel at the point *x*<==<=*f* to make *k* journeys? The first journey starts in the point *x*<==<=0. Input Specification: The first line contains four integers *a*, *b*, *f*, *k* (0<=&lt;<=*f*<=&lt;<=*a*<=≀<=106, 1<=≀<=*b*<=≀<=109, 1<=≀<=*k*<=≀<=104) β€” the endpoint of the first bus journey, the capacity of the fuel tank of the bus, the point where the gas station is located, and the required number of journeys. Output Specification: Print the minimum number of times the bus needs to refuel to make *k* journeys. If it is impossible for the bus to make *k* journeys, print -1. Demo Input: ['6 9 2 4\n', '6 10 2 4\n', '6 5 4 3\n'] Demo Output: ['4\n', '2\n', '-1\n'] Note: In the first example the bus needs to refuel during each journey. In the second example the bus can pass 10 units of distance without refueling. So the bus makes the whole first journey, passes 4 units of the distance of the second journey and arrives at the point with the gas station. Then it can refuel its tank, finish the second journey and pass 2 units of distance from the third journey. In this case, it will again arrive at the point with the gas station. Further, he can refill the tank up to 10 liters to finish the third journey and ride all the way of the fourth journey. At the end of the journey the tank will be empty. In the third example the bus can not make all 3 journeys because if it refuels during the second journey, the tanks will contain only 5 liters of gasoline, but the bus needs to pass 8 units of distance until next refueling.
1,683
Title: Reversing Encryption Time Limit: None seconds Memory Limit: None megabytes Problem Description: A string $s$ of length $n$ can be encrypted by the following algorithm: - iterate over all divisors of $n$ in decreasing order (i.e. from $n$ to $1$), - for each divisor $d$, reverse the substring $s[1 \dots d]$ (i.e. the substring which starts at position $1$ and ends at position $d$). For example, the above algorithm applied to the string $s$="codeforces" leads to the following changes: "codeforces" $\to$ "secrofedoc" $\to$ "orcesfedoc" $\to$ "rocesfedoc" $\to$ "rocesfedoc" (obviously, the last reverse operation doesn't change the string because $d=1$). You are given the encrypted string $t$. Your task is to decrypt this string, i.e., to find a string $s$ such that the above algorithm results in string $t$. It can be proven that this string $s$ always exists and is unique. Input Specification: The first line of input consists of a single integer $n$ ($1 \le n \le 100$) β€” the length of the string $t$. The second line of input consists of the string $t$. The length of $t$ is $n$, and it consists only of lowercase Latin letters. Output Specification: Print a string $s$ such that the above algorithm results in $t$. Demo Input: ['10\nrocesfedoc\n', '16\nplmaetwoxesisiht\n', '1\nz\n'] Demo Output: ['codeforces\n', 'thisisexampletwo\n', 'z\n'] Note: The first example is described in the problem statement.
1,684
Title: Police Recruits Time Limit: None seconds Memory Limit: None megabytes Problem Description: The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated. Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated. Input Specification: The first line of input will contain an integer *n*Β (1<=≀<=*n*<=≀<=105), the number of events. The next line will contain *n* space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time. Output Specification: Print a single integer, the number of crimes which will go untreated. Demo Input: ['3\n-1 -1 1\n', '8\n1 -1 1 -1 -1 1 1 1\n', '11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1\n'] Demo Output: ['2\n', '1\n', '8\n'] Note: Lets consider the second example: 1. Firstly one person is hired. 1. Then crime appears, the last hired person will investigate this crime. 1. One more person is hired. 1. One more crime appears, the last hired person will investigate this crime. 1. Crime appears. There is no free policeman at the time, so this crime will go untreated. 1. One more person is hired. 1. One more person is hired. 1. One more person is hired. The answer is one, as one crime (on step 5) will go untreated.
1,685
Title: Eugeny and Play List Time Limit: None seconds Memory Limit: None megabytes Problem Description: Eugeny loves listening to music. He has *n* songs in his play list. We know that song number *i* has the duration of *t**i* minutes. Eugeny listens to each song, perhaps more than once. He listens to song number *i* *c**i* times. Eugeny's play list is organized as follows: first song number 1 plays *c*1 times, then song number 2 plays *c*2 times, ..., in the end the song number *n* plays *c**n* times. Eugeny took a piece of paper and wrote out *m* moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment *x* means that Eugeny wants to know which song was playing during the *x*-th minute of his listening to the play list. Help Eugeny and calculate the required numbers of songs. Input Specification: The first line contains two integers *n*, *m* (1<=≀<=*n*,<=*m*<=≀<=105). The next *n* lines contain pairs of integers. The *i*-th line contains integers *c**i*,<=*t**i* (1<=≀<=*c**i*,<=*t**i*<=≀<=109) β€” the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains *m* positive integers *v*1,<=*v*2,<=...,<=*v**m*, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time *v**i*, when the music doesn't play any longer. It is guaranteed that *v**i*<=&lt;<=*v**i*<=+<=1 (*i*<=&lt;<=*m*). The moment of time *v**i* means that Eugeny wants to know which song was playing during the *v**i*-th munite from the start of listening to the playlist. Output Specification: Print *m* integers β€” the *i*-th number must equal the number of the song that was playing during the *v**i*-th minute after Eugeny started listening to the play list. Demo Input: ['1 2\n2 8\n1 16\n', '4 9\n1 2\n2 1\n1 1\n2 2\n1 2 3 4 5 6 7 8 9\n'] Demo Output: ['1\n1\n', '1\n1\n2\n2\n3\n4\n4\n4\n4\n'] Note: none
1,686
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of *n* plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble. But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts: - each cup contains a mark β€” a number from 1 to *n*; all marks on the cups are distinct; - the magician shuffles the cups in *m* operations, each operation looks like that: take a cup marked *x**i*, sitting at position *y**i* in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position). When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist. Input Specification: The first line contains integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=106). Each of the next *m* lines contains a couple of integers. The *i*-th line contains integers *x**i*, *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*) β€” the description of the *i*-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order. Output Specification: If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print *n* distinct integers, each from 1 to *n*: the *i*-th number should represent the mark on the cup that initially is in the row in position *i*. If there are multiple correct answers, you should print the lexicographically minimum one. Demo Input: ['2 1\n2 1\n', '3 2\n1 2\n1 1\n', '3 3\n1 3\n2 3\n1 3\n'] Demo Output: ['2 1 \n', '2 1 3 \n', '-1\n'] Note: none
1,687
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string *s* of length *n* comes out from Tavas' mouth instead. Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on *s*. Malekas has a favorite string *p*. He determined all positions *x*1<=&lt;<=*x*2<=&lt;<=...<=&lt;<=*x**k* where *p* matches *s*. More formally, for each *x**i* (1<=≀<=*i*<=≀<=*k*) he condition *s**x**i**s**x**i*<=+<=1... *s**x**i*<=+<=|*p*|<=-<=1<==<=*p* is fullfilled. Then Malekas wrote down one of subsequences of *x*1,<=*x*2,<=... *x**k* (possibly, he didn't write anything) on a piece of paper. Here a sequence *b* is a subsequence of sequence *a* if and only if we can turn *a* into *b* by removing some of its elements (maybe no one of them or all). After Tavas woke up, Malekas told him everything. He couldn't remember string *s*, but he knew that both *p* and *s* only contains lowercase English letters and also he had the subsequence he had written on that piece of paper. Tavas wonders, what is the number of possible values of *s*? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him. Answer can be very large, so Tavas wants you to print the answer modulo 109<=+<=7. Input Specification: The first line contains two integers *n* and *m*, the length of *s* and the length of the subsequence Malekas wrote down (1<=≀<=*n*<=≀<=106 and 0<=≀<=*m*<=≀<=*n*<=-<=|*p*|<=+<=1). The second line contains string *p* (1<=≀<=|*p*|<=≀<=*n*). The next line contains *m* space separated integers *y*1,<=*y*2,<=...,<=*y**m*, Malekas' subsequence (1<=≀<=*y*1<=&lt;<=*y*2<=&lt;<=...<=&lt;<=*y**m*<=≀<=*n*<=-<=|*p*|<=+<=1). Output Specification: In a single line print the answer modulo 1000<=000<=007. Demo Input: ['6 2\nioi\n1 3\n', '5 2\nioi\n1 2\n'] Demo Output: ['26\n', '0\n'] Note: In the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy. Here |*x*| denotes the length of string x. Please note that it's possible that there is no such string (answer is 0).
1,688
Title: Cards Time Limit: None seconds Memory Limit: None megabytes Problem Description: Catherine has a deck of *n* cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions: - take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; - take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color. She repeats this process until there is only one card left. What are the possible colors for the final card? Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=200)Β β€” the total number of cards. The next line contains a string *s* of length *n* β€” the colors of the cards. *s* contains only the characters 'B', 'G', and 'R', representing blue, green, and red, respectively. Output Specification: Print a single string of up to three charactersΒ β€” the possible colors of the final card (using the same symbols as the input) in alphabetical order. Demo Input: ['2\nRB\n', '3\nGRG\n', '5\nBBBBB\n'] Demo Output: ['G\n', 'BR\n', 'B\n'] Note: In the first sample, Catherine has one red card and one blue card, which she must exchange for a green card. In the second sample, Catherine has two green cards and one red card. She has two options: she can exchange the two green cards for a green card, then exchange the new green card and the red card for a blue card. Alternatively, she can exchange a green and a red card for a blue card, then exchange the blue card and remaining green card for a red card. In the third sample, Catherine only has blue cards, so she can only exchange them for more blue cards.
1,689
Title: International Olympiad Time Limit: None seconds Memory Limit: None megabytes Problem Description: International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where *y* stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string *y* that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition. For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995. You are given a list of abbreviations. For each of them determine the year it stands for. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=1000)Β β€” the number of abbreviations to process. Then *n* lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits. Output Specification: For each abbreviation given in the input, find the year of the corresponding Olympiad. Demo Input: ["5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0\n", "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999\n"] Demo Output: ['2015\n12015\n1991\n1989\n1990\n', '1989\n1999\n2999\n9999\n'] Note: none
1,690
Title: Sheep Time Limit: None seconds Memory Limit: None megabytes Problem Description: Information technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming! A large farm has a meadow with grazing sheep. Overall there are *n* sheep and each of them contains a unique number from 1 to *n* β€” because the sheep need to be distinguished and you need to remember information about each one, and they are so much alike! The meadow consists of infinite number of regions numbered from 1 to infinity. It's known that sheep *i* likes regions from *l**i* to *r**i*. There are two shepherds taking care of the sheep: First and Second. First wakes up early in the morning and leads the sheep graze on the lawn. Second comes in the evening and collects all the sheep. One morning, First woke up a little later than usual, and had no time to lead the sheep graze on the lawn. So he tied together every two sheep if there is a region they both like. First thought that it would be better β€” Second would have less work in the evening, because sheep won't scatter too much, being tied to each other! In the evening Second came on the lawn, gathered the sheep and tried to line them up in a row. But try as he might, the sheep wouldn't line up as Second want! Second had neither the strength nor the ability to untie the sheep so he left them as they are, but with one condition: he wanted to line up the sheep so that the maximum distance between two tied sheep was as small as possible. The distance between the sheep is the number of sheep in the ranks that are between these two. Help Second find the right arrangement. Input Specification: The first input line contains one integer *n* (1<=≀<=*n*<=≀<=2000). Each of the following *n* lines contains two integers *l**i* and *r**i* (1<=≀<=*l**i*,<=*r**i*<=≀<=109;Β *l**i*<=≀<=*r**i*). Output Specification: In the single output line print *n* space-separated numbers β€” the sought arrangement of the sheep. The *i*-th value in the line must represent the number of the sheep that took the *i*-th place from left in the optimal arrangement line. If there are multiple optimal arrangements, print any of them. Demo Input: ['3\n1 3\n5 7\n2 4\n', '5\n1 5\n2 4\n3 6\n1 7\n2 6\n', '4\n1 3\n4 6\n5 7\n2 3\n'] Demo Output: ['1 3 2', '2 1 3 5 4', '1 4 2 3'] Note: none
1,691
Title: Valued Keys Time Limit: None seconds Memory Limit: None megabytes Problem Description: You found a mysterious function *f*. The function takes two strings *s*1 and *s*2. These strings must consist only of lowercase English letters, and must be the same length. The output of the function *f* is another string of the same length. The *i*-th character of the output is equal to the minimum of the *i*-th character of *s*1 and the *i*-th character of *s*2. For example, *f*("ab", "ba") = "aa", and *f*("nzwzl", "zizez") = "niwel". You found two strings *x* and *y* of the same length and consisting of only lowercase English letters. Find any string *z* such that *f*(*x*,<=*z*)<==<=*y*, or print -1 if no such string *z* exists. Input Specification: The first line of input contains the string *x*. The second line of input contains the string *y*. Both *x* and *y* consist only of lowercase English letters, *x* and *y* have same length and this length is between 1 and 100. Output Specification: If there is no string *z* such that *f*(*x*,<=*z*)<==<=*y*, print -1. Otherwise, print a string *z* such that *f*(*x*,<=*z*)<==<=*y*. If there are multiple possible answers, print any of them. The string *z* should be the same length as *x* and *y* and consist only of lowercase English letters. Demo Input: ['ab\naa\n', 'nzwzl\nniwel\n', 'ab\nba\n'] Demo Output: ['ba\n', 'xiyez\n', '-1\n'] Note: The first case is from the statement. Another solution for the second case is "zizez" There is no solution for the third case. That is, there is no *z* such that *f*("ab", *z*) =  "ba".
1,692
Title: War of the Corporations Time Limit: None seconds Memory Limit: None megabytes Problem Description: A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence. Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring. Substring is a continuous subsequence of a string. Input Specification: The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100<=000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters. Output Specification: Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring. Demo Input: ['intellect\ntell\n', 'google\napple\n', 'sirisiri\nsir\n'] Demo Output: ['1', '0', '2'] Note: In the first sample AI's name may be replaced with "int#llect". In the second sample Gogol can just keep things as they are. In the third sample one of the new possible names of AI may be "s#ris#ri".
1,693
Title: Approximating a Constant Range Time Limit: None seconds Memory Limit: None megabytes Problem Description: When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challengingΒ β€” but why not make a similar programming contest problem while we're at it? You're given a sequence of *n* data points *a*1,<=...,<=*a**n*. There aren't any big jumps between consecutive data pointsΒ β€” for each 1<=≀<=*i*<=&lt;<=*n*, it's guaranteed that |*a**i*<=+<=1<=-<=*a**i*|<=≀<=1. A range [*l*,<=*r*] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let *M* be the maximum and *m* the minimum value of *a**i* for *l*<=≀<=*i*<=≀<=*r*; the range [*l*,<=*r*] is almost constant if *M*<=-<=*m*<=≀<=1. Find the length of the longest almost constant range. Input Specification: The first line of the input contains a single integer *n* (2<=≀<=*n*<=≀<=100<=000)Β β€” the number of data points. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=100<=000). Output Specification: Print a single numberΒ β€” the maximum length of an almost constant range of the given sequence. Demo Input: ['5\n1 2 3 3 2\n', '11\n5 4 5 5 6 7 8 8 8 7 6\n'] Demo Output: ['4\n', '5\n'] Note: In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].
1,694
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far. The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall. Traditionally GUC has *n* professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from 1 to *n*, with 1 being the most senior professor and *n* being the most junior professor. The ceremonial hall has *n* seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, *m* pairs of seats are in "senior-junior" relation, and the tradition requires that for all *m* pairs of seats (*a**i*,<=*b**i*) the professor seated in "senior" position *a**i* should be more senior than the professor seated in "junior" position *b**i*. GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that: - The seating of the professors changes every year. - Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall. - Each consecutive year lexicographically next arrangement of the professors is used. The arrangement of the professors is the list of *n* integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc. Given *n*, the number of professors, *y*, the current year and *m* pairs of restrictions, output the arrangement of the professors for this year. Input Specification: The first line contains three integers *n*, *y* and *m* (1<=≀<=*n*<=≀<=16,<=2001<=≀<=*y*<=≀<=1018,<=0<=≀<=*m*<=≀<=100) β€” the number of professors, the year for which the arrangement should be computed, and the number of pairs of seats for which the seniority relation should be kept, respectively. The next *m* lines contain one pair of integers each, "*a**i* *b**i*", indicating that professor on the *a**i*-th seat is more senior than professor on the *b**i*-th seat (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*). Some pair may be listed more than once. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin stream (you may also use the %I64d specificator). Output Specification: Print the order in which the professors should be seated in the requested year. If by this year the GUC would have ran out of arrangements, or the given "senior-junior" relation are contradictory, print "The times have changed" (without quotes). Demo Input: ['3 2001 2\n1 2\n2 3\n', '7 2020 6\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n', '10 3630801 0\n', '3 2001 3\n1 2\n2 3\n3 1\n'] Demo Output: ['1 2 3\n', '1 2 3 7 4 6 5\n', 'The times have changed\n', 'The times have changed\n'] Note: In the first example the lexicographically first order of seating is 1 2 3. In the third example the GUC will run out of arrangements after the year 3630800. In the fourth example there are no valid arrangements for the seating. The lexicographical comparison of arrangements is performed by the &lt; operator in modern programming languages. The arrangement *a* is lexicographically less that the arrangement *b*, if there exists such *i* (1 ≀ *i* ≀ *n*), that *a*<sub class="lower-index">*i*</sub> &lt; *b*<sub class="lower-index">*i*</sub>, and for any *j* (1 ≀ *j* &lt; *i*) *a*<sub class="lower-index">*j*</sub> = *b*<sub class="lower-index">*j*</sub>.
1,695
Title: Olympiad in Programming and Sports Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* students at Berland State University. Every student has two skills, each measured as a number: *a**i* β€” the programming skill and *b**i* β€” the sports skill. It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in the programming track and one to take part in the sports track. There should be exactly *p* students in the programming team and exactly *s* students in the sports team. A student can't be a member of both teams. The university management considers that the strength of the university on the Olympiad is equal to the sum of two values: the programming team strength and the sports team strength. The strength of a team is the sum of skills of its members in the corresponding area, so the strength of the programming team is the sum of all *a**i* and the strength of the sports team is the sum of all *b**i* over corresponding team members. Help Berland State University to compose two teams to maximize the total strength of the university on the Olympiad. Input Specification: The first line contains three positive integer numbers *n*, *p* and *s* (2<=≀<=*n*<=≀<=3000, *p*<=+<=*s*<=≀<=*n*) β€” the number of students, the size of the programming team and the size of the sports team. The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=3000), where *a**i* is the programming skill of the *i*-th student. The third line contains *n* positive integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≀<=*b**i*<=≀<=3000), where *b**i* is the sports skill of the *i*-th student. Output Specification: In the first line, print the the maximum strength of the university on the Olympiad. In the second line, print *p* numbers β€” the members of the programming team. In the third line, print *s* numbers β€” the members of the sports team. The students are numbered from 1 to *n* as they are given in the input. All numbers printed in the second and in the third lines should be distinct and can be printed in arbitrary order. If there are multiple solutions, print any of them. Demo Input: ['5 2 2\n1 3 4 5 2\n5 3 2 1 4\n', '4 2 2\n10 8 8 3\n10 7 9 4\n', '5 3 1\n5 2 5 1 7\n6 3 1 6 3\n'] Demo Output: ['18\n3 4 \n1 5 \n', '31\n1 2 \n3 4 \n', '23\n1 3 5 \n4 \n'] Note: none
1,696
Title: If at first you don't succeed... Time Limit: None seconds Memory Limit: None megabytes Problem Description: Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaurant, some of themΒ β€” in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by $A$ students, BeaverKingΒ β€” by $B$ students and $C$ students visited both restaurants. Vasya also knows that there are $N$ students in his group. Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time? Input Specification: The first line contains four integersΒ β€” $A$, $B$, $C$ and $N$ ($0 \leq A, B, C, N \leq 100$). Output Specification: If a distribution of $N$ students exists in which $A$ students visited BugDonalds, $B$ β€” BeaverKing, $C$ β€” both of the restaurants and at least one student is left home (it is known that Vasya didn't pass the exam and stayed at home), output one integerΒ β€” amount of students (including Vasya) who did not pass the exam. If such a distribution does not exist and Vasya made a mistake while determining the numbers $A$, $B$, $C$ or $N$ (as in samples 2 and 3), output $-1$. Demo Input: ['10 10 5 20\n', '2 2 0 4\n', '2 2 2 1\n'] Demo Output: ['5', '-1', '-1'] Note: The first sample describes following situation: $5$ only visited BugDonalds, $5$ students only visited BeaverKing, $5$ visited both of them and $5$ students (including Vasya) didn't pass the exam. In the second sample $2$ students only visited BugDonalds and $2$ only visited BeaverKing, but that means all $4$ students in group passed the exam which contradicts the fact that Vasya didn't pass meaning that this situation is impossible. The third sample describes a situation where $2$ students visited BugDonalds but the group has only $1$ which makes it clearly impossible.
1,697
Title: Green and Black Tea Time Limit: None seconds Memory Limit: None megabytes Problem Description: Innokentiy likes tea very much and today he wants to drink exactly *n* cups of tea. He would be happy to drink more but he had exactly *n* tea bags, *a* of them are green and *b* are black. Innokentiy doesn't like to drink the same tea (green or black) more than *k* times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink *n* cups of tea, without drinking the same tea more than *k* times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once. Input Specification: The first line contains four integers *n*, *k*, *a* and *b* (1<=≀<=*k*<=≀<=*n*<=≀<=105, 0<=≀<=*a*,<=*b*<=≀<=*n*)Β β€” the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that *a*<=+<=*b*<==<=*n*. Output Specification: If it is impossible to drink *n* cups of tea, print "NO" (without quotes). Otherwise, print the string of the length *n*, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them. Demo Input: ['5 1 3 2\n', '7 2 2 5\n', '4 3 4 0\n'] Demo Output: ['GBGBG\n', 'BBGBGBB', 'NO\n'] Note: none
1,698
Title: Lada Malina Time Limit: None seconds Memory Limit: None megabytes Problem Description: After long-term research and lots of experiments leading Megapolian automobile manufacturer Β«AutoVozΒ» released a brand new car model named Β«Lada MalinaΒ». One of the most impressive features of Β«Lada MalinaΒ» is its highly efficient environment-friendly engines. Consider car as a point in *Oxy* plane. Car is equipped with *k* engines numbered from 1 to *k*. Each engine is defined by its velocity vector whose coordinates are (*vx**i*,<=*vy**i*) measured in distance units per day. An engine may be turned on at any level *w**i*, that is a real number between <=-<=1 and <=+<=1 (inclusive) that result in a term of (*w**i*Β·*vx**i*,<=*w**i*Β·*vy**i*) in the final car velocity. Namely, the final car velocity is equal to Formally, if car moves with constant values of *w**i* during the whole day then its *x*-coordinate will change by the first component of an expression above, and its *y*-coordinate will change by the second component of an expression above. For example, if all *w**i* are equal to zero, the car won't move, and if all *w**i* are equal to zero except *w*1<==<=1, then car will move with the velocity of the first engine. There are *n* factories in Megapolia, *i*-th of them is located in (*fx**i*,<=*fy**i*). On the *i*-th factory there are *a**i* cars Β«Lada MalinaΒ» that are ready for operation. As an attempt to increase sales of a new car, Β«AutoVozΒ» is going to hold an international exposition of cars. There are *q* options of exposition location and time, in the *i*-th of them exposition will happen in a point with coordinates (*px**i*,<=*py**i*) in *t**i* days. Of course, at the Β«AutoVozΒ» is going to bring as much new cars from factories as possible to the place of exposition. Cars are going to be moved by enabling their engines on some certain levels, such that at the beginning of an exposition car gets exactly to the exposition location. However, for some of the options it may be impossible to bring cars from some of the factories to the exposition location by the moment of an exposition. Your task is to determine for each of the options of exposition location and time how many cars will be able to get there by the beginning of an exposition. Input Specification: The first line of input contains three integers *k*,<=*n*,<=*q* (2<=≀<=*k*<=≀<=10, 1<=≀<=*n*<=≀<=105, 1<=≀<=*q*<=≀<=105), the number of engines of Β«Lada MalinaΒ», number of factories producing Β«Lada MalinaΒ» and number of options of an exposition time and location respectively. The following *k* lines contain the descriptions of Β«Lada MalinaΒ» engines. The *i*-th of them contains two integers *vx**i*, *vy**i* (<=-<=1000<=≀<=*vx**i*,<=*vy**i*<=≀<=1000) defining the velocity vector of the *i*-th engine. Velocity vector can't be zero, i.e. at least one of *vx**i* and *vy**i* is not equal to zero. It is guaranteed that no two velosity vectors are collinear (parallel). Next *n* lines contain the descriptions of factories. The *i*-th of them contains two integers *fx**i*, *fy**i*, *a**i* (<=-<=109<=≀<=*fx**i*,<=*fy**i*<=≀<=109, 1<=≀<=*a**i*<=≀<=109) defining the coordinates of the *i*-th factory location and the number of cars that are located there. The following *q* lines contain the descriptions of the car exposition. The *i*-th of them contains three integers *px**i*, *py**i*, *t**i* (<=-<=109<=≀<=*px**i*,<=*py**i*<=≀<=109, 1<=≀<=*t**i*<=≀<=105) defining the coordinates of the exposition location and the number of days till the exposition start in the *i*-th option. Output Specification: For each possible option of the exposition output the number of cars that will be able to get to the exposition location by the moment of its beginning. Demo Input: ['2 4 1\n1 1\n-1 1\n2 3 1\n2 -2 1\n-2 1 1\n-2 -2 1\n0 0 2\n', '3 4 3\n2 0\n-1 1\n-1 -2\n-3 0 6\n1 -2 1\n-3 -7 3\n3 2 2\n-1 -4 1\n0 4 2\n6 0 1\n'] Demo Output: ['3\n', '4\n9\n0\n'] Note: Images describing sample tests are given below. Exposition options are denoted with crosses, factories are denoted with points. Each factory is labeled with a number of cars that it has. First sample test explanation: - Car from the first factory is not able to get to the exposition location in time. - Car from the second factory can get to the exposition in time if we set *w*<sub class="lower-index">1</sub> = 0, *w*<sub class="lower-index">2</sub> = 1. - Car from the third factory can get to the exposition in time if we set <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1a41eaee1a8903558be190d96f56b1bfe60e3ba9.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a8b87da549f125113bd6a37b75809d13a7c05c07.png" style="max-width: 100.0%;max-height: 100.0%;"/>. - Car from the fourth factory can get to the exposition in time if we set *w*<sub class="lower-index">1</sub> = 1, *w*<sub class="lower-index">2</sub> = 0.
1,699