task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: Coloring a Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a rooted tree with *n* vertices. The vertices are numbered from 1 to *n*, the root is the vertex number 1. Each vertex has a color, let's denote the color of vertex *v* by *c**v*. Initially *c**v*<==<=0. You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex *v* and a color *x*, and then color all vectices in the subtree of *v* (including *v* itself) in color *x*. In other words, for every vertex *u*, such that the path from root to *u* passes through *v*, set *c**u*<==<=*x*. It is guaranteed that you have to color each vertex in a color different from 0. You can learn what a rooted tree is using the link: [https://en.wikipedia.org/wiki/Tree_(graph_theory)](https://en.wikipedia.org/wiki/Tree_(graph_theory)). Input Specification: The first line contains a single integer *n* (2<=≤<=*n*<=≤<=104) — the number of vertices in the tree. The second line contains *n*<=-<=1 integers *p*2,<=*p*3,<=...,<=*p**n* (1<=≤<=*p**i*<=&lt;<=*i*), where *p**i* means that there is an edge between vertices *i* and *p**i*. The third line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=*n*), where *c**i* is the color you should color the *i*-th vertex into. It is guaranteed that the given graph is a tree. Output Specification: Print a single integer — the minimum number of steps you have to perform to color the tree into given colors. Demo Input: ['6\n1 2 2 1 5\n2 1 1 1 1 1\n', '7\n1 1 2 3 1 4\n3 3 1 1 1 2 3\n'] Demo Output: ['3\n', '5\n'] Note: The tree from the first sample is shown on the picture (numbers are vetices' indices): <img class="tex-graphics" src="https://espresso.codeforces.com/10324ccdc37f95343acc4f3c6050d8c334334ffa.png" style="max-width: 100.0%;max-height: 100.0%;"/> On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors): <img class="tex-graphics" src="https://espresso.codeforces.com/1c7bb267e2c1a006132248a43121400189309e2f.png" style="max-width: 100.0%;max-height: 100.0%;"/> On seond step we color all vertices in the subtree of vertex 5 into color 1: <img class="tex-graphics" src="https://espresso.codeforces.com/2201a6d49b89ba850ff0d0bdcbb3f8e9dd3871a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> On third step we color all vertices in the subtree of vertex 2 into color 1: <img class="tex-graphics" src="https://espresso.codeforces.com/6fa977fcdebdde94c47695151e0427b33d0102c5.png" style="max-width: 100.0%;max-height: 100.0%;"/> The tree from the second sample is shown on the picture (numbers are vetices' indices): <img class="tex-graphics" src="https://espresso.codeforces.com/d70f9ae72a2ed429dd6531cac757e375dd3c953d.png" style="max-width: 100.0%;max-height: 100.0%;"/> On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors): <img class="tex-graphics" src="https://espresso.codeforces.com/7289e8895d0dd56c47b6b17969b9cf77b36786b5.png" style="max-width: 100.0%;max-height: 100.0%;"/> On second step we color all vertices in the subtree of vertex 3 into color 1: <img class="tex-graphics" src="https://espresso.codeforces.com/819001df7229138db3a407713744d1e3be88b64e.png" style="max-width: 100.0%;max-height: 100.0%;"/> On third step we color all vertices in the subtree of vertex 6 into color 2: <img class="tex-graphics" src="https://espresso.codeforces.com/80ebbd870a0a339636a21b9acdaf9de046458b43.png" style="max-width: 100.0%;max-height: 100.0%;"/> On fourth step we color all vertices in the subtree of vertex 4 into color 1: <img class="tex-graphics" src="https://espresso.codeforces.com/ed836aa723ac0176abde4e32988e3ac205014e93.png" style="max-width: 100.0%;max-height: 100.0%;"/> On fith step we color all vertices in the subtree of vertex 7 into color 3: <img class="tex-graphics" src="https://espresso.codeforces.com/8132909e11b41c27b8df2f0b0c10bc841f35e58a.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,000
Title: st-Spanning Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an undirected connected graph consisting of *n* vertices and *m* edges. There are no loops and no multiple edges in the graph. You are also given two distinct vertices *s* and *t*, and two values *d**s* and *d**t*. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex *s* doesn't exceed *d**s*, and the degree of the vertex *t* doesn't exceed *d**t*, or determine, that there is no such spanning tree. The spanning tree of the graph *G* is a subgraph which is a tree and contains all vertices of the graph *G*. In other words, it is a connected graph which contains *n*<=-<=1 edges and can be obtained by removing some of the edges from *G*. The degree of a vertex is the number of edges incident to this vertex. Input Specification: The first line of the input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=200<=000, 1<=≤<=*m*<=≤<=*min*(400<=000,<=*n*·(*n*<=-<=1)<=/<=2)) — the number of vertices and the number of edges in the graph. The next *m* lines contain the descriptions of the graph's edges. Each of the lines contains two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*, *u*<=≠<=*v*) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected. The last line contains four integers *s*, *t*, *d**s*, *d**t* (1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*, 1<=≤<=*d**s*,<=*d**t*<=≤<=*n*<=-<=1). Output Specification: If the answer doesn't exist print "No" (without quotes) in the only line of the output. Otherwise, in the first line print "Yes" (without quotes). In the each of the next (*n*<=-<=1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once. You can output edges in any order. You can output the ends of each edge in any order. If there are several solutions, print any of them. Demo Input: ['3 3\n1 2\n2 3\n3 1\n1 2 1 1\n', '7 8\n7 4\n1 3\n5 4\n5 7\n3 2\n2 4\n6 1\n1 2\n6 4 1 4\n'] Demo Output: ['Yes\n3 2\n1 3\n', 'Yes\n1 3\n5 7\n3 2\n7 4\n2 4\n6 1\n'] Note: none
1,001
Title: Frog Fights Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ostap Bender recently visited frog farm and was inspired to create his own frog game. Number of frogs are places on a cyclic gameboard, divided into *m* cells. Cells are numbered from 1 to *m*, but the board is cyclic, so cell number 1 goes right after the cell number *m* in the direction of movement. *i*-th frog during its turn can jump for *a**i* cells. Frogs move in turns, game starts with a move by frog 1. On its turn *i*-th frog moves *a**i* cells forward, knocking out all the frogs on its way. If there is a frog in the last cell of the path of the *i*-th frog, that frog is also knocked out. After this the value *a**i* is decreased by the number of frogs that were knocked out during this turn. If *a**i* is zero or goes negative, then *i*-th frog doesn't make moves anymore. After frog number 1 finishes its turn, frog number 2 starts to move, then frog number 3 and so on. After the frog number *n* makes its move, frog 1 starts to move again, then frog 2 and so on this process goes forever. If some frog was already knocked out from the board, we consider that it skips all its moves. Help Ostap to identify, what frogs will stay on the board at the end of a game? Input Specification: First line of the input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=100000,<=1<=≤<=*m*<=≤<=109,<=*n*<=≤<=*m*) — number of frogs and gameboard size, respectively. Following *n* lines contains frogs descriptions — two integers *p**i* and *a**i* (1<=≤<=*p**i*,<=*a**i*<=≤<=*m*) — the number of cell occupied by *i*-th frog initially and initial jump length. All *p**i* are guaranteed to be distinct. Output Specification: In the first line output number of frogs on the final gameboard. In the second line output their numbers in any order. Demo Input: ['3 5\n2 1\n5 3\n4 3\n', '5 6\n1 2\n3 4\n2 5\n5 1\n6 1\n'] Demo Output: ['1\n3 ', '2\n1 4 '] Note: In the first sample first frog jumps 1 cell and finishes in cell number 3. Second frog jumps for 3 cells and finishes on cell number 3, knocking out frog number 1. Current jump length for frog number 2 is now 2. Third frog jumps to cell 2, then second frog jumps to cell 5. Third frog in turn finishes in cell 5 and removes frog 2 from the gameboard. Now, it's the only remaining frog in the game. In the second sample first frog jumps 2 cells and knocks out frogs in cells 2 and 3. Its value *a*<sub class="lower-index">*i*</sub> is now 0. Then fourth frog jumps and knocks out fifth frog and its *a*<sub class="lower-index">*i*</sub> is now 0 too. These two frogs will remains on the gameboard forever.
1,002
Title: Interactive Bulls and Cows (Hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: The only difference from the previous problem is the constraint on the number of requests. In this problem your program should guess the answer doing at most 7 requests. This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java — call System.out.flush(), and in Pascal — flush(output). Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind. On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed. Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers — the number of "bulls" and the number of "cows". A try can contain equal digits. More formally, let's the secret string is *s* and the second player are trying to guess it with a string *x*. The number of "bulls" is a number of such positions *i* (1<=≤<=*i*<=≤<=4) where *s*[*i*]<==<=*x*[*i*]. The number of "cows" is a number of such digits *c* that *s* contains *c* in the position *i* (i.e. *s*[*i*]<==<=*c*), *x* contains *c*, but *x*[*i*]<=≠<=*c*. For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow. In this problem you are to guess the string *s* that the system has chosen. You only know that the chosen string consists of 4 distinct digits. You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons — the program either guessed the number *x* or made an invalid action (for example, printed letters instead of digits). Your program is allowed to do at most 7 queries. You can hack solutions of other participants providing a 4-digit string containing distinct digits — the secret string. Input Specification: To read answers to the queries, the program must use the standard input. The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string *s* and the string *x**i* printed by your program. If the system response equals "4 0", then your solution should terminate. The testing system will let your program read the *i*-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value *x**i* in a single line and executes operation flush. Output Specification: The program must use the standard output to print queries. Your program must output requests — 4-digit strings *x*1,<=*x*2,<=..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input. Your program is allowed to do at most 7 queries. Demo Input: ['0 1\n2 0\n1 1\n0 4\n2 1\n4 0\n'] Demo Output: ['8000\n0179\n3159\n3210\n0112\n0123'] Note: The secret string *s* in the example is "0123".
1,003
Title: Video Cards Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated. There are *n* video cards in the shop, the power of the *i*-th video card is equal to integer value *a**i*. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced. Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power. Input Specification: The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the number of video cards in the shop. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=200<=000) — powers of video cards. Output Specification: The only line of the output should contain one integer value — the maximum possible total power of video cards working together. Demo Input: ['4\n3 2 15 9\n', '4\n8 2 2 7\n'] Demo Output: ['27\n', '18\n'] Note: In the first sample, it would be optimal to buy video cards with powers 3, 15 and 9. The video card with power 3 should be chosen as the leading one and all other video cards will be compatible with it. Thus, the total power would be 3 + 15 + 9 = 27. If he buys all the video cards and pick the one with the power 2 as the leading, the powers of all other video cards should be reduced by 1, thus the total power would be 2 + 2 + 14 + 8 = 26, that is less than 27. Please note, that it's not allowed to reduce the power of the leading video card, i.e. one can't get the total power 3 + 1 + 15 + 9 = 28. In the second sample, the optimal answer is to buy all video cards and pick the one with the power 2 as the leading. The video card with the power 7 needs it power to be reduced down to 6. The total power would be 8 + 2 + 2 + 6 = 18.
1,004
Title: Trial for Chief Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Having unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen. As soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divided by horizontal and vertical stripes into identical squares (the slab consisted of *N* lines and *M* columns) and painted every square black or white. Then every pretender was given a slab of the same size but painted entirely white. Within a day a pretender could paint any side-linked set of the squares of the slab some color. The set is called linked if for any two squares belonging to the set there is a path belonging the set on which any two neighboring squares share a side. The aim of each pretender is to paint his slab in the exactly the same way as the chief’s slab is painted. The one who paints a slab like that first becomes the new chief. Scientists found the slab painted by the ancient Berland tribe chief. Help them to determine the minimal amount of days needed to find a new chief if he had to paint his slab in the given way. Input Specification: The first line contains two integers *N* and *M* (1<=≤<=*N*,<=*M*<=≤<=50) — the number of lines and columns on the slab. The next *N* lines contain *M* symbols each — the final coloration of the slab. *W* stands for the square that should be painted white and *B* — for the square that should be painted black. Output Specification: In the single line output the minimal number of repaintings of side-linked areas needed to get the required coloration of the slab. Demo Input: ['3 3\nWBW\nBWB\nWBW\n', '2 3\nBBB\nBWB\n'] Demo Output: ['2\n', '1\n'] Note: none
1,005
Title: Exams Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasiliy has an exam period which will continue for *n* days. He has to pass exams on *m* subjects. Subjects are numbered from 1 to *m*. About every day we know exam for which one of *m* subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number *a**i* — the number of days he should prepare to pass the exam number *i*. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during *a**i* days for the exam number *i*. He can mix the order of preparation for exams in any way. Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105) — the number of days in the exam period and the number of subjects. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (0<=≤<=*d**i*<=≤<=*m*), where *d**i* is the number of subject, the exam of which can be passed on the day number *i*. If *d**i* equals 0, it is not allowed to pass any exams on the day number *i*. The third line contains *m* positive integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=105), where *a**i* is the number of days that are needed to prepare before passing the exam on the subject *i*. Output Specification: Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1. Demo Input: ['7 2\n0 1 0 2 1 0 2\n2 1\n', '10 3\n0 0 1 2 3 0 2 0 1 2\n1 1 4\n', '5 1\n1 1 1 1 1\n5\n'] Demo Output: ['5\n', '9\n', '-1\n'] Note: In the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day. In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day. In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it.
1,006
Title: Ant Man Time Limit: None seconds Memory Limit: None megabytes Problem Description: Scott Lang is at war with Darren Cross. There are *n* chairs in a hall where they are, numbered with 1,<=2,<=...,<=*n* from left to right. The *i*-th chair is located at coordinate *x**i*. Scott is on chair number *s* and Cross is on chair number *e*. Scott can jump to all other chairs (not only neighboring chairs). He wants to start at his position (chair number *s*), visit each chair exactly once and end up on chair number *e* with Cross. As we all know, Scott can shrink or grow big (grow big only to his normal size), so at any moment of time he can be either small or large (normal). The thing is, he can only shrink or grow big while being on a chair (not in the air while jumping to another chair). Jumping takes time, but shrinking and growing big takes no time. Jumping from chair number *i* to chair number *j* takes |*x**i*<=-<=*x**j*| seconds. Also, jumping off a chair and landing on a chair takes extra amount of time. If Scott wants to jump to a chair on his left, he can only be small, and if he wants to jump to a chair on his right he should be large. Jumping off the *i*-th chair takes: - *c**i* extra seconds if he's small. - *d**i* extra seconds otherwise (he's large). Also, landing on *i*-th chair takes: - *b**i* extra seconds if he's small. - *a**i* extra seconds otherwise (he's large). In simpler words, jumping from *i*-th chair to *j*-th chair takes exactly: - |*x**i*<=-<=*x**j*|<=+<=*c**i*<=+<=*b**j* seconds if *j*<=&lt;<=*i*. - |*x**i*<=-<=*x**j*|<=+<=*d**i*<=+<=*a**j* seconds otherwise (*j*<=&gt;<=*i*). Given values of *x*, *a*, *b*, *c*, *d* find the minimum time Scott can get to Cross, assuming he wants to visit each chair exactly once. Input Specification: The first line of the input contains three integers *n*,<=*s* and *e* (2<=≤<=*n*<=≤<=5000,<=1<=≤<=*s*,<=*e*<=≤<=*n*,<=*s*<=≠<=*e*) — the total number of chairs, starting and ending positions of Scott. The second line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n* (1<=≤<=*x*1<=&lt;<=*x*2<=&lt;<=...<=&lt;<=*x**n*<=≤<=109). The third line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a*1,<=*a*2,<=...,<=*a**n*<=≤<=109). The fourth line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b*1,<=*b*2,<=...,<=*b**n*<=≤<=109). The fifth line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c*1,<=*c*2,<=...,<=*c**n*<=≤<=109). The sixth line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≤<=*d*1,<=*d*2,<=...,<=*d**n*<=≤<=109). Output Specification: Print the minimum amount of time Scott needs to get to the Cross while visiting each chair exactly once. Demo Input: ['7 4 3\n8 11 12 16 17 18 20\n17 16 20 2 20 5 13\n17 8 8 16 12 15 13\n12 4 16 4 15 7 6\n8 14 2 11 17 12 8\n'] Demo Output: ['139\n'] Note: In the sample testcase, an optimal solution would be <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5bbd3e094ffa5a72e263dfaec7aeaff795bc22a3.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Spent time would be 17 + 24 + 23 + 20 + 33 + 22 = 139.
1,007
Title: Bets Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor. To begin with friends learned the rules: in the race there are *n* sections of equal length and *m* participants. The participants numbered from 1 to *m*. About each participant the following is known: - *l**i* — the number of the starting section, - *r**i* — the number of the finishing section (*l**i*<=≤<=*r**i*),- *t**i* — the time a biathlete needs to complete an section of the path,- *c**i* — the profit in roubles. If the *i*-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The *i*-th biathlete passes the sections from *l**i* to *r**i* inclusive. The competitor runs the whole way in (*r**i*<=-<=*l**i*<=+<=1)·*t**i* time units. It takes him exactly *t**i* time units to pass each section. In case of the athlete's victory on *k* sections the man who has betted on him receives *k*·*c**i* roubles. In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed. We should also add that Nikita can bet on each section and on any contestant running in this section. Help the friends find the maximum possible profit. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100). Then follow *m* lines, each containing 4 integers *l**i*, *r**i*, *t**i*, *c**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*, 1<=≤<=*t**i*,<=*c**i*<=≤<=1000). Output Specification: Print a single integer, the maximal profit in roubles that the friends can get. In each of *n* sections it is not allowed to place bets on more than one sportsman. Demo Input: ['4 4\n1 4 20 5\n1 3 21 10\n3 3 4 30\n3 4 4 20\n', '8 4\n1 5 24 10\n2 4 6 15\n4 6 30 50\n6 7 4 20\n'] Demo Output: ['60', '105'] Note: In the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles. In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles.
1,008
Title: Water Taps Time Limit: None seconds Memory Limit: None megabytes Problem Description: Consider a system of *n* water taps all pouring water into the same container. The *i*-th water tap can be set to deliver any amount of water from 0 to *a**i* ml per second (this amount may be a real number). The water delivered by *i*-th tap has temperature *t**i*. If for every you set *i*-th tap to deliver exactly *x**i* ml of water per second, then the resulting temperature of water will be (if , then to avoid division by zero we state that the resulting water temperature is 0). You have to set all the water taps in such a way that the resulting temperature is exactly *T*. What is the maximum amount of water you may get per second if its temperature has to be *T*? Input Specification: The first line contains two integers *n* and *T* (1<=≤<=*n*<=≤<=200000, 1<=≤<=*T*<=≤<=106) — the number of water taps and the desired temperature of water, respectively. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) where *a**i* is the maximum amount of water *i*-th tap can deliver per second. The third line contains *n* integers *t*1, *t*2, ..., *t**n* (1<=≤<=*t**i*<=≤<=106) — the temperature of water each tap delivers. Output Specification: Print the maximum possible amount of water with temperature exactly *T* you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0). Your answer is considered correct if its absolute or relative error doesn't exceed 10<=-<=6. Demo Input: ['2 100\n3 10\n50 150\n', '3 9\n5 5 30\n6 6 10\n', '2 12\n1 3\n10 15\n'] Demo Output: ['6.000000000000000\n', '40.000000000000000\n', '1.666666666666667\n'] Note: none
1,009
Title: Polyline Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of. Input Specification: Each of the three lines of the input contains two integers. The *i*-th line contains integers *x**i* and *y**i* (<=-<=109<=≤<=*x**i*,<=*y**i*<=≤<=109) — the coordinates of the *i*-th point. It is guaranteed that all points are distinct. Output Specification: Print a single number — the minimum possible number of segments of the polyline. Demo Input: ['1 -1\n1 1\n1 2\n', '-1 -1\n-1 3\n4 3\n', '1 1\n2 3\n3 2\n'] Demo Output: ['1\n', '2\n', '3\n'] Note: The variant of the polyline in the first sample: <img class="tex-graphics" src="https://espresso.codeforces.com/b41b4dad8437bd7a69f6ab01eaedf010b82ba7b8.png" style="max-width: 100.0%;max-height: 100.0%;"/> The variant of the polyline in the second sample: <img class="tex-graphics" src="https://espresso.codeforces.com/7410d2247b3381e5b27422609f90ff027e071812.png" style="max-width: 100.0%;max-height: 100.0%;"/> The variant of the polyline in the third sample: <img class="tex-graphics" src="https://espresso.codeforces.com/3a5018422eb982f0a2a9bd7f1fd7ab23777a0813.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,010
Title: Restore Cube Time Limit: None seconds Memory Limit: None megabytes Problem Description: Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers inside a single line (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations. When Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly. Input Specification: Each of the eight lines contains three space-separated integers — the numbers written on the piece of paper after Nick's mischief. All numbers do not exceed 106 in their absolute value. Output Specification: If there is a way to restore the cube, then print in the first line "YES". In each of the next eight lines print three integers — the restored coordinates of the points. The numbers in the *i*-th output line must be a permutation of the numbers in *i*-th input line. The numbers should represent the vertices of a cube with non-zero length of a side. If there are multiple possible ways, print any of them. If there is no valid way, print "NO" (without the quotes) in the first line. Do not print anything else. Demo Input: ['0 0 0\n0 0 1\n0 0 1\n0 0 1\n0 1 1\n0 1 1\n0 1 1\n1 1 1\n', '0 0 0\n0 0 0\n0 0 0\n0 0 0\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n'] Demo Output: ['YES\n0 0 0\n0 0 1\n0 1 0\n1 0 0\n0 1 1\n1 0 1\n1 1 0\n1 1 1\n', 'NO\n'] Note: none
1,011
Title: Mashmokh's Designed Problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: After a lot of trying, Mashmokh designed a problem and it's your job to solve it. You have a tree *T* with *n* vertices. Each vertex has a unique index from 1 to *n*. The root of *T* has index 1. For each vertex of this tree *v*, you are given a list of its children in a specific order. You must perform three types of query on this tree: 1. find distance (the number of edges in the shortest path) between *u* and *v*; 1. given *v* and *h*, disconnect *v* from its father and connect it to its *h*-th ancestor; more formally, let's denote the path from *v* to the root by *x*1,<=*x*2,<=...,<=*x**l* (*h*<=&lt;<=*l*), so that *x*1<==<=*v* and *x**l* is root; disconnect *v* from its father (*x*2) and connect it to *x**h*<=+<=1; vertex *v* must be added to the end of the child-list of vertex *x**h*<=+<=1; 1. in the vertex sequence produced by calling function dfs(root) find the latest vertex that has distance *k* from the root. The pseudo-code of function dfs(v): Input Specification: The first line of input contains two space-separated integers *n*,<=*m* (2<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=105), the number of vertices of *T* and number of queries to perform. The *i*-th of the following *n* lines contains an integer *l**i* (0<=≤<=*l**i*<=≤<=*n*), number of *i*-th vertex's children. Then *l**i* space-separated integers follow, the *j*-th of them is the index of *j*-th child of *i*-th vertex. Note that the order of these vertices is important. Each of the following *m* lines has one of the following format: "1 *v* *u*", "2 *v* *h*", or "3 *k*". The first number in the line is the type of query to perform according to the problem statement. The next numbers are description of the query. It's guaranteed that all the queries are correct. For example, in the second-type query *h* is at least 2 and at most distance of *v* from root. Also in the third-type query there is at least one vertex with distance *k* from the root at the time the query is given. Output Specification: For each query of the first or third type output one line containing the result of the query. Demo Input: ['4 9\n1 2\n1 3\n1 4\n0\n1 1 4\n2 4 2\n1 3 4\n3 1\n3 2\n2 3 2\n1 1 2\n3 1\n3 2\n', '2 2\n1 2\n0\n1 2 1\n3 1\n'] Demo Output: ['3\n2\n2\n4\n1\n3\n4\n', '1\n2\n'] Note: none
1,012
Title: none 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. Petya has a number consisting of *n* digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it *d*. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation *k* times: find the minimum *x* (1<=≤<=*x*<=&lt;<=*n*) such that *d**x*<==<=4 and *d**x*<=+<=1<==<=7, if *x* is odd, then to assign *d**x*<==<=*d**x*<=+<=1<==<=4, otherwise to assign *d**x*<==<=*d**x*<=+<=1<==<=7. Note that if no *x* was found, then the operation counts as completed and the array doesn't change at all. You are given the initial number as an array of digits and the number *k*. Help Petya find the result of completing *k* operations. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*k*<=≤<=109) — the number of digits in the number and the number of completed operations. The second line contains *n* digits without spaces representing the array of digits *d*, starting with *d*1. It is guaranteed that the first digit of the number does not equal zero. Output Specification: In the single line print the result without spaces — the number after the *k* operations are fulfilled. Demo Input: ['7 4\n4727447\n', '4 2\n4478\n'] Demo Output: ['4427477\n', '4478\n'] Note: In the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477. In the second sample: 4478 → 4778 → 4478.
1,013
Title: A Simple Task Time Limit: None seconds Memory Limit: None megabytes Problem Description: This task is very simple. Given a string *S* of length *n* and *q* queries each query is on the format *i* *j* *k* which means sort the substring consisting of the characters from *i* to *j* in non-decreasing order if *k*<==<=1 or in non-increasing order if *k*<==<=0. Output the final string after applying the queries. Input Specification: The first line will contain two integers *n*,<=*q* (1<=≤<=*n*<=≤<=105, 0<=≤<=*q*<=≤<=50<=000), the length of the string and the number of queries respectively. Next line contains a string *S* itself. It contains only lowercase English letters. Next *q* lines will contain three integers each *i*,<=*j*,<=*k* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*, ). Output Specification: Output one line, the string *S* after applying the queries. Demo Input: ['10 5\nabacdabcda\n7 10 0\n5 8 1\n1 4 0\n3 6 0\n7 10 1\n', '10 1\nagjucbvdfk\n1 10 1\n'] Demo Output: ['cbcaaaabdd', 'abcdfgjkuv'] Note: First sample test explanation: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3ac4e8cc7e335675a4a2b7b4758bfb3865377cea.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a90b5b03cf59288d8861f0142ecbdf6b12f69e5c.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1f482a91a275b6bce07eaed85312eac0cfcc6ccf.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/33b1a4a924f4bd562551ba4e40309f180dbe22e0.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bddc77fd5b02858eb2ff29819cd16a93dbd241e6.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,014
Title: Tram Time Limit: None seconds Memory Limit: None megabytes Problem Description: The tram in Berland goes along a straight line from the point 0 to the point *s* and back, passing 1 meter per *t*1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points *x*<==<=0 and *x*<==<=*s*. Igor is at the point *x*1. He should reach the point *x*2. Igor passes 1 meter per *t*2 seconds. Your task is to determine the minimum time Igor needs to get from the point *x*1 to the point *x*2, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point *x*1. Igor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is not obligatory that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than 1 meter per *t*2 seconds). He can also stand at some point for some time. Input Specification: The first line contains three integers *s*, *x*1 and *x*2 (2<=≤<=*s*<=≤<=1000, 0<=≤<=*x*1,<=*x*2<=≤<=*s*, *x*1<=≠<=*x*2) — the maximum coordinate of the point to which the tram goes, the point Igor is at, and the point he should come to. The second line contains two integers *t*1 and *t*2 (1<=≤<=*t*1,<=*t*2<=≤<=1000) — the time in seconds in which the tram passes 1 meter and the time in seconds in which Igor passes 1 meter. The third line contains two integers *p* and *d* (1<=≤<=*p*<=≤<=*s*<=-<=1, *d* is either 1 or ) — the position of the tram in the moment Igor came to the point *x*1 and the direction of the tram at this moment. If , the tram goes in the direction from the point *s* to the point 0. If *d*<==<=1, the tram goes in the direction from the point 0 to the point *s*. Output Specification: Print the minimum time in seconds which Igor needs to get from the point *x*1 to the point *x*2. Demo Input: ['4 2 4\n3 4\n1 1\n', '5 4 0\n1 2\n3 1\n'] Demo Output: ['8\n', '7\n'] Note: In the first example it is profitable for Igor to go by foot and not to wait the tram. Thus, he has to pass 2 meters and it takes 8 seconds in total, because he passes 1 meter per 4 seconds. In the second example Igor can, for example, go towards the point *x*<sub class="lower-index">2</sub> and get to the point 1 in 6 seconds (because he has to pass 3 meters, but he passes 1 meters per 2 seconds). At that moment the tram will be at the point 1, so Igor can enter the tram and pass 1 meter in 1 second. Thus, Igor will reach the point *x*<sub class="lower-index">2</sub> in 7 seconds in total.
1,015
Title: Guard Duty (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Princess Heidi decided to give orders to all her *K* Rebel ship commanders in person. Unfortunately, she is currently travelling through hyperspace, and will leave it only at *N* specific moments *t*1,<=*t*2,<=...,<=*t**N*. The meetings with commanders must therefore start and stop at those times. Namely, each commander will board her ship at some time *t**i* and disembark at some later time *t**j*. Of course, Heidi needs to meet with all commanders, and no two meetings can be held during the same time. Two commanders cannot even meet at the beginnings/endings of the hyperspace jumps, because too many ships in one position could give out their coordinates to the enemy. Your task is to find minimum time that Princess Heidi has to spend on meetings, with her schedule satisfying the conditions above. Input Specification: The first line contains two integers *K*, *N* (2<=≤<=2*K*<=≤<=*N*<=≤<=500000, *K*<=≤<=5000). The second line contains *N* distinct integers *t*1,<=*t*2,<=...,<=*t**N* (1<=≤<=*t**i*<=≤<=109) representing the times when Heidi leaves hyperspace. Output Specification: Output only one integer: the minimum time spent on meetings. Demo Input: ['2 5\n1 4 6 7 12\n', '3 6\n6 3 4 2 5 1\n', '4 12\n15 7 4 19 3 30 14 1 5 23 17 25\n'] Demo Output: ['4\n', '3\n', '6\n'] Note: In the first example, there are five valid schedules: [1, 4], [6, 7] with total time 4, [1, 4], [6, 12] with total time 9, [1, 4], [7, 12] with total time 8, [1, 6], [7, 12] with total time 10, and [4, 6], [7, 12] with total time 7. So the answer is 4. In the second example, there is only 1 valid schedule: [1, 2], [3, 4], [5, 6]. For the third example, one possible schedule with total time 6 is: [1, 3], [4, 5], [14, 15], [23, 25].
1,016
Title: Olympiad Time Limit: None seconds Memory Limit: None megabytes Problem Description: A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least *x* points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances. Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad. Input Specification: The first line contains two space-separated integers *n*,<=*x* (1<=≤<=*n*<=≤<=105; 0<=≤<=*x*<=≤<=2·105) — the number of Olympiad participants and the minimum number of points Vasya earned. The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=105) — the participants' points in the first tour. The third line contains *n* space-separated integers: *b*1,<=*b*2,<=...,<=*b**n* (0<=≤<=*b**i*<=≤<=105) — the participants' points in the second tour. The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad — there are two integers *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) such, that *a**i*<=+<=*b**j*<=≥<=*x*. Output Specification: Print two space-separated integers — the best and the worst place Vasya could have got on the Olympiad. Demo Input: ['5 2\n1 1 1 1 1\n1 1 1 1 1\n', '6 7\n4 3 5 6 4 4\n8 6 0 4 3 4\n'] Demo Output: ['1 5\n', '1 5\n'] Note: In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place. In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that — {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}. In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour. In the worst case scenario Vasya can get the fifth place if the table looks like that — {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.
1,017
Title: The Wall (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC2 (Handbook of Crazy Constructions) and looks for the right chapter: How to build a wall: 1. Take a set of bricks. 1. Select one of the possible wall designs. Computing the number of possible designs is left as an exercise to the reader. 1. Place bricks on top of each other, according to the chosen design. This seems easy enough. But Heidi is a Coding Cow, not a Constructing Cow. Her mind keeps coming back to point 2b. Despite the imminent danger of a zombie onslaught, she wonders just how many possible walls she could build with up to *n* bricks. A wall is a set of wall segments as defined in the easy version. How many different walls can be constructed such that the wall consists of at least 1 and at most *n* bricks? Two walls are different if there exist a column *c* and a row *r* such that one wall has a brick in this spot, and the other does not. Along with *n*, you will be given *C*, the width of the wall (as defined in the easy version). Return the number of different walls modulo 106<=+<=3. Input Specification: The first line contains two space-separated integers *n* and *C*, 1<=≤<=*n*<=≤<=500000, 1<=≤<=*C*<=≤<=200000. Output Specification: Print the number of different walls that Heidi could build, modulo 106<=+<=3. Demo Input: ['5 1\n', '2 2\n', '3 2\n', '11 5\n', '37 63\n'] Demo Output: ['5\n', '5\n', '9\n', '4367\n', '230574\n'] Note: The number 10<sup class="upper-index">6</sup> + 3 is prime. In the second sample case, the five walls are: In the third sample case, the nine walls are the five as in the second sample case and in addition the following four:
1,018
Title: Three Sons Time Limit: None seconds Memory Limit: None megabytes Problem Description: Three sons inherited from their father a rectangular corn fiend divided into *n*<=×<=*m* squares. For each square we know how many tons of corn grows on it. The father, an old farmer did not love all three sons equally, which is why he bequeathed to divide his field into three parts containing *A*, *B* and *C* tons of corn. The field should be divided by two parallel lines. The lines should be parallel to one side of the field and to each other. The lines should go strictly between the squares of the field. Each resulting part of the field should consist of at least one square. Your task is to find the number of ways to divide the field as is described above, that is, to mark two lines, dividing the field in three parts so that on one of the resulting parts grew *A* tons of corn, *B* on another one and *C* on the remaining one. Input Specification: The first line contains space-separated integers *n* and *m* — the sizes of the original (1<=≤<=*n*,<=*m*<=≤<=50,<=*max*(*n*,<=*m*)<=≥<=3). Then the field's description follows: *n* lines, each containing *m* space-separated integers *c**ij*, (0<=≤<=*c**ij*<=≤<=100) — the number of tons of corn each square contains. The last line contains space-separated integers *A*,<=*B*,<=*C* (0<=≤<=*A*,<=*B*,<=*C*<=≤<=106). Output Specification: Print the answer to the problem: the number of ways to divide the father's field so that one of the resulting parts contained *A* tons of corn, another one contained *B* tons, and the remaining one contained *C* tons. If no such way exists, print 0. Demo Input: ['3 3\n1 1 1\n1 1 1\n1 1 1\n3 3 3\n', '2 5\n1 1 1 1 1\n2 2 2 2 2\n3 6 6\n', '3 3\n1 2 3\n3 1 2\n2 3 1\n5 6 7\n'] Demo Output: ['2\n', '3\n', '0\n'] Note: The lines dividing the field can be horizontal or vertical, but they should be parallel to each other.
1,019
Title: Buns Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Lavrenty, a baker, is going to make several buns with stuffings and sell them. Lavrenty has *n* grams of dough as well as *m* different stuffing types. The stuffing types are numerated from 1 to *m*. Lavrenty knows that he has *a**i* grams left of the *i*-th stuffing. It takes exactly *b**i* grams of stuffing *i* and *c**i* grams of dough to cook a bun with the *i*-th stuffing. Such bun can be sold for *d**i* tugriks. Also he can make buns without stuffings. Each of such buns requires *c*0 grams of dough and it can be sold for *d*0 tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking. Find the maximum number of tugriks Lavrenty can earn. Input Specification: The first line contains 4 integers *n*, *m*, *c*0 and *d*0 (1<=≤<=*n*<=≤<=1000, 1<=≤<=*m*<=≤<=10, 1<=≤<=*c*0,<=*d*0<=≤<=100). Each of the following *m* lines contains 4 integers. The *i*-th line contains numbers *a**i*, *b**i*, *c**i* and *d**i* (1<=≤<=*a**i*,<=*b**i*,<=*c**i*,<=*d**i*<=≤<=100). Output Specification: Print the only number — the maximum number of tugriks Lavrenty can earn. Demo Input: ['10 2 2 1\n7 3 2 100\n12 3 1 10\n', '100 1 25 50\n15 5 20 10\n'] Demo Output: ['241', '200'] Note: To get the maximum number of tugriks in the first sample, you need to cook 2 buns with stuffing 1, 4 buns with stuffing 2 and a bun without any stuffing. In the second sample Lavrenty should cook 4 buns without stuffings.
1,020
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Artem has an array of *n* positive integers. Artem decided to play with it. The game consists of *n* moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets *min*(*a*,<=*b*) points, where *a* and *b* are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=5·105) — the number of elements in the array. The next line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the values of the array elements. Output Specification: In a single line print a single integer — the maximum number of points Artem can get. Demo Input: ['5\n3 1 5 2 6\n', '5\n1 2 3 4 5\n', '5\n1 100 101 100 1\n'] Demo Output: ['11\n', '6\n', '102\n'] Note: none
1,021
Title: PolandBall and Gifts Time Limit: None seconds Memory Limit: None megabytes Problem Description: It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are *n* Balls overall. Each Ball has someone for whom he should bring a present according to some permutation *p*, *p**i*<=≠<=*i* for all *i*. Unfortunately, Balls are quite clumsy. We know earlier that exactly *k* of them will forget to bring their gift. A Ball number *i* will get his present if the following two constraints will hold: 1. Ball number *i* will bring the present he should give. 1. Ball *x* such that *p**x*<==<=*i* will bring his present. What is minimum and maximum possible number of kids who will not get their present if exactly *k* Balls will forget theirs? Input Specification: The first line of input contains two integers *n* and *k* (2<=≤<=*n*<=≤<=106, 0<=≤<=*k*<=≤<=*n*), representing the number of Balls and the number of Balls who will forget to bring their presents. The second line contains the permutation *p* of integers from 1 to *n*, where *p**i* is the index of Ball who should get a gift from the *i*-th Ball. For all *i*, *p**i*<=≠<=*i* holds. Output Specification: You should output two values — minimum and maximum possible number of Balls who will not get their presents, in that order. Demo Input: ['5 2\n3 4 1 5 2\n', '10 1\n2 3 4 5 6 7 8 9 10 1\n'] Demo Output: ['2 4', '2 2'] Note: In the first sample, if the third and the first balls will forget to bring their presents, they will be th only balls not getting a present. Thus the minimum answer is 2. However, if the first ans the second balls will forget to bring their presents, then only the fifth ball will get a present. So, the maximum answer is 4.
1,022
Title: Fancy Number Time Limit: None seconds Memory Limit: None megabytes Problem Description: A car number in Berland consists of exactly *n* digits. A number is called beautiful if it has at least *k* equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of *n* digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input Specification: The first line contains two space-separated integers *n* and *k* (2<=≤<=*n*<=≤<=104,<=2<=≤<=*k*<=≤<=*n*) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of *n* digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output Specification: On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Demo Input: ['6 5\n898196\n', '3 2\n533\n', '10 6\n0001112223\n'] Demo Output: ['4\n888188\n', '0\n533\n', '3\n0000002223\n'] Note: In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the &lt; operator in modern programming languages. The string *x* is lexicographically smaller than the string *y*, if there exists such *i* (1 ≤ *i* ≤ *n*), that *x*<sub class="lower-index">*i*</sub> &lt; *y*<sub class="lower-index">*i*</sub>, and for any *j* (1 ≤ *j* &lt; *i*) *x*<sub class="lower-index">*j*</sub> = *y*<sub class="lower-index">*j*</sub>. The strings compared in this problem will always have the length *n*.
1,023
Title: Playing Cubes Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya and Vasya decided to play a little. They found *n* red cubes and *m* blue cubes. The game goes like that: the players take turns to choose a cube of some color (red or blue) and put it in a line from left to right (overall the line will have *n*<=+<=*m* cubes). Petya moves first. Petya's task is to get as many pairs of neighbouring cubes of the same color as possible. Vasya's task is to get as many pairs of neighbouring cubes of different colors as possible. The number of Petya's points in the game is the number of pairs of neighboring cubes of the same color in the line, the number of Vasya's points in the game is the number of neighbouring cubes of the different color in the line. Your task is to calculate the score at the end of the game (Petya's and Vasya's points, correspondingly), if both boys are playing optimally well. To "play optimally well" first of all means to maximize the number of one's points, and second — to minimize the number of the opponent's points. Input Specification: The only line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105) — the number of red and blue cubes, correspondingly. Output Specification: On a single line print two space-separated integers — the number of Petya's and Vasya's points correspondingly provided that both players play optimally well. Demo Input: ['3 1\n', '2 4\n'] Demo Output: ['2 1\n', '3 2\n'] Note: In the first test sample the optimal strategy for Petya is to put the blue cube in the line. After that there will be only red cubes left, so by the end of the game the line of cubes from left to right will look as [blue, red, red, red]. So, Petya gets 2 points and Vasya gets 1 point. If Petya would choose the red cube during his first move, then, provided that both boys play optimally well, Petya would get 1 point and Vasya would get 2 points.
1,024
Title: Tree of Life (hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: To add insult to injury, the zombies have taken all but two drawings from Heidi! Please help her recover the Tree of Life from only these two drawings. Input Specification: The input format is the same as in the medium version, except that now the bound on *n* is 2<=≤<=*n*<=≤<=1000 and that *k*<==<=2. Output Specification: The same as in the medium version. Demo Input: ['1\n9 2\n6\n4 3\n5 4\n6 1\n8 6\n8 2\n7 1\n5\n8 6\n8 7\n8 1\n7 3\n5 1\n'] Demo Output: ['YES\n2 1\n3 1\n5 4\n6 5\n7 6\n8 5\n9 8\n1 4\n'] Note: none
1,025
Title: Inverse Function Time Limit: 5 seconds Memory Limit: 64 megabytes Problem Description: Petya wrote a programme on C++ that calculated a very interesting function *f*(*n*). Petya ran the program with a certain value of *n* and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had the result. However while Petya was drinking tea, a sly virus managed to destroy the input file so that Petya can't figure out for which value of *n* the program was run. Help Petya, carry out the inverse function! Mostly, the program consists of a function in C++ with the following simplified syntax: - *function* ::= int f(int n) {*operatorSequence*}- *operatorSequence* ::= *operator* | *operator* *operatorSequence*- *operator* ::= return *arithmExpr*; | if (*logicalExpr*) return *arithmExpr*;- *logicalExpr* ::= *arithmExpr*<=&gt;<=*arithmExpr* | *arithmExpr*<=&lt;<=*arithmExpr* | *arithmExpr* == *arithmExpr*- *arithmExpr* ::= *sum*- *sum* ::= *product* | *sum*<=+<=*product* | *sum*<=-<=*product*- *product* ::= *multiplier* | *product*<=*<=*multiplier* | *product*<=/<=*multiplier*- *multiplier* ::= n | *number* | f(*arithmExpr*)- *number* ::= 0|1|2|... |32767 The whitespaces in a *operatorSequence* are optional. Thus, we have a function, in which body there are two kinds of operators. There is the operator "return *arithmExpr*;" that returns the value of the expression as the value of the function, and there is the conditional operator "if (*logicalExpr*) return *arithmExpr*;" that returns the value of the arithmetical expression when and only when the logical expression is true. Guaranteed that no other constructions of C++ language — cycles, assignment operators, nested conditional operators etc, and other variables except the *n* parameter are used in the function. All the constants are integers in the interval [0..32767]. The operators are performed sequentially. After the function has returned a value other operators in the sequence are not performed. Arithmetical expressions are performed taking into consideration the standard priority of the operations. It means that first all the products that are part of the sum are calculated. During the calculation of the products the operations of multiplying and division are performed from the left to the right. Then the summands are summed, and the addition and the subtraction are also performed from the left to the right. Operations "&gt;" (more), "&lt;" (less) and "==" (equals) also have standard meanings. Now you've got to pay close attention! The program is compiled with the help of 15-bit Berland C++ compiler invented by a Berland company BerSoft, that's why arithmetical operations are performed in a non-standard way. Addition, subtraction and multiplication are performed modulo 32768 (if the result of subtraction is negative, then 32768 is added to it until the number belongs to the interval [0..32767]). Division "/" is a usual integer division where the remainder is omitted. Examples of arithmetical operations: Guaranteed that for all values of *n* from 0 to 32767 the given function is performed correctly. That means that: 1. Division by 0 never occures. 2. When performing a function for the value *n*<==<=*N* recursive calls of the function *f* may occur only for the parameter value of 0,<=1,<=...,<=*N*<=-<=1. Consequently, the program never has an infinite recursion. 3. As the result of the sequence of the operators, the function always returns a value. We have to mention that due to all the limitations the value returned by the function *f* is independent from either global variables or the order of performing the calculations of arithmetical expressions as part of the logical one, or from anything else except the value of *n* parameter. That's why the *f* function can be regarded as a function in its mathematical sense, i.e. as a unique correspondence between any value of *n* from the interval [0..32767] and a value of *f*(*n*) from the same interval. Given the value of *f*(*n*), and you should find *n*. If the suitable *n* value is not unique, you should find the maximal one (from the interval [0..32767]). Input Specification: The first line has an integer *f*(*n*) from the interval [0..32767]. The next lines have the description of the function *f*. In the description can be found extra spaces and line breaks (see the examples) which, of course, can’t break key words int, if, return and numbers. The size of input data can’t exceed 100 bytes. Output Specification: Output a single number — the answer to the problem. If there’s no answer, output "-1" (without quotes). Demo Input: ['17\nint f(int n)\n{\nif (n &lt; 100) return 17;\nif (n &gt; 99) return 27;\n}\n', '13\nint f(int n)\n{\nif (n == 0) return 0;\nreturn f(n - 1) + 1;\n}\n', '144\nint f(int n)\n{\nif (n == 0) return 0;\nif (n == 1) return n;\nreturn f(n - 1) + f(n - 2);\n}'] Demo Output: ['99\n', '13', '24588\n'] Note: none
1,026
Title: Sereja and Table Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sereja has an *n*<=×<=*m* rectangular table *a*, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size *h*<=×<=*w*, then the component must contain exactly *hw* cells. A connected component of the same values is a set of cells of the table that meet the following conditions: - every two cells of the set have the same value; - the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table); - it is impossible to add any cell to the set unless we violate the two previous conditions. Can Sereja change the values of at most *k* cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case? Input Specification: The first line contains integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=100; 1<=≤<=*k*<=≤<=10). Next *n* lines describe the table *a*: the *i*-th of them contains *m* integers *a**i*1,<=*a**i*2,<=...,<=*a**im* (0<=≤<=*a**i*,<=*j*<=≤<=1) — the values in the cells of the *i*-th row. Output Specification: Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed. Demo Input: ['5 5 2\n1 1 1 1 1\n1 1 1 1 1\n1 1 0 1 1\n1 1 1 1 1\n1 1 1 1 1\n', '3 4 1\n1 0 0 0\n0 1 1 1\n1 1 1 0\n', '3 4 1\n1 0 0 1\n0 1 1 0\n1 0 0 1\n'] Demo Output: ['1\n', '-1\n', '0\n'] Note: none
1,027
Title: Tree and Table Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Petya likes trees a lot. Recently his mother has presented him a tree with 2*n* nodes. Petya immediately decided to place this tree on a rectangular table consisting of 2 rows and *n* columns so as to fulfill the following conditions: 1. Each cell of the table corresponds to exactly one tree node and vice versa, each tree node corresponds to exactly one table cell. 1. If two tree nodes are connected by an edge, then the corresponding cells have a common side. Now Petya wonders how many ways are there to place his tree on the table. He calls two placements distinct if there is a tree node which corresponds to distinct table cells in these two placements. Since large numbers can scare Petya, print the answer modulo 1000000007 (109<=+<=7). Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105). Next (2*n*<=-<=1) lines contain two integers each *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=2*n*; *a**i*<=≠<=*b**i*) that determine the numbers of the vertices connected by the corresponding edge. Consider the tree vertexes numbered by integers from 1 to 2*n*. It is guaranteed that the graph given in the input is a tree, that is, a connected acyclic undirected graph. Output Specification: Print a single integer — the required number of ways to place the tree on the table modulo 1000000007 (109<=+<=7). Demo Input: ['3\n1 3\n2 3\n4 3\n5 1\n6 2\n', '4\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n', '2\n1 2\n3 2\n4 2\n'] Demo Output: ['12\n', '28\n', '0\n'] Note: Note to the first sample (all 12 variants to place the tree on the table are given below):
1,028
Title: Sereja and Prefixes Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in *m* stages. Each time he either adds a new number to the end of the sequence or takes *l* first elements of the current sequence and adds them *c* times to the end. More formally, if we represent the current sequence as *a*1,<=*a*2,<=...,<=*a**n*, then after we apply the described operation, the sequence transforms into *a*1,<=*a*2,<=...,<=*a**n*[,<=*a*1,<=*a*2,<=...,<=*a**l*] (the block in the square brackets must be repeated *c* times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja. Input Specification: The first line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of stages to build a sequence. Next *m* lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer *x**i* (1<=≤<=*x**i*<=≤<=105) — the number to add. Type 2 means copying a prefix of length *l**i* to the end *c**i* times, in this case the line further contains two integers *l**i*,<=*c**i* (1<=≤<=*l**i*<=≤<=105,<=1<=≤<=*c**i*<=≤<=104), *l**i* is the length of the prefix, *c**i* is the number of copyings. It is guaranteed that the length of prefix *l**i* is never larger than the current length of the sequence. The next line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Specification: Print the elements that Sereja is interested in, in the order in which their numbers occur in the input. Demo Input: ['6\n1 1\n1 2\n2 2 1\n1 3\n2 5 2\n1 4\n16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n'] Demo Output: ['1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4\n'] Note: none
1,029
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vova has recently learned what a circulaton in a graph is. Recall the definition: let $G = (V, E)$ be a directed graph. A circulation $f$ is such a collection of non-negative real numbers $f_e$ ($e \in E$), that for each vertex $v \in V$ the following conservation condition holds: $$\sum\limits_{e \in \delta^{-}(v)} f_e = \sum\limits_{e \in \delta^{+}(v)} f_e$$ where $\delta^{+}(v)$ is the set of edges that end in the vertex $v$, and $\delta^{-}(v)$ is the set of edges that start in the vertex $v$. In other words, for each vertex the total incoming flow should be equal to the total outcoming flow. Let a $lr$-circulation be such a circulation $f$ that for each edge the condition $l_e \leq f_e \leq r_e$ holds, where $l_e$ and $r_e$ for each edge $e \in E$ are two non-negative real numbers denoting the lower and upper bounds on the value of the circulation on this edge $e$. Vova can't stop thinking about applications of a new topic. Right now he thinks about the following natural question: let the graph be fixed, and each value $l_e$ and $r_e$ be a linear function of a real variable $t$: $$l_e(t) = a_e t + b_e$$ $$r_e(t) = c_e t + d_e$$ Note that $t$ is the same for all edges. Let $t$ be chosen at random from uniform distribution on a segment $[0, 1]$. What is the probability of existence of $lr$-circulation in the graph? Input Specification: The first line contains two integers $n$, $m$ ($1 \leq n \leq 1000$, $1 \leq m \leq 2000$). Each of the next $m$ lines describes edges of the graph in the format $u_e$, $v_e$, $a_e$, $b_e$, $c_e$, $d_e$ ($1 \leq u_e, v_e \leq n$, $-10^4 \leq a_e, c_e \leq 10^4$, $0 \leq b_e, d_e \leq 10^4$), where $u_e$ and $v_e$ are the startpoint and the endpoint of the edge $e$, and the remaining 4 integers describe the linear functions for the upper and lower bound of circulation. It is guaranteed that for any $t \in [0, 1]$ and for any edge $e \in E$ the following condition holds $0 \leq l_e(t) \leq r_e(t) \leq 10^4$. Output Specification: Print a single real integer — the probability of existence of $lr$-circulation in the graph, given that $t$ is chosen uniformly at random from the segment $[0, 1]$. Your answer is considered correct if its absolute difference from jury's answer is not greater than $10^{-6}$. Demo Input: ['3 3\n1 2 0 3 -4 7\n2 3 -2 5 1 6\n3 1 0 4 0 4\n'] Demo Output: ['0.25'] Note: In the first example the conservation condition allows only circulations with equal values $f_e$ for all three edges. The value of circulation on the last edge should be $4$ whatever $t$ is chosen, so the probability is $$P(4 \in [3, -4t + 7]~~\&amp;~~4 \in [-2t + 5, t + 6]) = 0.25$$
1,030
Title: One-dimensional Japanese Crossword Time Limit: None seconds Memory Limit: None megabytes Problem Description: Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia [https://en.wikipedia.org/wiki/Japanese_crossword](https://en.wikipedia.org/wiki/Japanese_crossword)). Adaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of *n* squares (e.g. japanese crossword sized 1<=×<=*n*), which he wants to encrypt in the same way as in japanese crossword. Help Adaltik find the numbers encrypting the row he drew. Input Specification: The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the length of the row. The second line of the input contains a single string consisting of *n* characters 'B' or 'W', ('B' corresponds to black square, 'W' — to white square in the row that Adaltik drew). Output Specification: The first line should contain a single integer *k* — the number of integers encrypting the row, e.g. the number of groups of black squares in the row. The second line should contain *k* integers, encrypting the row, e.g. corresponding to sizes of groups of consecutive black squares in the order from left to right. Demo Input: ['3\nBBW\n', '5\nBWBWB\n', '4\nWWWW\n', '4\nBBBB\n', '13\nWBBBBWWBWBBBW\n'] Demo Output: ['1\n2 ', '3\n1 1 1 ', '0\n', '1\n4 ', '3\n4 1 3 '] Note: The last sample case correspond to the picture in the statement.
1,031
Title: Fibonotci Time Limit: None seconds Memory Limit: None megabytes Problem Description: Fibonotci sequence is an integer recursive sequence defined by the recurrence relation Sequence *s* is an infinite and almost cyclic sequence with a cycle of length *N*. A sequence *s* is called almost cyclic with a cycle of length *N* if , for *i*<=≥<=*N*, except for a finite number of values *s**i*, for which (*i*<=≥<=*N*). Following is an example of an almost cyclic sequence with a cycle of length 4: Notice that the only value of *s* for which the equality does not hold is *s*6 (*s*6<==<=7 and *s*2<==<=8). You are given *s*0,<=*s*1,<=...*s**N*<=-<=1 and all the values of sequence *s* for which (*i*<=≥<=*N*). Find . Input Specification: The first line contains two numbers *K* and *P*. The second line contains a single number *N*. The third line contains *N* numbers separated by spaces, that represent the first *N* numbers of the sequence *s*. The fourth line contains a single number *M*, the number of values of sequence *s* for which . Each of the following *M* lines contains two numbers *j* and *v*, indicating that and *s**j*<==<=*v*. All j-s are distinct. - 1<=≤<=*N*,<=*M*<=≤<=50000 - 0<=≤<=*K*<=≤<=1018 - 1<=≤<=*P*<=≤<=109 - 1<=≤<=*s**i*<=≤<=109, for all *i*<==<=0,<=1,<=...*N*<=-<=1 - *N*<=≤<=*j*<=≤<=1018 - 1<=≤<=*v*<=≤<=109 - All values are integers Output Specification: Output should contain a single integer equal to . Demo Input: ['10 8\n3\n1 2 1\n2\n7 3\n5 4\n'] Demo Output: ['4\n'] Note: none
1,032
Title: Two Problems Time Limit: None seconds Memory Limit: None megabytes Problem Description: A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as *x* points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result. He knows that the contest number 300 was unusual because there were only two problems. The contest lasted for *t* minutes, the minutes are numbered starting from zero. The first problem had the initial cost of *a* points, and every minute its cost reduced by *d**a* points. The second problem had the initial cost of *b* points, and every minute this cost reduced by *d**b* points. Thus, as soon as the zero minute of the contest is over, the first problem will cost *a*<=-<=*d**a* points, and the second problem will cost *b*<=-<=*d**b* points. It is guaranteed that at any moment of the contest each problem has a non-negative cost. Arkady asks you to find out whether Valera could have got exactly *x* points for this contest. You should assume that Valera could have solved any number of the offered problems. You should also assume that for each problem Valera made no more than one attempt, besides, he could have submitted both problems at the same minute of the contest, starting with minute 0 and ending with minute number *t*<=-<=1. Please note that Valera can't submit a solution exactly *t* minutes after the start of the contest or later. Input Specification: The single line of the input contains six integers *x*,<=*t*,<=*a*,<=*b*,<=*d**a*,<=*d**b* (0<=≤<=*x*<=≤<=600; 1<=≤<=*t*,<=*a*,<=*b*,<=*d**a*,<=*d**b*<=≤<=300) — Valera's result, the contest's duration, the initial cost of the first problem, the initial cost of the second problem, the number of points that the first and the second problem lose per minute, correspondingly. It is guaranteed that at each minute of the contest each problem has a non-negative cost, that is, *a*<=-<=*i*·*d**a*<=≥<=0 and *b*<=-<=*i*·*d**b*<=≥<=0 for all 0<=≤<=*i*<=≤<=*t*<=-<=1. Output Specification: If Valera could have earned exactly *x* points at a contest, print "YES", otherwise print "NO" (without the quotes). Demo Input: ['30 5 20 20 3 5\n', '10 4 100 5 5 1\n'] Demo Output: ['YES\n', 'NO\n'] Note: In the first sample Valera could have acted like this: he could have submitted the first problem at minute 0 and the second problem — at minute 2. Then the first problem brings him 20 points and the second problem brings him 10 points, that in total gives the required 30 points.
1,033
Title: How many trees? Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game... For sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this. However, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus — Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User. This time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with *n* nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from 1 to *n*. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf). In Hexadecimal's game all the trees are different, but the height of each is not lower than *h*. In this problem «height» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you? Input Specification: The input data contains two space-separated positive integer numbers *n* and *h* (*n*<=≤<=35, *h*<=≤<=*n*). Output Specification: Output one number — the answer to the problem. It is guaranteed that it does not exceed 9·1018. Demo Input: ['3 2\n', '3 3\n'] Demo Output: ['5', '4'] Note: none
1,034
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are *n* bottles on the ground, the *i*-th bottle is located at position (*x**i*,<=*y**i*). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 1. If the choice was to continue then choose some bottle and walk towards it. 1. Pick this bottle and walk to the recycling bin. 1. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input Specification: First line of the input contains six integers *a**x*, *a**y*, *b**x*, *b**y*, *t**x* and *t**y* (0<=≤<=*a**x*,<=*a**y*,<=*b**x*,<=*b**y*,<=*t**x*,<=*t**y*<=≤<=109) — initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of bottles on the ground. Then follow *n* lines, each of them contains two integers *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=109) — position of the *i*-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Specification: Print one real number — the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. 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 1 2 0 0\n3\n1 1\n2 1\n2 3\n', '5 0 4 2 2 0\n5\n5 2\n3 0\n5 5\n3 5\n3 3\n'] Demo Output: ['11.084259940083\n', '33.121375178000\n'] Note: Consider the first sample. Adil will use the following path: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/37eea809c04afe04f2670475cc5b21df4a90afd1.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Bera will use the following path: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/08e917ff238fec015f897516a95529b6d9aed5c7.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Adil's path will be <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f58aa00f71a0b723b5de3c8e56ce41dc8afec7f8.png" style="max-width: 100.0%;max-height: 100.0%;"/> units long, while Bera's path will be <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3615db76a2cdd77d711b73d2894f03bdd52af736.png" style="max-width: 100.0%;max-height: 100.0%;"/> units long.
1,035
Title: April Fools' Problem (easy) Time Limit: None seconds Memory Limit: None megabytes Problem Description: The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers *n*, *k* and a sequence of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n*. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal. However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools! Input Specification: The first line of the input contains two space-separated integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=2200). The second line contains *n* space-separated integers *a*1,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=104). Output Specification: Output one number. Demo Input: ['8 5\n1 1 1 1 1 1 1 1\n', '10 3\n16 8 2 4 512 256 32 128 64 1\n', '5 1\n20 10 50 30 46\n', '6 6\n6 6 6 6 6 6\n', '1 1\n100\n'] Demo Output: ['5', '7', '10', '36', '100'] Note: none
1,036
Title: Devu and his Brother Time Limit: None seconds Memory Limit: None megabytes Problem Description: Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays *a* and *b* by their father. The array *a* is given to Devu and *b* to his brother. As Devu is really a naughty kid, he wants the minimum value of his array *a* should be at least as much as the maximum value of his brother's array *b*. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times. You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting. Input Specification: The first line contains two space-separated integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=105). The second line will contain *n* space-separated integers representing content of the array *a* (1<=≤<=*a**i*<=≤<=109). The third line will contain *m* space-separated integers representing content of the array *b* (1<=≤<=*b**i*<=≤<=109). Output Specification: You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition. Demo Input: ['2 2\n2 3\n3 5\n', '3 2\n1 2 3\n3 4\n', '3 2\n4 5 6\n1 2\n'] Demo Output: ['3\n', '4\n', '0\n'] Note: In example 1, you can increase *a*<sub class="lower-index">1</sub> by 1 and decrease *b*<sub class="lower-index">2</sub> by 1 and then again decrease *b*<sub class="lower-index">2</sub> by 1. Now array *a* will be [3; 3] and array *b* will also be [3; 3]. Here minimum element of *a* is at least as large as maximum element of *b*. So minimum number of operations needed to satisfy Devu's condition are 3. In example 3, you don't need to do any operation, Devu's condition is already satisfied.
1,037
Title: Help Greg the Dwarf 2 Time Limit: None seconds Memory Limit: None megabytes Problem Description: Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. That's why he wants to find the shortest route from the excavation point to his crypt. Greg has recollected how the Codeforces participants successfully solved the problem of transporting his coffin to a crypt. So, in some miraculous way Greg appeared in your bedroom and asks you to help him in a highly persuasive manner. As usual, you didn't feel like turning him down. After some thought, you formalized the task as follows: as the Neverland mountain has a regular shape and ends with a rather sharp peak, it can be represented as a cone whose base radius equals *r* and whose height equals *h*. The graveyard where Greg is busy excavating and his crypt can be represented by two points on the cone's surface. All you've got to do is find the distance between points on the cone's surface. The task is complicated by the fact that the mountain's base on the ground level and even everything below the mountain has been dug through by gnome (one may wonder whether they've been looking for the same stuff as Greg...). So, one can consider the shortest way to pass not only along the side surface, but also along the cone's base (and in a specific case both points can lie on the cone's base — see the first sample test) Greg will be satisfied with the problem solution represented as the length of the shortest path between two points — he can find his way pretty well on his own. He gave you two hours to solve the problem and the time is ticking! Input Specification: The first input line contains space-separated integers *r* and *h* (1<=≤<=*r*,<=*h*<=≤<=1000) — the base radius and the cone height correspondingly. The second and third lines contain coordinates of two points on the cone surface, groups of three space-separated real numbers. The coordinates of the points are given in the systems of coordinates where the origin of coordinates is located in the centre of the cone's base and its rotation axis matches the *OZ* axis. In this coordinate system the vertex of the cone is located at the point (0,<=0,<=*h*), the base of the cone is a circle whose center is at the point (0,<=0,<=0), lying on the *XOY* plane, and all points on the cone surface have a non-negative coordinate *z*. It is guaranteed that the distances from the points to the cone surface do not exceed 10<=-<=12. All real numbers in the input have no more than 16 digits after decimal point. Output Specification: Print the length of the shortest path between the points given in the input, with absolute or relative error not exceeding 10<=-<=6. Demo Input: ['2 2\n1.0 0.0 0.0\n-1.0 0.0 0.0\n', '2 2\n1.0 0.0 0.0\n1.0 0.0 1.0\n', '2 2\n1.0 0.0 1.0\n-1.0 0.0 1.0\n', '2 2\n1.0 0.0 0.0\n0.0 1.0 1.0\n'] Demo Output: ['2.000000000', '2.414213562', '2.534324263', '3.254470198'] Note: none
1,038
Title: Right Triangles Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: You are given a *n*<=×<=*m* field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). Input Specification: The first line contains two positive integer numbers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000). The following *n* lines consist of *m* characters each, describing the field. Only '.' and '*' are allowed. Output Specification: Output a single number — total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Demo Input: ['2 2\n**\n*.\n', '3 4\n*..*\n.**.\n*.**\n'] Demo Output: ['1\n', '9\n'] Note: none
1,039
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20&gt;10$, $40&gt;20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case. Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal. Input Specification: The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array. Output Specification: Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array. Demo Input: ['7\n10 1 1 1 5 5 3\n', '5\n1 1 1 1 1\n'] Demo Output: ['4\n', '0\n'] Note: In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4. In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
1,040
Title: One Bomb Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a description of a depot. It is a rectangular checkered field of *n*<=×<=*m* size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (*x*,<=*y*), then after triggering it will wipe out all walls in the row *x* and all walls in the column *y*. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input Specification: The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the number of rows and columns in the depot field. The next *n* lines contain *m* symbols "." and "*" each — the description of the field. *j*-th symbol in *i*-th of them stands for cell (*i*,<=*j*). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output Specification: If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line — the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Demo Input: ['3 4\n.*..\n....\n.*..\n', '3 3\n..*\n.*.\n*..\n', '6 5\n..*..\n..*..\n*****\n..*..\n..*..\n..*..\n'] Demo Output: ['YES\n1 2\n', 'NO\n', 'YES\n3 3\n'] Note: none
1,041
Title: Parallelepiped Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input Specification: The first and the single line contains three space-separated integers — the areas of the parallelepiped's faces. The area's values are positive (<=&gt;<=0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Specification: Print a single number — the sum of all edges of the parallelepiped. Demo Input: ['1 1 1\n', '4 6 6\n'] Demo Output: ['12\n', '28\n'] Note: In the first sample the parallelepiped has sizes 1 × 1 × 1, in the second one — 2 × 2 × 3.
1,042
Title: Bear and Tree Jumps Time Limit: None seconds Memory Limit: None megabytes Problem Description: A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of *n* vertices, numbered 1 through *n*. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most *k*. For a pair of vertices (*s*,<=*t*) we define *f*(*s*,<=*t*) as the minimum number of jumps Limak needs to get from *s* to *t*. Your task is to find the sum of *f*(*s*,<=*t*) over all pairs of vertices (*s*,<=*t*) such that *s*<=&lt;<=*t*. Input Specification: The first line of the input contains two integers *n* and *k* (2<=≤<=*n*<=≤<=200<=000, 1<=≤<=*k*<=≤<=5) — the number of vertices in the tree and the maximum allowed jump distance respectively. The next *n*<=-<=1 lines describe edges in the tree. The *i*-th of those lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*) — the indices on vertices connected with *i*-th edge. It's guaranteed that the given edges form a tree. Output Specification: Print one integer, denoting the sum of *f*(*s*,<=*t*) over all pairs of vertices (*s*,<=*t*) such that *s*<=&lt;<=*t*. Demo Input: ['6 2\n1 2\n1 3\n2 4\n2 5\n4 6\n', '13 3\n1 2\n3 2\n4 2\n5 2\n3 6\n10 6\n6 7\n6 13\n5 8\n5 9\n9 11\n11 12\n', '3 5\n2 1\n3 1\n'] Demo Output: ['20\n', '114\n', '3\n'] Note: In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). There are <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c0295201207e28a36e641d8cf599f45986059e71.png" style="max-width: 100.0%;max-height: 100.0%;"/> pairs of vertices (*s*, *t*) such that *s* &lt; *t*. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5·2 + 10·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (*s* &lt; *t*), so the answer is 3·1 = 3.
1,043
Title: XOR and OR Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string. A Bitlandish string is a string made only of characters "0" and "1". BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string *a*, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as *x* and the other one as *y*. Then he calculates two values *p* and *q*: *p*<==<=*x* *xor* *y*, *q*<==<=*x* *or* *y*. Then he replaces one of the two taken characters by *p* and the other one by *q*. The *xor* operation means the bitwise excluding OR operation. The *or* operation is the bitwise OR operation. So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string. You've got two Bitlandish strings *a* and *b*. Your task is to check if it is possible for BitHaval to transform string *a* to string *b* in several (possibly zero) described operations. Input Specification: The first line contains Bitlandish string *a*, the second line contains Bitlandish string *b*. The strings can have different lengths. It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106. Output Specification: Print "YES" if *a* can be transformed into *b*, otherwise print "NO". Please do not print the quotes. Demo Input: ['11\n10\n', '1\n01\n', '000\n101\n'] Demo Output: ['YES\n', 'NO\n', 'NO\n'] Note: none
1,044
Title: Driving Test Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 1. Polycarp's car overtakes the other car; 1. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 1. Polycarp's car goes past the "overtake is allowed" sign; 1. Polycarp's car goes past the "no speed limit"; 1. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view? Input Specification: The first line contains one integer number *n* (1<=≤<=*n*<=≤<=2·105) — number of events. Each of the next *n* lines starts with integer *t* (1<=≤<=*t*<=≤<=6) — the type of the event. An integer *s* (1<=≤<=*s*<=≤<=300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). Output Specification: Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view. Demo Input: ['11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300\n', '5\n1 100\n3 200\n2\n4\n5\n', '7\n1 20\n2\n6\n4\n6\n6\n2\n'] Demo Output: ['2\n', '0\n', '2\n'] Note: In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
1,045
Title: Thwarting Demonstrations Time Limit: None seconds Memory Limit: None megabytes Problem Description: It is dark times in Berland. Berlyand opposition, funded from a neighboring state, has organized a demonstration in Berland capital Bertown. Through the work of intelligence we know that the demonstrations are planned to last for *k* days. Fortunately, Berland has a special police unit, which can save the country. It has exactly *n* soldiers numbered from 1 to *n*. Berland general, the commander of the detachment, must schedule the detachment's work in these difficult *k* days. In each of these days, the general must send a certain number of police officers to disperse riots. Since the detachment is large and the general is not very smart, he can only select a set of all soldiers numbered from *l* to *r*, inclusive, where *l* and *r* are selected arbitrarily. Now the general has exactly two problems. First, he cannot send the same group twice — then soldiers get bored and they rebel. Second, not all soldiers are equally reliable. Every soldier has a reliability of *a**i*. The reliability of the detachment is counted as the sum of reliabilities of soldiers in it. The reliability of a single soldier can be negative, then when you include him in the detachment, he will only spoil things. The general is distinguished by his great greed and shortsightedness, so each day he sends to the dissolution the most reliable group of soldiers possible (that is, of all the groups that have not been sent yet). The Berland Government has decided to know what would be the minimum reliability of the detachment, sent to disperse the demonstrations during these *k* days. The general himself can not cope with such a difficult task. Help him to not embarrass himself in front of his superiors! Input Specification: The first line contains two integers *n* and *k* — the number of soldiers in the detachment and the number of times somebody goes on duty. The second line contains *n* space-separated integers *a**i*, their absolute value doesn't exceed 109 — the soldiers' reliabilities. Please do not use the %lld specifier to read or write 64-bit integers in С++, it is preferred to use cin, cout streams of the %I64d specifier. Output Specification: Print a single number — the sought minimum reliability of the groups that go on duty during these *k* days. Demo Input: ['3 4\n1 4 2\n', '4 6\n2 -1 2 -1\n', '8 10\n1 -2 3 -4 5 -6 7 -8\n'] Demo Output: ['4\n', '1\n', '2\n'] Note: none
1,046
Title: Visible Black Areas Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya has a polygon consisting of $n$ vertices. All sides of the Petya's polygon are parallel to the coordinate axes, and each two adjacent sides of the Petya's polygon are perpendicular. It is guaranteed that the polygon is simple, that is, it doesn't have self-intersections and self-touches. All internal area of the polygon (borders are not included) was painted in black color by Petya. Also, Petya has a rectangular window, defined by its coordinates, through which he looks at the polygon. A rectangular window can not be moved. The sides of the rectangular window are parallel to the coordinate axes. Determine the number of black connected areas of Petya's polygon, which can be seen through the rectangular window. Input Specification: The first line contain four integers $x_1, y_1, x_2, y_2$ ($x_1 &lt; x_2$, $y_2 &lt; y_1$) — the coordinates of top-left and bottom-right corners of the rectangular window. The second line contains a single integer $n$ ($4 \le n \le 15\,000$) — the number of vertices in Petya's polygon. Each of the following $n$ lines contains two integers — the coordinates of vertices of the Petya's polygon in counterclockwise order. Guaranteed, that the given polygon satisfies the conditions described in the statement. All coordinates of the rectangular window and all coordinates of the vertices of the polygon are non-negative and do not exceed $15\,000$. Output Specification: Print the number of black connected areas of Petya's polygon, which can be seen through the rectangular window. Demo Input: ['5 7 16 3\n16\n0 0\n18 0\n18 6\n16 6\n16 1\n10 1\n10 4\n7 4\n7 2\n2 2\n2 6\n12 6\n12 12\n10 12\n10 8\n0 8\n'] Demo Output: ['2'] Note: The example corresponds to the picture above.
1,047
Title: Arpa’s obvious problem and Mehrdad’s terrible solution Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are some beautiful girls in Arpa’s land as mentioned before. Once Arpa came up with an obvious problem: Given an array and a number *x*, count the number of pairs of indices *i*,<=*j* (1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*) such that , where is bitwise xor operation (see notes for explanation). Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem. Input Specification: First line contains two integers *n* and *x* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*x*<=≤<=105) — the number of elements in the array and the integer *x*. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105) — the elements of the array. Output Specification: Print a single integer: the answer to the problem. Demo Input: ['2 3\n1 2\n', '6 1\n5 1 2 3 4 1\n'] Demo Output: ['1', '2'] Note: In the first sample there is only one pair of *i* = 1 and *j* = 2. <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bec9071ce5b1039982fe0ae476cd31528ddfa2f3.png" style="max-width: 100.0%;max-height: 100.0%;"/> so the answer is 1. In the second sample the only two pairs are *i* = 3, *j* = 4 (since <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3701990d023d19c5da0b315b5057d572ec11e4fd.png" style="max-width: 100.0%;max-height: 100.0%;"/>) and *i* = 1, *j* = 5 (since <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8c96223ca88621240a5ee6e1498acb7e4ce0eb44.png" style="max-width: 100.0%;max-height: 100.0%;"/>). A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: [https://en.wikipedia.org/wiki/Bitwise_operation#XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
1,048
Title: Labyrinth-13 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,049
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation *p* of length *n* or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation. Let's define the deviation of a permutation *p* as . Find a cyclic shift of permutation *p* with minimum possible deviation. If there are multiple solutions, print any of them. Let's denote id *k* (0<=≤<=*k*<=&lt;<=*n*) of a cyclic shift of permutation *p* as the number of right shifts needed to reach this shift, for example: - *k*<==<=0: shift *p*1,<=*p*2,<=... *p**n*, - *k*<==<=1: shift *p**n*,<=*p*1,<=... *p**n*<=-<=1, - ..., - *k*<==<=*n*<=-<=1: shift *p*2,<=*p*3,<=... *p**n*,<=*p*1. Input Specification: First line contains single integer *n* (2<=≤<=*n*<=≤<=106) — the length of the permutation. The second line contains *n* space-separated integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*) — the elements of the permutation. It is guaranteed that all elements are distinct. Output Specification: Print two integers: the minimum deviation of cyclic shifts of permutation *p* and the id of such shift. If there are multiple solutions, print any of them. Demo Input: ['3\n1 2 3\n', '3\n2 3 1\n', '3\n3 2 1\n'] Demo Output: ['0 0\n', '0 1\n', '2 1\n'] Note: In the first sample test the given permutation *p* is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well. In the second sample test the deviation of *p* equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift. In the third sample test the deviation of *p* equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.
1,050
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Arpa has found a list containing *n* numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1. Arpa can perform two types of operations: - Choose a number and delete it with cost *x*. - Choose a number and increase it by 1 with cost *y*. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number. Help Arpa to find the minimum possible cost to make the list good. Input Specification: First line contains three integers *n*, *x* and *y* (1<=≤<=*n*<=≤<=5·105, 1<=≤<=*x*,<=*y*<=≤<=109) — the number of elements in the list and the integers *x* and *y*. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the elements of the list. Output Specification: Print a single integer: the minimum possible cost to make the list good. Demo Input: ['4 23 17\n1 17 17 16\n', '10 6 2\n100 49 71 73 66 96 8 60 41 63\n'] Demo Output: ['40\n', '10\n'] Note: In example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17). A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd [here](https://en.wikipedia.org/wiki/Greatest_common_divisor).
1,051
Title: Rectangular Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has *n* pebbles. He arranges them in *a* equal rows, each row has *b* pebbles (*a*<=&gt;<=1). Note that the Beaver must use all the pebbles he has, i. e. *n*<==<=*a*·*b*. Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, *b* pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of *a* and *b*) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble. The game process can be represented as a finite sequence of integers *c*1,<=...,<=*c**k*, where: - *c*1<==<=*n* - *c**i*<=+<=1 is the number of pebbles that the Beaver ends up with after the *i*-th move, that is, the number of pebbles in a row after some arrangement of *c**i* pebbles (1<=≤<=*i*<=&lt;<=*k*). Note that *c**i*<=&gt;<=*c**i*<=+<=1. - *c**k*<==<=1 The result of the game is the sum of numbers *c**i*. You are given *n*. Find the maximum possible result of the game. Input Specification: The single line of the input contains a single integer *n* — the initial number of pebbles the Smart Beaver has. The input limitations for getting 30 points are: - 2<=≤<=*n*<=≤<=50 The input limitations for getting 100 points are: - 2<=≤<=*n*<=≤<=109 Output Specification: Print a single number — the maximum possible result of the game. Demo Input: ['10\n', '8\n'] Demo Output: ['16\n', '15\n'] Note: Consider the first example (*c*<sub class="lower-index">1</sub> = 10). The possible options for the game development are: - Arrange the pebbles in 10 rows, one pebble per row. Then *c*<sub class="lower-index">2</sub> = 1, and the game ends after the first move with the result of 11. - Arrange the pebbles in 5 rows, two pebbles per row. Then *c*<sub class="lower-index">2</sub> = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. *c*<sub class="lower-index">3</sub> = 1, and the game ends with the result of 13. - Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to *c*<sub class="lower-index">2</sub> = 5, *c*<sub class="lower-index">3</sub> = 1, and the game ends with the result of 16 — the maximum possible result.
1,052
Title: Special Offer! Super Price 999 Bourles! Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors. Polycaprus calculated that the optimal celling price for such scissors would be *p* bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect. Polycarpus agrees to lower the price by no more than *d* bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price. Note, Polycarpus counts only the trailing nines in a price. Input Specification: The first line contains two integers *p* and *d* (1<=≤<=*p*<=≤<=1018; 0<=≤<=*d*<=&lt;<=*p*) — the initial price of scissors and the maximum possible price reduction. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output Specification: Print the required price — the maximum price that ends with the largest number of nines and that is less than *p* by no more than *d*. The required number shouldn't have leading zeroes. Demo Input: ['1029 102\n', '27191 17\n'] Demo Output: ['999\n', '27189\n'] Note: none
1,053
Title: Petya and Divisors Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Little Petya loves looking for numbers' divisors. One day Petya came across the following problem: You are given *n* queries in the form "*x**i* *y**i*". For each query Petya should count how many divisors of number *x**i* divide none of the numbers *x**i*<=-<=*y**i*,<=*x**i*<=-<=*y**i*<=+<=1,<=...,<=*x**i*<=-<=1. Help him. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=105). Each of the following *n* lines contain two space-separated integers *x**i* and *y**i* (1<=≤<=*x**i*<=≤<=105, 0<=≤<=*y**i*<=≤<=*i*<=-<=1, where *i* is the query's ordinal number; the numeration starts with 1). If *y**i*<==<=0 for the query, then the answer to the query will be the number of divisors of the number *x**i*. In this case you do not need to take the previous numbers *x* into consideration. Output Specification: For each query print the answer on a single line: the number of positive integers *k* such that Demo Input: ['6\n4 0\n3 1\n5 2\n6 2\n18 4\n10000 3\n'] Demo Output: ['3\n1\n1\n2\n2\n22\n'] Note: Let's write out the divisors that give answers for the first 5 queries: 1) 1, 2, 4 2) 3 3) 5 4) 2, 6 5) 9, 18
1,054
Title: Book of Evil Time Limit: None seconds Memory Limit: None megabytes Problem Description: Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains *n* settlements numbered from 1 to *n*. Moving through the swamp is very difficult, so people tramped exactly *n*<=-<=1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths. The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range *d*. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance *d* or less from the settlement where the Book resides. Manao has heard of *m* settlements affected by the Book of Evil. Their numbers are *p*1,<=*p*2,<=...,<=*p**m*. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task. Input Specification: The first line contains three space-separated integers *n*, *m* and *d* (1<=≤<=*m*<=≤<=*n*<=≤<=100000; 0<=≤<=*d*<=≤<=*n*<=-<=1). The second line contains *m* distinct space-separated integers *p*1,<=*p*2,<=...,<=*p**m* (1<=≤<=*p**i*<=≤<=*n*). Then *n*<=-<=1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers *a**i* and *b**i* representing the ends of this path. Output Specification: Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0. Demo Input: ['6 2 3\n1 2\n1 5\n2 3\n3 4\n4 5\n5 6\n'] Demo Output: ['3\n'] Note: Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.
1,055
Title: Multitasking Time Limit: None seconds Memory Limit: None megabytes Problem Description: Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort *n* arrays simultaneously, each array consisting of *m* integers. Iahub can choose a pair of distinct indices *i* and *j* (1<=≤<=*i*,<=*j*<=≤<=*m*,<=*i*<=≠<=*j*). Then in each array the values at positions *i* and *j* are swapped only if the value at position *i* is strictly greater than the value at position *j*. Iahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the *n* arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most (at most pairs). Help Iahub, find any suitable array. Input Specification: The first line contains three integers *n* (1<=≤<=<=*n*<=≤<=1000), *m* (1<=≤<=*m*<=≤<=<=100) and *k*. Integer *k* is 0 if the arrays must be sorted in ascending order, and 1 if the arrays must be sorted in descending order. Each line *i* of the next *n* lines contains *m* integers separated by a space, representing the *i*-th array. For each element *x* of the array *i*, 1<=≤<=*x*<=≤<=106 holds. Output Specification: On the first line of the output print an integer *p*, the size of the array (*p* can be at most ). Each of the next *p* lines must contain two distinct integers *i* and *j* (1<=≤<=*i*,<=*j*<=≤<=*m*,<=*i*<=≠<=*j*), representing the chosen indices. If there are multiple correct answers, you can print any. Demo Input: ['2 5 0\n1 3 2 5 4\n1 4 3 2 5\n', '3 2 1\n1 2\n2 3\n3 4\n'] Demo Output: ['3\n2 4\n2 3\n4 5\n', '1\n2 1\n'] Note: Consider the first sample. After the first operation, the arrays become [1, 3, 2, 5, 4] and [1, 2, 3, 4, 5]. After the second operation, the arrays become [1, 2, 3, 5, 4] and [1, 2, 3, 4, 5]. After the third operation they become [1, 2, 3, 4, 5] and [1, 2, 3, 4, 5].
1,056
Title: Delivery Bears Time Limit: None seconds Memory Limit: None megabytes Problem Description: Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city. In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with *n* nodes and *m* edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node *n*. The total weight that travels across a particular edge must not exceed the weight capacity of that edge. Niwel has exactly *x* bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like. Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight. Input Specification: The first line contains three integers *n*, *m* and *x* (2<=≤<=*n*<=≤<=50, 1<=≤<=*m*<=≤<=500, 1<=≤<=*x*<=≤<=100<=000) — the number of nodes, the number of directed edges and the number of bears, respectively. Each of the following *m* lines contains three integers *a**i*, *b**i* and *c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*, 1<=≤<=*c**i*<=≤<=1<=000<=000). This represents a directed edge from node *a**i* to *b**i* with weight capacity *c**i*. There are no self loops and no multiple edges from one city to the other city. More formally, for each *i* and *j* that *i*<=≠<=*j* it's guaranteed that *a**i*<=≠<=*a**j* or *b**i*<=≠<=*b**j*. It is also guaranteed that there is at least one path from node 1 to node *n*. Output Specification: Print one real value on a single line — the maximum amount of weight Niwel can deliver if he uses exactly *x* bears. 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: ['4 4 3\n1 2 2\n2 4 1\n1 3 1\n3 4 2\n', '5 11 23\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 3 4\n2 4 5\n3 5 6\n1 4 2\n2 5 3\n1 5 2\n3 2 30\n'] Demo Output: ['1.5000000000\n', '10.2222222222\n'] Note: In the first sample, Niwel has three bears. Two bears can choose the path <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7c0aa60a06309ef607b7159fd7f3687ea0d943ce.png" style="max-width: 100.0%;max-height: 100.0%;"/>, while one bear can choose the path <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a26c2f3e93c9d9be6c21cb5d2bd6ac1f99f4ff55.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Even though the bear that goes on the path <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a26c2f3e93c9d9be6c21cb5d2bd6ac1f99f4ff55.png" style="max-width: 100.0%;max-height: 100.0%;"/> can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.
1,057
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: - *a*1<==<=*p*, where *p* is some integer; - *a**i*<==<=*a**i*<=-<=1<=+<=(<=-<=1)*i*<=+<=1·*q* (*i*<=&gt;<=1), where *q* is some integer. Right now Gena has a piece of paper with sequence *b*, consisting of *n* integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression. Sequence *s*1,<=<=*s*2,<=<=...,<=<=*s**k* is a subsequence of sequence *b*1,<=<=*b*2,<=<=...,<=<=*b**n*, if there is such increasing sequence of indexes *i*1,<=*i*2,<=...,<=*i**k* (1<=<=≤<=<=*i*1<=<=&lt;<=<=*i*2<=<=&lt;<=... <=<=&lt;<=<=*i**k*<=<=≤<=<=*n*), that *b**i**j*<=<==<=<=*s**j*. In other words, sequence *s* can be obtained from *b* by crossing out some elements. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=4000). The next line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=106). Output Specification: Print a single integer — the length of the required longest subsequence. Demo Input: ['2\n3 5\n', '4\n10 20 10 30\n'] Demo Output: ['2\n', '3\n'] Note: In the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10, 20, 10.
1,058
Title: Bear and Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game. Input Specification: The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=90) — the number of interesting minutes. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t*1<=&lt;<=*t*2<=&lt;<=... *t**n*<=≤<=90), given in the increasing order. Output Specification: Print the number of minutes Limak will watch the game. Demo Input: ['3\n7 20 88\n', '9\n16 20 30 40 50 60 70 80 90\n', '9\n15 20 30 40 50 60 70 80 90\n'] Demo Output: ['35\n', '15\n', '90\n'] Note: In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes. In the second sample, the first 15 minutes are boring. In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
1,059
Title: Two Sets Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little Petya likes numbers a lot. Recently his mother has presented him a collection of *n* non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: - Let's introduce *x*1 to denote the *xor* of all numbers Petya has got left; and let's introduce *x*2 to denote the *xor* of all numbers he gave to Masha. Value (*x*1<=+<=*x*2) must be as large as possible. - If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value *x*1. The *xor* operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the *xor* of an empty set of numbers equals 0. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018. Output Specification: Print *n* space-separated integers, the *i*-th of them should equal either 1, if Petya keeps the number that follows *i*-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input. Demo Input: ['6\n1 2 3 4 5 6\n', '3\n1000000000000 1000000000000 1000000000000\n', '8\n1 1 2 2 3 3 4 4\n'] Demo Output: ['2 2 2 2 2 2\n', '2 2 2\n', '1 2 1 2 2 2 1 2\n'] Note: none
1,060
Title: Valera and Plates Time Limit: None seconds Memory Limit: None megabytes Problem Description: Valera is a lazy student. He has *m* clean bowls and *k* clean plates. Valera has made an eating plan for the next *n* days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input Specification: The first line of the input contains three integers *n*, *m*, *k* (1<=≤<=*n*,<=*m*,<=*k*<=≤<=1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=2). If *a**i* equals one, then on day *i* Valera will eat a first type dish. If *a**i* equals two, then on day *i* Valera will eat a second type dish. Output Specification: Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Demo Input: ['3 1 1\n1 2 1\n', '4 3 1\n1 1 1 1\n', '3 1 2\n2 2 2\n', '8 2 2\n1 2 1 2 1 2 1 2\n'] Demo Output: ['1\n', '1\n', '0\n', '4\n'] Note: In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.
1,061
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarpus has a chessboard of size *n*<=×<=*m*, where *k* rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated *q* rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of ​​the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. Input Specification: The first line contains four integers *n*, *m*, *k* and *q* (1<=≤<=*n*,<=*m*<=≤<=100<=000, 1<=≤<=*k*,<=*q*<=≤<=200<=000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to *n* horizontally and from 1 to *m* vertically. Next *k* lines contain pairs of integers "*x* *y*", describing the positions of the rooks (1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m*). It is guaranteed that all the rooks are in distinct squares. Next *q* lines describe the strategically important areas as groups of four integers "*x*1 *y*1 *x*2 *y*2" (1<=≤<=*x*1<=≤<=*x*2<=≤<=*n*, 1<=≤<=*y*1<=≤<=*y*2<=≤<=*m*). The corresponding rectangle area consists of cells (*x*,<=*y*), for which *x*1<=≤<=*x*<=≤<=*x*2, *y*1<=≤<=*y*<=≤<=*y*2. Strategically important areas can intersect of coincide. Output Specification: Print *q* lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. Demo Input: ['4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3\n'] Demo Output: ['YES\nYES\nNO\n'] Note: Picture to the sample: <img class="tex-graphics" src="https://espresso.codeforces.com/4b760b396c0058262fe776c85e60c5effd77ec1a.png" style="max-width: 100.0%;max-height: 100.0%;"/> For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook.
1,062
Title: Interval Cubing Time Limit: None seconds Memory Limit: None megabytes Problem Description: While learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem: Given an integer sequence *a*1,<=*a*2,<=...,<=*a**n*. You should run *q* queries of two types: 1. Given two integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), ask the sum of all elements in the sequence *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r*. 1. Given two integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), let each element *x* in the sequence *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r* becomes *x*3. In other words, apply an assignments *a**l*<==<=*a**l*3,<=*a**l*<=+<=1<==<=*a**l*<=+<=13,<=...,<=*a**r*<==<=*a**r*3. For every query of type 1, output the answer to it. Tiny himself surely cannot work it out, so he asks you for help. In addition, Tiny is a prime lover. He tells you that because the answer may be too huge, you should only output it modulo 95542721 (this number is a prime number). Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=105), representing the length of the sequence. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109). The third line contains an integer *q* (1<=≤<=*q*<=≤<=105), representing the number of queries. Then follow *q* lines. Each line contains three integers *t**i* (1<=≤<=*t**i*<=≤<=2), *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*), where *t**i* stands for the type of the query while *l**i* and *r**i* is the parameters of the query, correspondingly. Output Specification: For each 1-type query, print the answer to it per line. You should notice that each printed number should be non-negative and less than 95542721. Demo Input: ['8\n1 2 3 4 5 6 7 8\n5\n1 2 5\n2 2 5\n1 2 5\n2 3 6\n1 4 7\n'] Demo Output: ['14\n224\n2215492\n'] Note: none
1,063
Title: Divisiblity of Differences Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a multiset of *n* integers. You should select exactly *k* of them in a such way that the difference between any two of them is divisible by *m*, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset. Input Specification: First line contains three integers *n*, *k* and *m* (2<=≤<=*k*<=≤<=*n*<=≤<=100<=000, 1<=≤<=*m*<=≤<=100<=000) — number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109) — the numbers in the multiset. Output Specification: If it is not possible to select *k* numbers in the desired way, output «No» (without the quotes). Otherwise, in the first line of output print «Yes» (without the quotes). In the second line print *k* integers *b*1,<=*b*2,<=...,<=*b**k* — the selected numbers. If there are multiple possible solutions, print any of them. Demo Input: ['3 2 3\n1 8 4\n', '3 3 3\n1 8 4\n', '4 3 5\n2 7 7 7\n'] Demo Output: ['Yes\n1 4 ', 'No', 'Yes\n2 7 7 '] Note: none
1,064
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road. We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (*x*1,<=*y*1), and the distress signal came from the point (*x*2,<=*y*2). Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed meters per second. Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (*v**x*,<=*v**y*) for the nearest *t* seconds, and then will change to (*w**x*,<=*w**y*). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (*x*,<=*y*), while its own velocity relative to the air is equal to zero and the wind (*u**x*,<=*u**y*) is blowing, then after seconds the new position of the dirigible will be . Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer. It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air. Input Specification: The first line of the input contains four integers *x*1, *y*1, *x*2, *y*2 (|*x*1|,<=<=|*y*1|,<=<=|*x*2|,<=<=|*y*2|<=≤<=10<=000) — the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively. The second line contains two integers and *t* (0<=&lt;<=*v*,<=*t*<=≤<=1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively. Next follow one per line two pairs of integer (*v**x*,<=*v**y*) and (*w**x*,<=*w**y*), describing the wind for the first *t* seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that and . Output Specification: Print a single real value — the minimum time the rescuers need to get to point (*x*2,<=*y*2). You 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: ['0 0 5 5\n3 2\n-1 -1\n-1 0\n', '0 0 0 1000\n100 1000\n-50 0\n50 0\n'] Demo Output: ['3.729935587093555327\n', '11.547005383792516398\n'] Note: none
1,065
Title: Numbers Exchange Time Limit: None seconds Memory Limit: None megabytes Problem Description: Eugeny has *n* cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has *m* cards, distinct numbers from 1 to *m* are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange. Input Specification: The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=2·105, 1<=≤<=*m*<=≤<=109) — the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that *n* is even. The second line contains a sequence of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the numbers on Eugeny's cards. Output Specification: If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print *n* integers — Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the *i*-th card wasn't exchanged then the *i*-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the *i*-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them. Demo Input: ['6 2\n5 6 7 9 4 5\n', '8 6\n7 7 7 7 8 8 8 8\n', '4 1\n4 2 1 10\n'] Demo Output: ['1\n5 6 7 9 4 2 \n', '6\n7 2 4 6 8 1 3 5 \n', '-1\n'] Note: none
1,066
Title: Clues Time Limit: None seconds Memory Limit: None megabytes Problem Description: As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues *A* and *B* and the direct link between clues *B* and *A* is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues *A* and *B* are considered linked either if there is a direct link between them or if there is a direct link between *A* and some other clue *C* which is linked to *B*. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals *T*. Please count the number of different ways to find exactly *T* direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo *k*. Input Specification: The first line contains three space-separated integers *n*,<=*m*,<=*k* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*m*<=≤<=105, 1<=≤<=*k*<=≤<=109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next *m* lines contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=*n*,<=*a*<=≠<=*b*), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Specification: Print the single number — the answer to the problem modulo *k*. Demo Input: ['2 0 1000000000\n', '3 0 100\n', '4 1 1000000000\n1 4\n'] Demo Output: ['1\n', '3\n', '8\n'] Note: The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.
1,067
Title: Ilya and Two Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ilya has recently taken up archaeology. He's recently found two numbers, written in the *m*-based notation. Each of the found numbers consisted of exactly *n* digits. Ilya immediately started looking for information about those numbers. He learned that the numbers are part of a cyphered code and the one who can decypher it can get the greatest treasure. After considerable research Ilya understood that to decypher the code, he should do the following: - Rearrange digits in the first number in some manner. Similarly, rearrange digits in the second number in some manner. As a result of this operation, the numbers can get leading zeroes. - Add numbers, digit by digit, modulo *m*. In other words, we need to get the third number of length *n*, each digit of the number is the sum of the respective numbers of the found numbers. For example, suppose there are two numbers recorded in the ternary notation, 001210 and 012111, then if you add them to each other digit by digit modulo 3, you will get number 010021. - The key to the code is the maximum possible number that can be obtained in the previous step. Help Ilya, find the key to the code. Input Specification: The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=105,<=*m*<=&gt;<=1). The second line contains the first found number, the third line contains the second found number. The numbers are recorded as a sequence of digits in the *m*-based notation. Each digit is an integer from 0 to *m*<=-<=1. The digits in the line are written in the order from the most significant digits to the least significant ones. The given numbers can contain leading zeroes. Output Specification: Print *n* *m*-base digits. The resulting third number written in the *m*-based notation. Print the digits in the order from the most significant digits to the least significant ones. Demo Input: ['4 7\n5 4 3 2\n5 6 5 4\n', '5 5\n2 4 4 1 3\n1 0 1 2 4\n'] Demo Output: ['6 4 2 1 \n', '4 4 4 3 2 \n'] Note: none
1,068
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of *n* narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island *i* has coordinates [*l**i*,<=*r**i*], besides, *r**i*<=&lt;<=*l**i*<=+<=1 for 1<=≤<=*i*<=≤<=*n*<=-<=1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length *a* can be placed between the *i*-th and the (*i*<=+<=1)-th islads, if there are such coordinates of *x* and *y*, that *l**i*<=≤<=*x*<=≤<=*r**i*, *l**i*<=+<=1<=≤<=*y*<=≤<=*r**i*<=+<=1 and *y*<=-<=*x*<==<=*a*. The detective was supplied with *m* bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input Specification: The first line contains integers *n* (2<=≤<=*n*<=≤<=2·105) and *m* (1<=≤<=*m*<=≤<=2·105) — the number of islands and bridges. Next *n* lines each contain two integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=1018) — the coordinates of the island endpoints. The last line contains *m* integer numbers *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=1018) — the lengths of the bridges that Andrewid got. Output Specification: If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print *n*<=-<=1 numbers *b*1,<=*b*2,<=...,<=*b**n*<=-<=1, which mean that between islands *i* and *i*<=+<=1 there must be used a bridge number *b**i*. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Demo Input: ['4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8\n', '2 2\n11 14\n17 18\n2 9\n', '2 1\n1 1\n1000000000000000000 1000000000000000000\n999999999999999999\n'] Demo Output: ['Yes\n2 3 1 \n', 'No\n', 'Yes\n1 \n'] Note: In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
1,069
Title: Network Configuration Time Limit: None seconds Memory Limit: None megabytes Problem Description: The R1 company wants to hold a web search championship. There were *n* computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the *i*-th computer it was *a**i* kilobits per second. There will be *k* participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible. The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least *k* of *n* computers had the same data transfer speed and the data transfer speed on these computers was as large as possible? Input Specification: The first line contains two space-separated integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=100) — the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n* (16<=≤<=*a**i*<=≤<=32768); number *a**i* denotes the maximum data transfer speed on the *i*-th computer. Output Specification: Print a single integer — the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer. Demo Input: ['3 2\n40 20 30\n', '6 4\n100 20 40 20 50 50\n'] Demo Output: ['30\n', '40\n'] Note: In the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal.
1,070
Title: King Moves Time Limit: None seconds Memory Limit: None megabytes Problem Description: The only king stands on the standard chess board. You are given his position in format "cd", where *c* is the column from 'a' to 'h' and *d* is the row from '1' to '8'. Find the number of moves permitted for the king. Check the king's moves here [https://en.wikipedia.org/wiki/King_(chess)](https://en.wikipedia.org/wiki/King_(chess)). Input Specification: The only line contains the king's position in the format "cd", where 'c' is the column from 'a' to 'h' and 'd' is the row from '1' to '8'. Output Specification: Print the only integer *x* — the number of moves permitted for the king. Demo Input: ['e4\n'] Demo Output: ['8\n'] Note: none
1,071
Title: Terse princess Time Limit: None seconds Memory Limit: None megabytes Problem Description: «Next please», — the princess called and cast an estimating glance at the next groom. The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous ones added together, she exclaims «Wow!» (no «Oh...» in this case). At the sight of the first groom the princess stays calm and says nothing. The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw *n* grooms, said «Oh...» exactly *a* times and exclaimed «Wow!» exactly *b* times. Your task is to output a sequence of *n* integers *t*1,<=*t*2,<=...,<=*t**n*, where *t**i* describes the fortune of *i*-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1. Input Specification: The only line of input data contains three integer numbers *n*,<=*a* and *b* (1<=≤<=*n*<=≤<=100,<=0<=≤<=*a*,<=*b*<=≤<=15,<=*n*<=&gt;<=*a*<=+<=*b*), separated with single spaces. Output Specification: Output any sequence of integers *t*1,<=*t*2,<=...,<=*t**n*, where *t**i* (1<=≤<=*t**i*<=≤<=50000) is the fortune of *i*-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1. Demo Input: ['10 2 3\n', '5 0 0\n'] Demo Output: ['5 1 3 6 16 35 46 4 200 99', '10 10 6 6 5'] Note: Let's have a closer look at the answer for the first sample test. - The princess said «Oh...» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99. - The princess exclaimed «Wow!» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.
1,072
Title: Points on the line Time Limit: None seconds Memory Limit: None megabytes Problem Description: We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1,<=3,<=2,<=1} is 2. Diameter of multiset consisting of one point is 0. You are given *n* points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed *d*? Input Specification: The first line contains two integers *n* and *d* (1<=≤<=*n*<=≤<=100,<=0<=≤<=*d*<=≤<=100) — the amount of points and the maximum allowed diameter respectively. The second line contains *n* space separated integers (1<=≤<=*x**i*<=≤<=100) — the coordinates of the points. Output Specification: Output a single integer — the minimum number of points you have to remove. Demo Input: ['3 1\n2 1 4\n', '3 0\n7 7 7\n', '6 3\n1 3 4 6 9 10\n'] Demo Output: ['1\n', '0\n', '3\n'] Note: In the first test case the optimal strategy is to remove the point with coordinate 4. The remaining points will have coordinates 1 and 2, so the diameter will be equal to 2 - 1 = 1. In the second test case the diameter is equal to 0, so its is unnecessary to remove any points. In the third test case the optimal strategy is to remove points with coordinates 1, 9 and 10. The remaining points will have coordinates 3, 4 and 6, so the diameter will be equal to 6 - 3 = 3.
1,073
Title: Minimal Labels Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a directed acyclic graph with *n* vertices and *m* edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected. You should assign labels to all vertices in such a way that: - Labels form a valid permutation of length *n* — an integer sequence such that each integer from 1 to *n* appears exactly once in it. - If there exists an edge from vertex *v* to vertex *u* then *label**v* should be smaller than *label**u*. - Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions. Input Specification: The first line contains two integer numbers *n*, *m* (2<=≤<=*n*<=≤<=105,<=1<=≤<=*m*<=≤<=105). Next *m* lines contain two integer numbers *v* and *u* (1<=≤<=*v*,<=*u*<=≤<=*n*,<=*v*<=≠<=*u*) — edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges. Output Specification: Print *n* numbers — lexicographically smallest correct permutation of labels of vertices. Demo Input: ['3 3\n1 2\n1 3\n3 2\n', '4 5\n3 1\n4 1\n2 3\n3 4\n2 4\n', '5 4\n3 1\n2 1\n2 3\n4 5\n'] Demo Output: ['1 3 2 \n', '4 1 2 3 \n', '3 1 2 4 5 \n'] Note: none
1,074
Title: Thief in a Shop Time Limit: None seconds Memory Limit: None megabytes Problem Description: A thief made his way to a shop. As usual he has his lucky knapsack with him. The knapsack can contain *k* objects. There are *n* kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind *i* is *a**i*. The thief is greedy, so he will take exactly *k* products (it's possible for some kinds to take several products of that kind). Find all the possible total costs of products the thief can nick into his knapsack. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=1000) — the number of kinds of products and the number of products the thief will take. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=1000) — the costs of products for kinds from 1 to *n*. Output Specification: Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order. Demo Input: ['3 2\n1 2 3\n', '5 5\n1 1 1 1 1\n', '3 3\n3 5 11\n'] Demo Output: ['2 3 4 5 6\n', '5\n', '9 11 13 15 17 19 21 25 27 33\n'] Note: none
1,075
Title: GCD of Polynomials Time Limit: None seconds Memory Limit: None megabytes Problem Description: Suppose you have two polynomials and . Then polynomial can be uniquely represented in the following way: This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, denotes the degree of polynomial *P*(*x*). is called the remainder of division of polynomial by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer *n*. You have to build two polynomials with degrees not greater than *n*, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of *x*) are equal to one, and the described Euclid's algorithm performs exactly *n* steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair to pair . Input Specification: You are given a single integer *n* (1<=≤<=*n*<=≤<=150) — the number of steps of the algorithm you need to reach. Output Specification: Print two polynomials in the following format. In the first line print a single integer *m* (0<=≤<=*m*<=≤<=*n*) — the degree of the polynomial. In the second line print *m*<=+<=1 integers between <=-<=1 and 1 — the coefficients of the polynomial, from constant to leading. The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly *n* steps when called using these polynomials. If there is no answer for the given *n*, print -1. If there are multiple answer, print any of them. Demo Input: ['1\n', '2\n'] Demo Output: ['1\n0 1\n0\n1\n', '2\n-1 0 1\n1\n0 1\n'] Note: In the second example you can print polynomials *x*<sup class="upper-index">2</sup> - 1 and *x*. The sequence of transitions is There are two steps in it.
1,076
Title: Boxes And Balls Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ivan has *n* different boxes. The first of them contains some balls of *n* different colors. Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every *i* (1<=≤<=*i*<=≤<=*n*) *i*-th box will contain all balls with color *i*. In order to do this, Ivan will make some turns. Each turn he does the following: 1. Ivan chooses any non-empty box and takes all balls from this box; 1. Then Ivan chooses any *k* empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into *k* non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either *k*<==<=2 or *k*<==<=3. The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes. Help Ivan to determine the minimum possible penalty of the game! Input Specification: The first line contains one integer number *n* (1<=≤<=*n*<=≤<=200000) — the number of boxes and colors. The second line contains *n* integer numbers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=109), where *a**i* is the number of balls with color *i*. Output Specification: Print one number — the minimum possible penalty of the game. Demo Input: ['3\n1 2 3\n', '4\n2 3 4 5\n'] Demo Output: ['6\n', '19\n'] Note: In the first example you take all the balls from the first box, choose *k* = 3 and sort all colors to corresponding boxes. Penalty is 6. In the second example you make two turns: 1. Take all the balls from the first box, choose *k* = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14; 1. Take all the balls from the first box, choose *k* = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5. Total penalty is 19.
1,077
Title: Gena and Second Distance Time Limit: None seconds Memory Limit: None megabytes Problem Description: Gena doesn't like geometry, so he asks you to solve this problem for him. A rectangle with sides parallel to coordinate axes contains *n* dots. Let's consider some point of the plane. Let's count the distances from this point to the given *n* points. Let's sort these numbers in the non-decreasing order. We'll call the beauty of the point the second element of this array. If there are two mimimum elements in this array, the beaty will be equal to this minimum. Find the maximum beauty of a point inside the given rectangle. Input Specification: The first line contains three integers *w*,<=*h*,<=*n* (1<=≤<=*w*,<=*h*<=≤<=106,<=2<=≤<=*n*<=≤<=1000) — the lengths of the rectangle sides and the number of points. Next *n* lines contain two integers *x**i*,<=*y**i* (0<=≤<=*x**i*<=≤<=*w*,<=0<=≤<=*y**i*<=≤<=*h*) each — the coordinates of a point. It is possible that it will be coincident points. Output Specification: Print a single number — the maximum beauty of a point with the absolute or relative error of at most 10<=-<=9. Demo Input: ['5 5 4\n0 0\n5 0\n0 5\n5 5\n', '5 5 3\n4 0\n2 5\n4 1\n'] Demo Output: ['4.99999999941792340\n', '5.65685424744772010\n'] Note: The point which beauty we need to find must have coordinates (*x*, *y*), where 0 ≤ *x* ≤ *w*, 0 ≤ *y* ≤ *h*. Some of the *n* points can coincide.
1,078
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: John Doe has found the beautiful permutation formula. Let's take permutation *p*<==<=*p*1,<=*p*2,<=...,<=*p**n*. Let's define transformation *f* of this permutation: where *k* (*k*<=&gt;<=1) is an integer, the transformation parameter, *r* is such maximum integer that *rk*<=≤<=*n*. If *rk*<==<=*n*, then elements *p**rk*<=+<=1,<=*p**rk*<=+<=2 and so on are omitted. In other words, the described transformation of permutation *p* cyclically shifts to the left each consecutive block of length *k* and the last block with the length equal to the remainder after dividing *n* by *k*. John Doe thinks that permutation *f*(*f*( ... *f*(*p*<==<=[1,<=2,<=...,<=*n*],<=2) ... ,<=*n*<=-<=1),<=*n*) is beautiful. Unfortunately, he cannot quickly find the beautiful permutation he's interested in. That's why he asked you to help him. Your task is to find a beautiful permutation for the given *n*. For clarifications, see the notes to the third sample. Input Specification: A single line contains integer *n* (2<=≤<=*n*<=≤<=106). Output Specification: Print *n* distinct space-separated integers from 1 to *n* — a beautiful permutation of size *n*. Demo Input: ['2\n', '3\n', '4\n'] Demo Output: ['2 1 \n', '1 3 2 \n', '4 2 3 1 \n'] Note: A note to the third test sample: - *f*([1, 2, 3, 4], 2) = [2, 1, 4, 3] - *f*([2, 1, 4, 3], 3) = [1, 4, 2, 3] - *f*([1, 4, 2, 3], 4) = [4, 2, 3, 1]
1,079
Title: Alyona and copybooks Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack of three copybooks for *c* rubles. Alyona already has *n* copybooks. What is the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase. Input Specification: The only line contains 4 integers *n*, *a*, *b*, *c* (1<=≤<=*n*,<=*a*,<=*b*,<=*c*<=≤<=109). Output Specification: Print the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4. Demo Input: ['1 1 3 4\n', '6 2 1 1\n', '4 4 4 4\n', '999999999 1000000000 1000000000 1000000000\n'] Demo Output: ['3\n', '1\n', '0\n', '1000000000\n'] Note: In the first example Alyona can buy 3 packs of 1 copybook for 3*a* = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally. In the second example Alyuna can buy a pack of 2 copybooks for *b* = 1 ruble. She will have 8 copybooks in total. In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything. In the fourth example Alyona should buy one pack of one copybook.
1,080
Title: Office Keys Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are *n* people and *k* keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the minimum time needed for all *n* people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it. Input Specification: The first line contains three integers *n*, *k* and *p* (1<=≤<=*n*<=≤<=1<=000, *n*<=≤<=*k*<=≤<=2<=000, 1<=≤<=*p*<=≤<=109) — the number of people, the number of keys and the office location. The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — positions in which people are located initially. The positions are given in arbitrary order. The third line contains *k* distinct integers *b*1,<=*b*2,<=...,<=*b**k* (1<=≤<=*b**j*<=≤<=109) — positions of the keys. The positions are given in arbitrary order. Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point. Output Specification: Print the minimum time (in seconds) needed for all *n* to reach the office with keys. Demo Input: ['2 4 50\n20 100\n60 10 40 80\n', '1 2 10\n11\n15 7\n'] Demo Output: ['50\n', '7\n'] Note: In the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.
1,081
Title: cAPS lOCK Time Limit: None seconds Memory Limit: None megabytes Problem Description: wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: - either it only contains uppercase letters; - or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed. Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged. Input Specification: The first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive. Output Specification: Print the result of the given word's processing. Demo Input: ['cAPS\n', 'Lock\n'] Demo Output: ['Caps', 'Lock\n'] Note: none
1,082
Title: The Closest Pair Time Limit: None seconds Memory Limit: None megabytes Problem Description: Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded. The problem is the follows. Given *n* points in the plane, find a pair of points between which the distance is minimized. Distance between (*x*1,<=*y*1) and (*x*2,<=*y*2) is . The pseudo code of the unexpected code is as follows: Here, *tot* can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, *tot* should not be more than *k* in order not to get Time Limit Exceeded. You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded? Input Specification: A single line which contains two space-separated integers *n* and *k* (2<=≤<=*n*<=≤<=2000, 1<=≤<=*k*<=≤<=109). Output Specification: If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print *n* lines, and the *i*-th line contains two integers *x**i*,<=*y**i* (|*x**i*|,<=|*y**i*|<=≤<=109) representing the coordinates of the *i*-th point. The conditions below must be held: - All the points must be distinct. - |*x**i*|,<=|*y**i*|<=≤<=109. - After running the given code, the value of *tot* should be larger than *k*. Demo Input: ['4 3\n', '2 100\n'] Demo Output: ['0 0\n0 1\n1 0\n1 1\n', 'no solution\n'] Note: none
1,083
Title: Nineteen Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alice likes word "nineteen" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters. Help her to find the maximum number of "nineteen"s that she can get in her string. Input Specification: The first line contains a non-empty string *s*, consisting only of lowercase English letters. The length of string *s* doesn't exceed 100. Output Specification: Print a single integer — the maximum number of "nineteen"s that she can get in her string. Demo Input: ['nniinneetteeeenn\n', 'nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii\n', 'nineteenineteen\n'] Demo Output: ['2', '2', '2'] Note: none
1,084
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Память компьютера состоит из *n* ячеек, которые выстроены в ряд. Пронумеруем ячейки от 1 до *n* слева направо. Про каждую ячейку известно, свободна она или принадлежит какому-либо процессу (в таком случае известен процесс, которому она принадлежит). Для каждого процесса известно, что принадлежащие ему ячейки занимают в памяти непрерывный участок. С помощью операций вида «переписать данные из занятой ячейки в свободную, а занятую теперь считать свободной» требуется расположить все принадлежащие процессам ячейки в начале памяти компьютера. Другими словами, любая свободная ячейка должна располагаться правее (иметь больший номер) любой занятой. Вам необходимо найти минимальное количество операций переписывания данных из одной ячейки в другую, с помощью которых можно достичь описанных условий. Допустимо, что относительный порядок ячеек в памяти для каждого из процессов изменится после дефрагментации, но относительный порядок самих процессов должен остаться без изменений. Это значит, что если все ячейки, принадлежащие процессу *i*, находились в памяти раньше всех ячеек процесса *j*, то и после перемещений это условие должно выполняться. Считайте, что номера всех процессов уникальны, хотя бы одна ячейка памяти занята каким-либо процессом. Input Specification: В первой строке входных данных записано число *n* (1<=≤<=*n*<=≤<=200<=000) — количество ячеек в памяти компьютера. Во второй строке входных данных следуют *n* целых чисел *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*), где *a**i* равно либо 0 (это означает, что *i*-я ячейка памяти свободна), либо номеру процесса, которому принадлежит *i*-я ячейка памяти. Гарантируется, что хотя бы одно значение *a**i* не равно 0. Процессы пронумерованы целыми числами от 1 до *n* в произвольном порядке. При этом процессы не обязательно пронумерованы последовательными числами. Output Specification: Выведите одно целое число — минимальное количество операций, которое нужно сделать для дефрагментации памяти. Demo Input: ['4\n0 2 2 1\n', '8\n0 8 8 8 0 4 4 2\n'] Demo Output: ['2\n', '4\n'] Note: В первом тестовом примере достаточно двух операций: 1. Переписать данные из третьей ячейки в первую. После этого память компьютера примет вид: 2 2 0 1. 1. Переписать данные из четвертой ячейки в третью. После этого память компьютера примет вид: 2 2 1 0.
1,085
Title: Minimum Binary Number Time Limit: None seconds Memory Limit: None megabytes Problem Description: String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string *s*. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" "110"); 1. replace "11" with "1" (for example, "110" "10"). Let *val*(*s*) be such a number that *s* is its binary representation. Correct string *a* is less than some other correct string *b* iff *val*(*a*)<=&lt;<=*val*(*b*). Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all). Input Specification: The first line contains integer number *n* (1<=≤<=*n*<=≤<=100) — the length of string *s*. The second line contains the string *s* consisting of characters "0" and "1". It is guaranteed that the string *s* is correct. Output Specification: Print one string — the minimum correct string that you can obtain from the given one. Demo Input: ['4\n1001\n', '1\n1\n'] Demo Output: ['100\n', '1\n'] Note: In the first example you can obtain the answer by the following sequence of operations: "1001" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "1010" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "1100" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "100". In the second example you can't obtain smaller answer no matter what operations you use.
1,086
Title: Red and Blue Balls Time Limit: None seconds Memory Limit: None megabytes Problem Description: User ainta has a stack of *n* red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack. - While the top ball inside the stack is red, pop the ball from the top of the stack. - Then replace the blue ball on the top with a red ball. - And finally push some blue balls to the stack until the stack has total of *n* balls inside. If there are no blue balls inside the stack, ainta can't apply this operation. Given the initial state of the stack, ainta wants to know the maximum number of operations he can repeatedly apply. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=50) — the number of balls inside the stack. The second line contains a string *s* (|*s*|<==<=*n*) describing the initial state of the stack. The *i*-th character of the string *s* denotes the color of the *i*-th ball (we'll number the balls from top to bottom of the stack). If the character is "R", the color is red. If the character is "B", the color is blue. Output Specification: Print the maximum number of operations ainta can repeatedly apply. 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: ['3\nRBR\n', '4\nRBBR\n', '5\nRBBRR\n'] Demo Output: ['2\n', '6\n', '6\n'] Note: The first example is depicted below. The explanation how user ainta applies the first operation. He pops out one red ball, changes the color of the ball in the middle from blue to red, and pushes one blue ball. The explanation how user ainta applies the second operation. He will not pop out red balls, he simply changes the color of the ball on the top from blue to red. From now on, ainta can't apply any operation because there are no blue balls inside the stack. ainta applied two operations, so the answer is 2. The second example is depicted below. The blue arrow denotes a single operation.
1,087
Title: Color the Carpet Time Limit: None seconds Memory Limit: None megabytes Problem Description: Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height *h* and width *w*. Then the grid is divided into *h*<=×<=*w* squares. Alice is going to assign one of *k* different colors to each square. The colors are numbered from 1 to *k*. She may choose not to use all of the colors. However, there are some restrictions. For every two adjacent squares (squares that shares an edge) *x* and *y*, there is a color constraint in one of the forms: - *color*(*x*)<==<=*color*(*y*), or - *color*(*x*)<=≠<=*color*(*y*). Example of the color constraints: Ideally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least of the color constraints are satisfied. If she has 4 colors she can color the carpet in the following way: And she is happy because of the color constraints are satisfied, and . Your task is to help her color the carpet. Input Specification: The first line contains three integers *h*,<=*w*,<=*k* (2<=≤<=*h*,<=*w*<=≤<=1000,<=1<=≤<=*k*<=≤<=*w*·*h*). The next 2*h*<=-<=1 lines describe the color constraints from top to bottom, left to right. They contain *w*<=-<=1,<=*w*,<=*w*<=-<=1,<=*w*,<=...,<=*w*<=-<=1 characters respectively. Each color constraint is represented by a character "E" or "N", where "E" means "<==<=" and "N" means "<=≠<=". The color constraints listed in the order they are depicted on the picture. Output Specification: If there is a coloring that satisfies at least of the color constraints, print "YES" (without quotes) in the first line. In each of the next *h* lines, print *w* integers describing the coloring. Otherwise, print "NO" (without quotes). Demo Input: ['3 4 4\nENE\nNNEE\nNEE\nENEN\nENN\n'] Demo Output: ['YES\n1 1 2 2\n3 4 1 1\n3 3 2 4'] Note: none
1,088
Title: Random Teams Time Limit: None seconds Memory Limit: None megabytes Problem Description: *n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input Specification: The only line of input contains two integers *n* and *m*, separated by a single space (1<=≤<=*m*<=≤<=*n*<=≤<=109) — the number of participants and the number of teams respectively. Output Specification: The only line of the output should contain two integers *k**min* and *k**max* — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Demo Input: ['5 1\n', '3 2\n', '6 3\n'] Demo Output: ['10 10\n', '1 1\n', '3 6\n'] Note: In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people.
1,089
Title: Pyramids Time Limit: None seconds Memory Limit: None megabytes Problem Description: IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal. The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. Input Specification: The only line of the input contains three integers *l*3,<=*l*4,<=*l*5 (1<=≤<=*l*3,<=*l*4,<=*l*5<=≤<=1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly. Output Specification: Output one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10<=-<=9. Demo Input: ['2 5 3\n'] Demo Output: ['38.546168065709'] Note: none
1,090
Title: Word Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word. Input Specification: The first line contains a word *s* — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100. Output Specification: Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one. Demo Input: ['HoUse\n', 'ViP\n', 'maTRIx\n'] Demo Output: ['house\n', 'VIP\n', 'matrix\n'] Note: none
1,091
Title: Crazy Town Time Limit: None seconds Memory Limit: None megabytes Problem Description: Crazy Town is a plane on which there are *n* infinite line roads. Each road is defined by the equation *a**i**x*<=+<=*b**i**y*<=+<=*c**i*<==<=0, where *a**i* and *b**i* are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input Specification: The first line contains two space-separated integers *x*1, *y*1 (<=-<=106<=≤<=*x*1,<=*y*1<=≤<=106) — the coordinates of your home. The second line contains two integers separated by a space *x*2, *y*2 (<=-<=106<=≤<=*x*2,<=*y*2<=≤<=106) — the coordinates of the university you are studying at. The third line contains an integer *n* (1<=≤<=*n*<=≤<=300) — the number of roads in the city. The following *n* lines contain 3 space-separated integers (<=-<=106<=≤<=*a**i*,<=*b**i*,<=*c**i*<=≤<=106; |*a**i*|<=+<=|*b**i*|<=&gt;<=0) — the coefficients of the line *a**i**x*<=+<=*b**i**y*<=+<=*c**i*<==<=0, defining the *i*-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Specification: Output the answer to the problem. Demo Input: ['1 1\n-1 -1\n2\n0 1 0\n1 0 0\n', '1 1\n-1 -1\n3\n1 0 0\n0 1 0\n1 1 -3\n'] Demo Output: ['2\n', '2\n'] Note: Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):
1,092
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array *a*1,<=*a*2,<=...,<=*a**n* consisting of *n* integers, and an integer *k*. You have to split the array into exactly *k* non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the *k* obtained minimums. What is the maximum possible integer you can get? Definitions of subsegment and array splitting are given in notes. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=<=105) — the size of the array *a* and the number of subsegments you have to split the array to. The second line contains *n* integers *a*1,<=<=*a*2,<=<=...,<=<=*a**n* (<=-<=109<=<=≤<=<=*a**i*<=≤<=<=109). Output Specification: Print single integer — the maximum possible integer you can get if you split the array into *k* non-empty subsegments and take maximum of minimums on the subsegments. Demo Input: ['5 2\n1 2 3 4 5\n', '5 1\n-4 -5 -3 -2 -1\n'] Demo Output: ['5\n', '-5\n'] Note: A subsegment [*l*,  *r*] (*l* ≤ *r*) of array *a* is the sequence *a*<sub class="lower-index">*l*</sub>,  *a*<sub class="lower-index">*l* + 1</sub>,  ...,  *a*<sub class="lower-index">*r*</sub>. Splitting of array *a* of *n* elements into *k* subsegments [*l*<sub class="lower-index">1</sub>, *r*<sub class="lower-index">1</sub>], [*l*<sub class="lower-index">2</sub>, *r*<sub class="lower-index">2</sub>], ..., [*l*<sub class="lower-index">*k*</sub>, *r*<sub class="lower-index">*k*</sub>] (*l*<sub class="lower-index">1</sub> = 1, *r*<sub class="lower-index">*k*</sub> = *n*, *l*<sub class="lower-index">*i*</sub> = *r*<sub class="lower-index">*i* - 1</sub> + 1 for all *i* &gt; 1) is *k* sequences (*a*<sub class="lower-index">*l*<sub class="lower-index">1</sub></sub>, ..., *a*<sub class="lower-index">*r*<sub class="lower-index">1</sub></sub>), ..., (*a*<sub class="lower-index">*l*<sub class="lower-index">*k*</sub></sub>, ..., *a*<sub class="lower-index">*r*<sub class="lower-index">*k*</sub></sub>). In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are *min*(1, 2, 3, 4) = 1 and *min*(5) = 5. The resulting maximum is *max*(1, 5) = 5. It is obvious that you can't reach greater result. In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is *min*( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.
1,093
Title: Ann and Books Time Limit: None seconds Memory Limit: None megabytes Problem Description: In Ann's favorite book shop are as many as *n* books on math and economics. Books are numbered from 1 to *n*. Each of them contains non-negative number of problems. Today there is a sale: any subsegment of a segment from *l* to *r* can be bought at a fixed price. Ann decided that she wants to buy such non-empty subsegment that the sale operates on it and the number of math problems is greater than the number of economics problems exactly by *k*. Note that *k* may be positive, negative or zero. Unfortunately, Ann is not sure on which segment the sale operates, but she has *q* assumptions. For each of them she wants to know the number of options to buy a subsegment satisfying the condition (because the time she spends on choosing depends on that). Currently Ann is too busy solving other problems, she asks you for help. For each her assumption determine the number of subsegments of the given segment such that the number of math problems is greaten than the number of economics problems on that subsegment exactly by *k*. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000, <=-<=109<=≤<=*k*<=≤<=109) — the number of books and the needed difference between the number of math problems and the number of economics problems. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=2), where *t**i* is 1 if the *i*-th book is on math or 2 if the *i*-th is on economics. The third line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109), where *a**i* is the number of problems in the *i*-th book. The fourth line contains a single integer *q* (1<=≤<=*q*<=≤<=100<=000) — the number of assumptions. Each of the next *q* lines contains two integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*) describing the *i*-th Ann's assumption. Output Specification: Print *q* lines, in the *i*-th of them print the number of subsegments for the *i*-th Ann's assumption. Demo Input: ['4 1\n1 1 1 2\n1 1 1 1\n4\n1 2\n1 3\n1 4\n3 4\n', '4 0\n1 2 1 2\n0 0 0 0\n1\n1 4\n'] Demo Output: ['2\n3\n4\n1\n', '10\n'] Note: In the first sample Ann can buy subsegments [1;1], [2;2], [3;3], [2;4] if they fall into the sales segment, because the number of math problems is greater by 1 on them that the number of economics problems. So we should count for each assumption the number of these subsegments that are subsegments of the given segment. Segments [1;1] and [2;2] are subsegments of [1;2]. Segments [1;1], [2;2] and [3;3] are subsegments of [1;3]. Segments [1;1], [2;2], [3;3], [2;4] are subsegments of [1;4]. Segment [3;3] is subsegment of [3;4].
1,094
Title: Ilya and Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve. He's got a square 2*n*<=×<=2*n*-sized matrix and 4*n* integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum. The beauty of a 2*n*<=×<=2*n*-sized matrix is an integer, obtained by the following algorithm: 1. Find the maximum element in the matrix. Let's denote it as *m*. 1. If *n*<==<=0, then the beauty of the matrix equals *m*. Otherwise, a matrix can be split into 4 non-intersecting 2*n*<=-<=1<=×<=2*n*<=-<=1-sized submatrices, then the beauty of the matrix equals the sum of number *m* and other four beauties of the described submatrices. As you can see, the algorithm is recursive. Help Ilya, solve the problem and print the resulting maximum beauty of the matrix. Input Specification: The first line contains integer 4*n* (1<=≤<=4*n*<=≤<=2·106). The next line contains 4*n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the numbers you need to arrange in the 2*n*<=×<=2*n*-sized matrix. Output Specification: On a single line print the maximum value of the beauty of the described matrix. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['1\n13\n', '4\n1 2 3 4\n'] Demo Output: ['13\n', '14\n'] Note: Consider the second sample. You need to arrange the numbers in the matrix as follows: Then the beauty of the matrix will equal: 4 + 1 + 2 + 3 + 4 = 14.
1,095
Title: DZY Loves Games Time Limit: None seconds Memory Limit: None megabytes Problem Description: Today DZY begins to play an old game. In this game, he is in a big maze with *n* rooms connected by *m* corridors (each corridor allows to move in both directions). You can assume that all the rooms are connected with corridors directly or indirectly. DZY has got lost in the maze. Currently he is in the first room and has *k* lives. He will act like the follows: - Firstly he will randomly pick one of the corridors going from his current room. Each outgoing corridor has the same probability to be picked. - Then he will go through the corridor and then the process repeats. There are some rooms which have traps in them. The first room definitely has no trap, the *n*-th room definitely has a trap. Each time DZY enters one of these rooms, he will lost one life. Now, DZY knows that if he enters the *n*-th room with exactly 2 lives, firstly he will lost one live, but then he will open a bonus round. He wants to know the probability for him to open the bonus round. Please, help him. Input Specification: The first line contains three integers *n*,<=*m*,<=*k* (2<=≤<=*n*<=≤<=500; 1<=≤<=*m*<=≤<=105; 2<=≤<=*k*<=≤<=109). The second line contains *n* integers, each of them is either 0 or 1. If the *i*-th number is 1, then the *i*-th room has a trap, otherwise it has not a trap. Please note, that the number of rooms with a trap is no more than 101. It is guaranteed that the first room has no trap, and the *n*-th room has a trap. Then *m* lines follows. Each of them contains two integers *u**i*,<=*v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*; *u**i*<=≠<=*v**i*), meaning that current corridor connects two rooms *u**i* and *v**i*. It is guaranteed that the corridor system is connected. Output Specification: Print the only real number — the probability for DZY to open the bonus round. The answer will be considered correct if its relative or absolute error doesn't exceed 10<=-<=4. Demo Input: ['5 5 3\n0 0 1 0 1\n1 2\n2 3\n3 4\n4 5\n1 2\n', '3 2 2\n0 1 1\n1 2\n2 3\n', '2 1 3\n0 1\n1 2\n'] Demo Output: ['0.25000000\n', '-0.00000000\n', '1.00000000\n'] Note: none
1,096
Title: Accounting Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income *A* of his kingdom during 0-th year is known, as well as the total income *B* during *n*-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient *X* — the coefficient of income growth during one year. This coefficient should satisfy the equation: Surely, the king is not going to do this job by himself, and demands you to find such number *X*. It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient *X* must be integers. The number *X* may be zero or negative. Input Specification: The input contains three integers *A*, *B*, *n* (|*A*|,<=|*B*|<=≤<=1000, 1<=≤<=*n*<=≤<=10). Output Specification: Output the required integer coefficient *X*, or «No solution», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them. Demo Input: ['2 18 2\n', '-1 8 3\n', '0 0 10\n', '1 16 5\n'] Demo Output: ['3', '-2', '5', 'No solution'] Note: none
1,097
Title: Ivan the Fool VS Gorynych the Dragon Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once upon a time in a kingdom far, far away… Okay, let’s start at the point where Ivan the Fool met Gorynych the Dragon. Ivan took out his magic sword and the battle began. First Gorynych had *h* heads and *t* tails. With each strike of the sword Ivan can either cut off several heads (from 1 to *n*, but not more than Gorynych has at the moment), or several tails (from 1 to *m*, but not more than Gorynych has at the moment). At the same time, horrible though it seems, Gorynych the Dragon can also grow new heads and tails. And the number of growing heads and tails is determined uniquely by the number of heads or tails cut by the current strike. When the total number of heads and tails exceeds *R*, Gorynych the Dragon strikes its final blow and destroys Ivan the Fool. That’s why Ivan aims to cut off all the dragon’s heads and tails as quickly as possible and win. The events can also develop in a third way: neither of the opponents can win over the other one and they will continue fighting forever. The tale goes like this; easy to say, hard to do. Your task is to write a program that will determine the battle’s outcome. Consider that Ivan strikes consecutively. After each blow Gorynych grows a number of new heads and tails depending on the number of cut ones. Gorynych the Dragon is defeated if after the blow he loses all his heads and tails and can’t grow new ones. Ivan fights in the optimal way (fools are lucky), i.e. - if Ivan can win, he wins having struck the least number of blows; - if it is impossible to defeat Gorynych, but is possible to resist him for an infinitely long period of time, then that’s the strategy Ivan chooses; - if Gorynych wins in any case, Ivan aims to resist him for as long as possible. Input Specification: The first line contains three integers *h*, *t* and *R* (0<=≤<=*h*,<=*t*,<=*R*<=≤<=200, 0<=&lt;<=*h*<=+<=*t*<=≤<=*R*) which represent the initial numbers of Gorynych’s heads and tails and the largest total number of heads and tails with which Gorynych the Dragon does not yet attack. The next line contains integer *n* (1<=≤<=*n*<=≤<=200). The next *n* contain pairs of non-negative numbers "*h**i* *t**i*" which represent the number of heads and the number of tails correspondingly, that will grow if Gorynych has *i* heads (1<=≤<=*i*<=≤<=*n*) cut. The next line contains an integer *m* (1<=≤<=*m*<=≤<=200) and then — the description of Gorynych’s behavior when his tails are cut off in the format identical to the one described above. All the numbers in the input file do not exceed 200. Output Specification: Print "Ivan" (without quotes) in the first line if Ivan wins, or "Zmey" (that means a dragon in Russian) if Gorynych the Dragon wins. In the second line print a single integer which represents the number of blows Ivan makes. If the battle will continue forever, print in the first line "Draw". Demo Input: ['2 2 4\n2\n1 0\n0 1\n3\n0 1\n0 1\n0 0\n', '2 2 4\n1\n0 1\n1\n1 0\n', '2 2 5\n1\n1 1\n1\n3 0\n'] Demo Output: ['Ivan\n2\n', 'Draw\n', 'Zmey\n2\n'] Note: none
1,098
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with *n* vertices and *m* edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops. Input Specification: The first line contains two integers — the number of vertices *n* and the number of edges *m* of the graph (1<=≤<=*n*<=≤<=100, 0<=≤<=*m*<=≤<=). Each of the following *m* lines contains a pair of integers *x* and *y*, that show that an edge exists between vertices *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself. Output Specification: Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is. Demo Input: ['6 6\n6 3\n6 4\n5 1\n2 5\n1 4\n5 4\n', '6 5\n5 6\n4 6\n3 1\n5 1\n1 2\n'] Demo Output: ['FHTAGN!', 'NO'] Note: Let us denote as a simple cycle a set of *v* vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., *v* - 1 and *v*, *v* and 1. A tree is a connected undirected graph consisting of *n* vertices and *n* - 1 edges (*n* &gt; 0). A rooted tree is a tree where one vertex is selected to be the root.
1,099