task
stringlengths 0
154k
| __index_level_0__
int64 0
39.2k
|
|---|---|
Title: ...Wait for it...
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Barney is searching for his dream girl. He lives in NYC. NYC has *n* junctions numbered from 1 to *n* and *n*<=-<=1 roads connecting them. We will consider the NYC as a rooted tree with root being junction 1. *m* girls live in NYC, *i*-th of them lives along junction *c**i* and her weight initially equals *i* pounds.
Barney consider a girl *x* to be better than a girl *y* if and only if: girl *x* has weight strictly less than girl *y* or girl *x* and girl *y* have equal weights and index of girl *x* living junction index is strictly less than girl *y* living junction index, i.e. *c**x*<=<<=*c**y*. Thus for any two girls one of them is always better than another one.
For the next *q* days, one event happens each day. There are two types of events:
1. Barney goes from junction *v* to junction *u*. As a result he picks at most *k* best girls he still have not invited from junctions on his way and invites them to his house to test if one of them is his dream girl. If there are less than *k* not invited girls on his path, he invites all of them.1. Girls living along junctions in subtree of junction *v* (including *v* itself) put on some weight. As result, their weights increase by *k* pounds.
Your task is for each event of first type tell Barney the indices of girls he will invite to his home in this event.
Input Specification:
The first line of input contains three integers *n*, *m* and *q* (1<=β€<=*n*,<=*m*,<=*q*<=β€<=105)Β β the number of junctions in NYC, the number of girls living in NYC and the number of events respectively.
The next *n*<=-<=1 lines describes the roads. Each line contains two integers *v* and *u* (1<=β€<=*v*,<=*u*<=β€<=*n*,<=*v*<=β <=*u*) meaning that there is a road connecting junctions *v* and *u* .
The next line contains *m* integers *c*1,<=*c*2,<=...,<=*c**m* (1<=β€<=*c**i*<=β€<=*n*)Β β the girl's living junctions.
The next *q* lines describe the events in chronological order. Each line starts with an integer *t* (1<=β€<=*t*<=β€<=2)Β β type of the event .
If *t*<==<=1 then the line describes event of first type three integers *v*, *u* and *k* (1<=β€<=*v*,<=*u*,<=*k*<=β€<=*n*) followΒ β the endpoints of Barney's path and the number of girls that he will invite at most.
Otherwise the line describes event of second type and two integers *v* and *k* (1<=β€<=*v*<=β€<=*n*,<=1<=β€<=*k*<=β€<=109) followΒ β the root of the subtree and value by which all the girls' weights in the subtree should increase.
Output Specification:
For each event of the first type, print number *t* and then *t* integers *g*1,<=*g*2,<=...,<=*g**t* in one line, meaning that in this event Barney will invite *t* girls whose indices are *g*1,<=...,<=*g**t* in the order from the best to the worst according to Barney's considerations.
Demo Input:
['5 7 11\n3 5\n2 3\n4 3\n1 4\n4 1 4 5 4 1 4\n2 4 3\n1 2 1 2\n1 4 2 1\n2 2 10\n2 1 10\n1 2 4 1\n1 2 3 4\n2 5 2\n2 4 9\n1 3 5 2\n1 1 2 3\n']
Demo Output:
['2 2 1 \n1 3 \n1 5 \n0 \n1 4 \n2 6 7 \n']
Note:
For the first sample case:
Description of events:
1. Weights of girls in subtree of junction 4 increase by 3. These girls have IDs: 1,β3,β5,β4,β7. 1. Barney goes from junction 2 to 1. Girls on his way have IDs 1,β2,β3,β5,β6,β7 with weights 4,β2,β6,β8,β6,β10 respectively. So, he invites girls 2 and 1. 1. Barney goes from junction 4 to junction 2. Girls on his way has IDs 3,β5,β7 with weights 6,β8,β10 respectively. So he invites girl 3. 1. Weight of girls in subtree of junction 2 increase by 10. There are no not invited girls, so nothing happens. 1. Weight of girls in subtree of junction 1 increase by 10. These girls (all girls left) have IDs: 4,β5,β6,β7. 1. Barney goes from junction 2 to junction 4. Girls on his way has IDs 5,β7 with weights 18,β20 respectively. So he invites girl 5. 1. Barney goes from junction 2 to junction 3. There is no girl on his way. 1. Weight of girls in subtree of junction 5 increase by 2. The only girl there is girl with ID 4. 1. Weight of girls in subtree of junction 4 increase by 9. These girls have IDs: 4,β6,β7. 1. Barney goes from junction 3 to junction 5. Only girl on his way is girl with ID 4. 1. Barney goes from junction 1 to junction 2. Girls on his way has IDs 6,β7 with weights 16,β29 respectively.
| 500
|
Title: Luba And The Ticket
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.
The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.
Input Specification:
You are given a string consisting of 6 characters (all characters are digits from 0 to 9) β this string denotes Luba's ticket. The ticket can start with the digit 0.
Output Specification:
Print one number β the minimum possible number of digits Luba needs to replace to make the ticket lucky.
Demo Input:
['000000\n', '123456\n', '111000\n']
Demo Output:
['0\n', '2\n', '1\n']
Note:
In the first example the ticket is already lucky, so the answer is 0.
In the second example Luba can replace 4 and 5 with zeroes, and the ticket will become lucky. It's easy to see that at least two replacements are required.
In the third example Luba can replace any zero with 3. It's easy to see that at least one replacement is required.
| 501
|
Title: Simple XML
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's define a string <x> as an opening tag, where *x* is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where *x* is the same letter.
Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair.
Let's define the notion of a XML-text:
- an empty string is a XML-text - if *s* is a XML-text, then *s*'=<a>+*s*+</a> also is a XML-text, where *a* is any small Latin letter - if *s*1, *s*2 are XML-texts, then *s*1+*s*2 also is a XML-text
You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form:
- each tag (opening and closing) is located on a single line - print before the tag 2<=*<=*h* spaces, where *h* is the level of the tag's nestedness.
Input Specification:
The input data consists on the only non-empty string β the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces.
Output Specification:
Print the given XML-text according to the above-given rules.
Demo Input:
['<a><b><c></c></b></a>\n', '<a><b></b><d><c></c></d></a>\n']
Demo Output:
['<a>\n <b>\n <c>\n </c>\n </b>\n</a>\n', '<a>\n <b>\n </b>\n <d>\n <c>\n </c>\n </d>\n</a>\n']
Note:
none
| 502
|
Title: Sleuth
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the questionβs last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. Thatβs why Vasyaβs friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
Input Specification:
The single line contains a question represented by a non-empty line consisting of large and small Latin letters, spaces and a question mark. The line length does not exceed 100. It is guaranteed that the question mark occurs exactly once in the line β as the last symbol and that the line contains at least one letter.
Output Specification:
Print answer for the question in a single line: YES if the answer is "Yes", NO if the answer is "No".
Remember that in the reply to the question the last letter, not the last character counts. I. e. the spaces and the question mark do not count as letters.
Demo Input:
['Is it a melon?\n', 'Is it an apple?\n', 'Is it a banana ?\n', 'Is it an apple and a banana simultaneouSLY?\n']
Demo Output:
['NO\n', 'YES\n', 'YES\n', 'YES\n']
Note:
none
| 503
|
Title: Igor In the Museum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Igor is in the museum and he wants to see as many pictures as possible.
Museum can be represented as a rectangular field of *n*<=Γ<=*m* cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.
At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.
For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.
Input Specification:
First line of the input contains three integers *n*, *m* and *k* (3<=β€<=*n*,<=*m*<=β€<=1000,<=1<=β€<=*k*<=β€<=*min*(*n*Β·*m*,<=100<=000))Β β the museum dimensions and the number of starting positions to process.
Each of the next *n* lines contains *m* symbols '.', '*' β the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.
Each of the last *k* lines contains two integers *x* and *y* (1<=β€<=*x*<=β€<=*n*,<=1<=β€<=*y*<=β€<=*m*)Β β the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns β from left to right. It is guaranteed that all starting positions are empty cells.
Output Specification:
Print *k* integersΒ β the maximum number of pictures, that Igor can see if he starts in corresponding position.
Demo Input:
['5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3\n', '4 4 1\n****\n*..*\n*.**\n****\n3 2\n']
Demo Output:
['6\n4\n10\n', '8\n']
Note:
none
| 504
|
Title: Santa Claus and Robot
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of *m* points *p*1,<=*p*2,<=...,<=*p**m* with integer coordinates, do the following: denote its initial location by *p*0. First, the robot will move from *p*0 to *p*1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches *p*1, it'll move to *p*2, again, choosing one of the shortest ways, then to *p*3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.
While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.
Input Specification:
The first line of input contains the only positive integer *n* (1<=β€<=*n*<=β€<=2Β·105) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of *n* letters, each being equal either L, or R, or U, or D. *k*-th letter stands for the direction which Robot traveled the *k*-th unit segment in: L means that it moved to the left, RΒ β to the right, UΒ β to the top and DΒ β to the bottom. Have a look at the illustrations for better explanation.
Output Specification:
The only line of input should contain the minimum possible length of the sequence.
Demo Input:
['4\nRURD\n', '6\nRRULDD\n', '26\nRRRULURURUULULLLDLDDRDRDLD\n', '3\nRLL\n', '4\nLRLR\n']
Demo Output:
['2\n', '2\n', '7\n', '2\n', '4\n']
Note:
The illustrations to the first three tests are given below.
<img class="tex-graphics" src="https://espresso.codeforces.com/832fb8f97a482be815e0f87edde26c9791a0d330.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img class="tex-graphics" src="https://espresso.codeforces.com/119a8ba68772b2c2bf76f2acdc58027f6c5cde1f.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img class="tex-graphics" src="https://espresso.codeforces.com/c7b4534f24cbad48148bcba24bc44f37bf7a2dbf.png" style="max-width: 100.0%;max-height: 100.0%;"/>
The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.
| 505
|
Title: Valera and Contest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of *n* students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.
After the contest was over, Valera was interested in results. He found out that:
- each student in the team scored at least *l* points and at most *r* points; - in total, all members of the team scored exactly *s**all* points; - the total score of the *k* members of the team who scored the most points is equal to exactly *s**k*; more formally, if *a*1,<=*a*2,<=...,<=*a**n* is the sequence of points earned by the team of students in the non-increasing order (*a*1<=β₯<=*a*2<=β₯<=...<=β₯<=*a**n*), then *s**k*<==<=*a*1<=+<=*a*2<=+<=...<=+<=*a**k*.
However, Valera did not find out exactly how many points each of *n* students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
Input Specification:
The first line of the input contains exactly six integers *n*,<=*k*,<=*l*,<=*r*,<=*s**all*,<=*s**k* (1<=β€<=*n*,<=*k*,<=*l*,<=*r*<=β€<=1000; *l*<=β€<=*r*; *k*<=β€<=*n*; 1<=β€<=*s**k*<=β€<=*s**all*<=β€<=106).
It's guaranteed that the input is such that the answer exists.
Output Specification:
Print exactly *n* integers *a*1,<=*a*2,<=...,<=*a**n* β the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
Demo Input:
['5 3 1 3 13 9\n', '5 3 1 3 15 9\n']
Demo Output:
['2 3 2 3 3 ', '3 3 3 3 3 ']
Note:
none
| 506
|
Title: Vanya and Scales
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya has a scales for weighing loads and weights of masses *w*0,<=*w*1,<=*w*2,<=...,<=*w*100 grams where *w* is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass *m* using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass *m* and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.
Input Specification:
The first line contains two integers *w*,<=*m* (2<=β€<=*w*<=β€<=109, 1<=β€<=*m*<=β€<=109) β the number defining the masses of the weights and the mass of the item.
Output Specification:
Print word 'YES' if the item can be weighted and 'NO' if it cannot.
Demo Input:
['3 7\n', '100 99\n', '100 50\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7β+β3β=β9β+β1.
Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.
Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input.
| 507
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted.
The battery of the newest device allows to highlight at most *n* sections on the display.
Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.
Input Specification:
The first line contains the integer *n* (2<=β€<=*n*<=β€<=100<=000) β the maximum number of sections which can be highlighted on the display.
Output Specification:
Print the maximum integer which can be shown on the display of Stepan's newest device.
Demo Input:
['2\n', '3\n']
Demo Output:
['1\n', '7\n']
Note:
none
| 508
|
Title: Credit Card
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recenlty Luba got a credit card and started to use it. Let's consider *n* consecutive days Luba uses the card.
She starts with 0 money on her account.
In the evening of *i*-th day a transaction *a**i* occurs. If *a**i*<=><=0, then *a**i* bourles are deposited to Luba's account. If *a**i*<=<<=0, then *a**i* bourles are withdrawn. And if *a**i*<==<=0, then the amount of money on Luba's account is checked.
In the morning of any of *n* days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed *d*.
It can happen that the amount of money goes greater than *d* by some transaction in the evening. In this case answer will be Β«-1Β».
Luba must not exceed this limit, and also she wants that every day her account is checked (the days when *a**i*<==<=0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
Input Specification:
The first line contains two integers *n*, *d* (1<=β€<=*n*<=β€<=105, 1<=β€<=*d*<=β€<=109) βthe number of days and the money limitation.
The second line contains *n* integer numbers *a*1,<=*a*2,<=... *a**n* (<=-<=104<=β€<=*a**i*<=β€<=104), where *a**i* represents the transaction in *i*-th day.
Output Specification:
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
Demo Input:
['5 10\n-1 5 0 -5 3\n', '3 4\n-10 0 20\n', '5 10\n-5 0 10 -11 0\n']
Demo Output:
['0\n', '-1\n', '2\n']
Note:
none
| 509
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph *G*. It is required to find a subset of vertices *C* of the maximum size such that any two of them are connected by an edge in graph *G*. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider *n* distinct points on a line. Let the *i*-th point have the coordinate *x**i* and weight *w**i*. Let's form graph *G*, whose vertices are these points and edges connect exactly the pairs of points (*i*,<=*j*), such that the distance between them is not less than the sum of their weights, or more formally: |*x**i*<=-<=*x**j*|<=β₯<=*w**i*<=+<=*w**j*.
Find the size of the maximum clique in such graph.
Input Specification:
The first line contains the integer *n* (1<=β€<=*n*<=β€<=200<=000) β the number of points.
Each of the next *n* lines contains two numbers *x**i*, *w**i* (0<=β€<=*x**i*<=β€<=109,<=1<=β€<=*w**i*<=β€<=109) β the coordinate and the weight of a point. All *x**i* are different.
Output Specification:
Print a single number β the number of vertexes in the maximum clique of the given graph.
Demo Input:
['4\n2 3\n3 1\n6 1\n0 2\n']
Demo Output:
['3\n']
Note:
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
| 510
|
Title: Cycle In Maze
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Robot is in a rectangular maze of size *n*<=Γ<=*m*. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly *k*, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=β€<=*n*,<=*m*<=β€<=1000, 1<=β€<=*k*<=β€<=106) β the size of the maze and the length of the cycle.
Each of the following *n* lines contains *m* symbols β the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output Specification:
Print the lexicographically minimum Robot's way with the length exactly *k*, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Demo Input:
['2 3 2\n.**\nX..\n', '5 6 14\n..***.\n*...X.\n..*...\n..*.**\n....*.\n', '3 3 4\n***\n*X*\n***\n']
Demo Output:
['RL\n', 'DLDDLLLRRRUURU\n', 'IMPOSSIBLE\n']
Note:
In the first sample two cyclic ways for the Robot with the length 2 exist β "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.
| 511
|
Title: EKG
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input Specification:
The first line contains two integers *n* (1<=β€<=*n*<=β€<=103) and *x* (1<=β€<=*x*<=β€<=*n*) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to *n*.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=*n*) β the number of the beaver followed by the *i*-th beaver. If *a**i*<==<=0, then the *i*-th beaver doesn't know who is should be in front of him. It is guaranteed that values *a**i* are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
- It is guaranteed that the number of zero elements *a**i* doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
- The number of zero elements *a**i* is arbitrary.
Output Specification:
Print all possible positions of the Smart Beaver in the line in the increasing order.
Demo Input:
['6 1\n2 0 4 0 6 0\n', '6 2\n2 3 0 5 6 0\n', '4 1\n0 0 0 0\n', '6 2\n0 0 1 0 4 5\n']
Demo Output:
['2\n4\n6\n', '2\n5\n', '1\n2\n3\n4\n', '1\n3\n4\n6\n']
| 512
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions.
To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.
Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible.
Input Specification:
The first line contains an integer number *t* (1<=β€<=*t*<=β€<=50) β the number of plates.
*t* descriptions of plates follow. A description of each plate consists of four lines. Each line consists of a pair of integers numbers *x**i*,<=*y**i* (<=-<=108<=β€<=*x**i*,<=*y**i*<=β€<=108) β coordinates of the next bot. All bots are in different locations.
Note, though, the problem can include several records in one test, you can hack other people's submissions only with the test of one plate, i.e. parameter *t* in a hack test should be equal to 1.
Output Specification:
Print answers for all plates separately. First goes a single integer number in a separate line. If scientists have made an unfortunate mistake and nanobots are not able to form the desired square, print -1. Otherwise, print the minimum possible length of the longest bot's path.
If a solution exists, in the next four lines print two integer numbers β positions of each bot after moving. Print bots' positions in the order they are specified in the input data.
If there are multiple solution, you can print any of them.
Demo Input:
['2\n1 1\n1 -1\n-1 1\n-1 -1\n1 1\n2 2\n4 4\n6 6\n']
Demo Output:
['0\n1 1\n1 -1\n-1 1\n-1 -1\n-1\n']
Note:
none
| 513
|
Title: Expression Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A simplified arithmetic expression (SAE) is an arithmetic expression defined by the following grammar:
- <SAE> ::= <Number> | <SAE>+<SAE> | <SAE>*<SAE> | (<SAE>) - <Number> ::= <Digit> | <Digit><Number> - <Digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
In other words it's a correct arithmetic expression that is allowed to contain brackets, numbers (possibly with leading zeros), multiplications and additions. For example expressions "(0+01)", "0" and "1*(0)" are simplified arithmetic expressions, but expressions "2-1", "+1" and "1+2)" are not.
Given a string *s*1*s*2...*s*|*s*| that represents a SAE; *s**i* denotes the *i*-th character of the string which can be either a digit ('0'-'9'), a plus sign ('+'), a multiplication sign ('*'), an opening round bracket '(' or a closing round bracket ')'.
A part *s**l**s**l*<=+<=1...*s**r* of this string is called a sub-expression if and only if it is a SAE.
You task is to answer *m* queries, each of which is a pair of integers *l**i*, *r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=|*s*|). For each query determine whether the corresponding part of the given string is a sub-expression and in case it's a sub-expression calculate its value modulo 1000000007Β (109<=+<=7). The values should be calculated using standard operator priorities.
Input Specification:
The first line of the input contains non-empty string *s* (1<=β€<=|*s*|<=β€<=4Β·105) which represents a correct SAE. Each character of the string can be one of the following characters: '*', '+', '(', ')' or a digit ('0'-'9'). The expression might contain extra-huge numbers.
The second line contains an integer *m* (1<=β€<=*m*<=β€<=4Β·105) which is the number of queries. Each of the next *m* lines contains two space-separated integers *l**i*, *r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=|*s*|) β the *i*-th query.
Output Specification:
The *i*-th number of output should be the answer for the *i*-th query. If the *i*-th query corresponds to a valid sub-expression output the value of the sub-expression modulo 1000000007Β (109<=+<=7). Otherwise output -1 as an answer for the query. Print numbers on separate lines.
Demo Input:
['((1+2)*3+101*2)\n6\n8 14\n1 6\n2 10\n11 14\n5 5\n4 5\n', '(01)\n1\n1 4\n']
Demo Output:
['205\n-1\n10\n2\n2\n-1\n', '1\n']
Note:
none
| 514
|
Title: Supermarket
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $a$ yuan for $b$ kilos (You don't need to care about what "yuan" is), the same as $a/b$ yuan for a kilo.
Now imagine you'd like to buy $m$ kilos of apples. You've asked $n$ supermarkets and got the prices. Find the minimum cost for those apples.
You can assume that there are enough apples in all supermarkets.
Input Specification:
The first line contains two positive integers $n$ and $m$ ($1 \leq n \leq 5\,000$, $1 \leq m \leq 100$), denoting that there are $n$ supermarkets and you want to buy $m$ kilos of apples.
The following $n$ lines describe the information of the supermarkets. Each line contains two positive integers $a, b$ ($1 \leq a, b \leq 100$), denoting that in this supermarket, you are supposed to pay $a$ yuan for $b$ kilos of apples.
Output Specification:
The only line, denoting the minimum cost for $m$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $10^{-6}$.
Formally, let your answer be $x$, and the jury's answer be $y$. Your answer is considered correct if $\frac{|x - y|}{\max{(1, |y|)}} \le 10^{-6}$.
Demo Input:
['3 5\n1 2\n3 4\n1 3\n', '2 1\n99 100\n98 99\n']
Demo Output:
['1.66666667\n', '0.98989899\n']
Note:
In the first sample, you are supposed to buy $5$ kilos of apples in supermarket $3$. The cost is $5/3$ yuan.
In the second sample, you are supposed to buy $1$ kilo of apples in supermarket $2$. The cost is $98/99$ yuan.
| 515
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In some country live wizards. They love playing with numbers.
The blackboard has two numbers written on it β *a* and *b*. The order of the numbers is not important. Let's consider *a*<=β€<=*b* for the sake of definiteness. The players can cast one of the two spells in turns:
- Replace *b* with *b*<=-<=*a**k*. Number *k* can be chosen by the player, considering the limitations that *k*<=><=0 and *b*<=-<=*a**k*<=β₯<=0. Number *k* is chosen independently each time an active player casts a spell. - Replace *b* with *b*Β *mod*Β *a*.
If *a*<=><=*b*, similar moves are possible.
If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.
To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.
Input Specification:
The first line contains a single integer *t* β the number of input data sets (1<=β€<=*t*<=β€<=104). Each of the next *t* lines contains two integers *a*, *b* (0<=β€<=*a*,<=*b*<=β€<=1018). The numbers are separated by a space.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output Specification:
For any of the *t* input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input.
Demo Input:
['4\n10 21\n31 10\n0 1\n10 30\n']
Demo Output:
['First\nSecond\nSecond\nFirst\n']
Note:
In the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win.
In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win.
In the third sample, the first player has no moves.
In the fourth sample, the first player wins in one move, taking 30 modulo 10.
| 516
|
Title: Optimal Point
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.
Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed.
Mole wants to find an optimal point to watch roses, that is such point with integer coordinates that the maximum Manhattan distance to the rose is minimum possible.
As usual, he asks you to help.
Manhattan distance between points (*x*1,<=Β *y*1,<=Β *z*1) and (*x*2,<=Β *y*2,<=Β *z*2) is defined as |*x*1<=-<=*x*2|<=+<=|*y*1<=-<=*y*2|<=+<=|*z*1<=-<=*z*2|.
Input Specification:
The first line of the input contains an integer *t* *t* (1<=β€<=*t*<=β€<=100<=000)Β β the number of test cases. Then follow exactly *t* blocks, each containing the description of exactly one test.
The first line of each block contains an integer *n**i* (1<=β€<=*n**i*<=β€<=100<=000)Β β the number of roses in the test. Then follow *n**i* lines, containing three integers eachΒ β the coordinates of the corresponding rose. Note that two or more roses may share the same position.
It's guaranteed that the sum of all *n**i* doesn't exceed 100<=000 and all coordinates are not greater than 1018 by their absolute value.
Output Specification:
For each of *t* test cases print three integersΒ β the coordinates of the optimal point to watch roses. If there are many optimal answers, print any of them.
The coordinates of the optimal point may coincide with the coordinates of any rose.
Demo Input:
['1\n5\n0 0 4\n0 0 -4\n0 4 0\n4 0 0\n1 1 1\n', '2\n1\n3 5 9\n2\n3 5 9\n3 5 9\n']
Demo Output:
['0 0 0\n', '3 5 9\n3 5 9\n']
Note:
In the first sample, the maximum Manhattan distance from the point to the rose is equal to 4.
In the second sample, the maximum possible distance is 0. Note that the positions of the roses may coincide with each other and with the position of the optimal point.
| 517
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction.
A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input Specification:
The first line contains a single integer $n$ ($1 \le n \le 10^5$)Β β the number of queries.
Next $n$ lines contain queries, one per line. Each line contains three integers $p$, $q$, and $b$ ($0 \le p \le 10^{18}$, $1 \le q \le 10^{18}$, $2 \le b \le 10^{18}$). All numbers are given in notation with base $10$.
Output Specification:
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Demo Input:
['2\n6 12 10\n4 3 10\n', '4\n1 1 2\n9 36 2\n4 12 3\n3 5 4\n']
Demo Output:
['Finite\nInfinite\n', 'Finite\nFinite\nFinite\nInfinite\n']
Note:
$\frac{6}{12} = \frac{1}{2} = 0,5_{10}$
$\frac{4}{3} = 1,(3)_{10}$
$\frac{9}{36} = \frac{1}{4} = 0,01_2$
$\frac{4}{12} = \frac{1}{3} = 0,1_3$
| 518
|
Title: Ruminations on Ruminants
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kevin Sun is ruminating on the origin of cows while standing at the origin of the Cartesian plane. He notices *n* lines on the plane, each representable by an equation of the form *ax*<=+<=*by*<==<=*c*. He also observes that no two lines are parallel and that no three lines pass through the same point.
For each triple (*i*,<=*j*,<=*k*) such that 1<=β€<=*i*<=<<=*j*<=<<=*k*<=β€<=*n*, Kevin considers the triangle formed by the three lines . He calls a triangle original if the circumcircle of that triangle passes through the origin. Since Kevin believes that the circles of bovine life are tied directly to such triangles, he wants to know the number of original triangles formed by unordered triples of distinct lines.
Recall that the circumcircle of a triangle is the circle which passes through all the vertices of that triangle.
Input Specification:
The first line of the input contains a single integer *n* (3<=β€<=*n*<=β€<=2000), the number of lines.
The next *n* lines describe lines . The *i*-th of these lines contains three space-separated integers *a**i*,<=*b**i*,<=*c**i* (|*a**i*|,<=|*b**i*|,<=|*c**i*|<=β€<=10<=000,<=*a**i*2<=+<=*b**i*2<=><=0), representing the equation *a**i**x*<=+<=*b**i**y*<==<=*c**i* of line .
Output Specification:
Print a single integer, the number of triples (*i*,<=*j*,<=*k*) with *i*<=<<=*j*<=<<=*k* such that lines form an original triangle.
Demo Input:
['4\n1 0 0\n0 1 0\n1 1 -1\n1 -1 2\n', '3\n0 1 1\n1 1 2\n1 -1 -2\n']
Demo Output:
['2\n', '1\n']
Note:
Note that in the first sample, some of the lines pass through the origin.
In the second sample, there is exactly one triple of lines: *y*β=β1,β*x*β+β*y*β=β2,β*x*β-β*y*β=ββ-β2. The triangle they form has vertices (0,β2),β(1,β1),β(β-β1,β1). The circumcircle of this triangle has equation *x*<sup class="upper-index">2</sup>β+β(*y*β-β1)<sup class="upper-index">2</sup>β=β1. This indeed passes through (0,β0).
| 519
|
Title: Hit Ball
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When Valera was playing football on a stadium, it suddenly began to rain. Valera hid in the corridor under the grandstand not to get wet. However, the desire to play was so great that he decided to train his hitting the ball right in this corridor. Valera went back far enough, put the ball and hit it. The ball bounced off the walls, the ceiling and the floor corridor and finally hit the exit door. As the ball was wet, it left a spot on the door. Now Valera wants to know the coordinates for this spot.
Let's describe the event more formally. The ball will be considered a point in space. The door of the corridor will be considered a rectangle located on plane *xOz*, such that the lower left corner of the door is located at point (0,<=0,<=0), and the upper right corner is located at point (*a*,<=0,<=*b*) . The corridor will be considered as a rectangular parallelepiped, infinite in the direction of increasing coordinates of *y*. In this corridor the floor will be considered as plane *xOy*, and the ceiling as plane, parallel to *xOy* and passing through point (*a*,<=0,<=*b*). We will also assume that one of the walls is plane *yOz*, and the other wall is plane, parallel to *yOz* and passing through point (*a*,<=0,<=*b*).
We'll say that the ball hit the door when its coordinate *y* was equal to 0. Thus the coordinates of the spot are point (*x*0,<=0,<=*z*0), where 0<=β€<=*x*0<=β€<=*a*,<=0<=β€<=*z*0<=β€<=*b*. To hit the ball, Valera steps away from the door at distance *m* and puts the ball in the center of the corridor at point . After the hit the ball flies at speed (*v**x*,<=*v**y*,<=*v**z*). This means that if the ball has coordinates (*x*,<=*y*,<=*z*), then after one second it will have coordinates (*x*<=+<=*v**x*,<=*y*<=+<=*v**y*,<=*z*<=+<=*v**z*).
See image in notes for clarification.
When the ball collides with the ceiling, the floor or a wall of the corridor, it bounces off in accordance with the laws of reflection (the angle of incidence equals the angle of reflection). In the problem we consider the ideal physical model, so we can assume that there is no air resistance, friction force, or any loss of energy.
Input Specification:
The first line contains three space-separated integers *a*,<=*b*,<=*m* (1<=β€<=*a*,<=*b*,<=*m*<=β€<=100). The first two integers specify point (*a*,<=0,<=*b*), through which the ceiling and one of the corridor walls pass. The third integer is the distance at which Valera went away from the door.
The second line has three space-separated integers *v**x*,<=*v**y*,<=*v**z* (|*v**x*|,<=|*v**y*|,<=|*v**z*|<=β€<=100,<=*v**y*<=<<=0,<=*v**z*<=β₯<=0) β the speed of the ball after the hit.
It is guaranteed that the ball hits the door.
Output Specification:
Print two real numbers *x*0,<=*z*0 β the *x* and *z* coordinates of point (*x*0,<=0,<=*z*0), at which the ball hits the exit door. The answer will be considered correct, if its absolute or relative error does not exceed 10<=<=-<=6.
Demo Input:
['7 2 11\n3 -11 2\n', '7 2 11\n4 -3 3\n']
Demo Output:
['6.5000000000 2.0000000000\n', '4.1666666667 1.0000000000\n']
Note:
<img class="tex-graphics" src="https://espresso.codeforces.com/0b96c99a50a7ff8657d6301992a0fe440badfb7b.png" style="max-width: 100.0%;max-height: 100.0%;"/>
| 520
|
Title: Success Rate
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made *y* submissions, out of which *x* have been successful. Thus, your current success rate on Codeforces is equal to *x*<=/<=*y*.
Your favorite rational number in the [0;1] range is *p*<=/<=*q*. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be *p*<=/<=*q*?
Input Specification:
The first line contains a single integer *t* (1<=β€<=*t*<=β€<=1000)Β β the number of test cases.
Each of the next *t* lines contains four integers *x*, *y*, *p* and *q* (0<=β€<=*x*<=β€<=*y*<=β€<=109; 0<=β€<=*p*<=β€<=*q*<=β€<=109; *y*<=><=0; *q*<=><=0).
It is guaranteed that *p*<=/<=*q* is an irreducible fraction.
Hacks. For hacks, an additional constraint of *t*<=β€<=5 must be met.
Output Specification:
For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.
Demo Input:
['4\n3 10 1 2\n7 14 3 8\n20 70 2 7\n5 6 1 1\n']
Demo Output:
['4\n10\n0\n-1\n']
Note:
In the first example, you have to make 4 successful submissions. Your success rate will be equal to 7β/β14, or 1β/β2.
In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9β/β24, or 3β/β8.
In the third example, there is no need to make any new submissions. Your success rate is already equal to 20β/β70, or 2β/β7.
In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.
| 521
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The country Treeland consists of *n* cities connected with *n*<=-<=1 bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly 2*k* teams from 2*k* different cities.
During the first stage all teams are divided into *k* pairs. Teams of each pair play two games against each other: one in the hometown of the first team, and the other in the hometown of the other team. Thus, each of the 2*k* cities holds exactly one soccer game. However, it's not decided yet how to divide teams into pairs.
It's also necessary to choose several cities to settle players in. Organizers tend to use as few cities as possible to settle the teams.
Nobody wants to travel too much during the championship, so if a team plays in cities *u* and *v*, it wants to live in one of the cities on the shortest path between *u* and *v* (maybe, in *u* or in *v*). There is another constraint also: the teams from one pair must live in the same city.
Summarizing, the organizers want to divide 2*k* teams into pairs and settle them in the minimum possible number of cities *m* in such a way that teams from each pair live in the same city which lies between their hometowns.
Input Specification:
The first line of input contains two integers *n* and *k* (2<=β€<=*n*<=β€<=2Β·105,<=2<=β€<=2*k*<=β€<=*n*)Β β the number of cities in Treeland and the number of pairs of teams, respectively.
The following *n*<=-<=1 lines describe roads in Treeland: each of these lines contains two integers *a* and *b* (1<=β€<=*a*,<=*b*<=β€<=*n*,<=*a*<=β <=*b*) which mean that there is a road between cities *a* and *b*. It's guaranteed that there is a path between any two cities.
The last line contains 2*k* distinct integers *c*1,<=*c*2,<=...,<=*c*2*k* (1<=β€<=*c**i*<=β€<=*n*), where *c**i* is the hometown of the *i*-th team. All these numbers are distinct.
Output Specification:
The first line of output must contain the only positive integer *m* which should be equal to the minimum possible number of cities the teams can be settled in.
The second line should contain *m* distinct numbers *d*1,<=*d*2,<=...,<=*d**m* (1<=β€<=*d**i*<=β€<=*n*) denoting the indices of the cities where the teams should be settled.
The *k* lines should follow, the *j*-th of them should contain 3 integers *u**j*, *v**j* and *x**j*, where *u**j* and *v**j* are the hometowns of the *j*-th pair's teams, and *x**j* is the city they should live in during the tournament. Each of the numbers *c*1,<=*c*2,<=...,<=*c*2*k* should occur in all *u**j*'s and *v**j*'s exactly once. Each of the numbers *x**j* should belong to {*d*1,<=*d*2,<=...,<=*d**m*}.
If there are several possible answers, print any of them.
Demo Input:
['6 2\n1 2\n1 3\n2 4\n2 5\n3 6\n2 5 4 6\n']
Demo Output:
['1\n2\n5 4 2\n6 2 2\n']
Note:
In the first test the orginizers can settle all the teams in the city number 2. The way to divide all teams into pairs is not important, since all requirements are satisfied anyway, because the city 2 lies on the shortest path between every two cities from {2,β4,β5,β6}.
| 522
|
Title: Notepad
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base *b* caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length *n* without leading zeros in this number system. Each page in Nick's notepad has enough space for *c* numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.
Would you help Nick find out how many numbers will be written on the last page.
Input Specification:
The only input line contains three space-separated integers *b*, *n* and *c* (2<=β€<=*b*<=<<=10106, 1<=β€<=*n*<=<<=10106, 1<=β€<=*c*<=β€<=109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.
Output Specification:
In the only line output the amount of numbers written on the same page as the last number.
Demo Input:
['2 3 3\n', '2 3 4\n']
Demo Output:
['1', '4']
Note:
In both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.
| 523
|
Title: Polo the Penguin and Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little penguin Polo adores strings. But most of all he adores strings of length *n*.
One day he wanted to find a string that meets the following conditions:
1. The string consists of *n* lowercase English letters (that is, the string's length equals *n*), exactly *k* of these letters are distinct. 1. No two neighbouring letters of a string coincide; that is, if we represent a string as *s*<==<=*s*1*s*2... *s**n*, then the following inequality holds, *s**i*<=β <=*s**i*<=+<=1(1<=β€<=*i*<=<<=*n*). 1. Among all strings that meet points 1 and 2, the required string is lexicographically smallest.
Help him find such string or state that such string doesn't exist.
String *x*<==<=*x*1*x*2... *x**p* is lexicographically less than string *y*<==<=*y*1*y*2... *y**q*, if either *p*<=<<=*q* and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**p*<==<=*y**p*, or there is such number *r* (*r*<=<<=*p*,<=*r*<=<<=*q*), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=<<=*y**r*<=+<=1. The characters of the strings are compared by their ASCII codes.
Input Specification:
A single line contains two positive integers *n* and *k* (1<=β€<=*n*<=β€<=106,<=1<=β€<=*k*<=β€<=26) β the string's length and the number of distinct letters.
Output Specification:
In a single line print the required string. If there isn't such string, print "-1" (without the quotes).
Demo Input:
['7 4\n', '4 7\n']
Demo Output:
['ababacd\n', '-1\n']
Note:
none
| 524
|
Title: Rosetta Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains a single integer *a* (0<=β€<=*a*<=β€<=1<=000<=000).
Output Specification:
Output a single integer.
Demo Input:
['129\n']
Demo Output:
['1\n']
Note:
none
| 525
|
Title: Gifts
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with *n* gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for *n* names of items from the list. If the fish's list has *p* occurrences of the given name, then the old man can't ask for this name of item more than *p* times.
The old man knows that if he asks for *s* gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose *s* gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the *n* names in such a way that he can get *n* gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.
The old man wondered, what is the probability that he can get *n* most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.
Input Specification:
The first line contains two space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=1000) β the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then *m* lines follow: the *i*-th line first contains integer *k**i* (*k**i*<=><=0)Β β the number of distinct prices of gifts with the *i*-th name, then *k**i* distinct space-separated integers *c**ij* (1<=β€<=*c**ij*<=β€<=109), the gifts' prices.
It is guaranteed that the sum of all *k**i* doesn't exceed 1000. It is guaranteed that *n* is not greater than the total number of the gifts.
Output Specification:
On a single line print one real number β the probability of getting *n* most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10<=-<=9.
Demo Input:
['3 1\n3 10 20 30\n', '3 2\n1 40\n4 10 20 30 40\n']
Demo Output:
['1.000000000\n', '0.166666667\n']
Note:
none
| 526
|
Title: Lucky Tickets
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didnβt think it was enough and Leonid also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the 2*t* pieces he ended up with *t* tickets, each of which was lucky.
When Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest.
Vasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123.
What maximum number of tickets could Vasya get after that?
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=104) β the number of pieces. The second line contains *n* space-separated numbers *a**i* (1<=β€<=*a**i*<=β€<=108) β the numbers on the pieces. Vasya can only glue the pieces in pairs. Even if the number of a piece is already lucky, Vasya should glue the piece with some other one for it to count as lucky. Vasya does not have to use all the pieces. The numbers on the pieces an on the resulting tickets may coincide.
Output Specification:
Print the single number β the maximum number of lucky tickets that will be able to be restored. Don't forget that every lucky ticket is made of exactly two pieces glued together.
Demo Input:
['3\n123 123 99\n', '6\n1 1 1 23 10 3\n']
Demo Output:
['1\n', '1\n']
Note:
none
| 527
|
Title: Little Elephant and Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Little Elephant loves numbers.
He has a positive integer *x*. The Little Elephant wants to find the number of positive integers *d*, such that *d* is the divisor of *x*, and *x* and *d* have at least one common (the same) digit in their decimal representations.
Help the Little Elephant to find the described number.
Input Specification:
A single line contains a single integer *x* (1<=β€<=*x*<=β€<=109).
Output Specification:
In a single line print an integer β the answer to the problem.
Demo Input:
['1\n', '10\n']
Demo Output:
['1\n', '2\n']
Note:
none
| 528
|
Title: Yaroslav and Points
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Yaroslav has *n* points that lie on the *Ox* axis. The coordinate of the first point is *x*1, the coordinate of the second point is *x*2, ..., the coordinate of the *n*-th point is β *x**n*. Now Yaroslav wants to execute *m* queries, each of them is of one of the two following types:
1. Move the *p**j*-th point from position *x**p**j* to position *x**p**j*<=+<=*d**j*. At that, it is guaranteed that after executing such query all coordinates of the points will be distinct. 1. Count the sum of distances between all pairs of points that lie on the segment [*l**j*,<=*r**j*] (*l**j*<=β€<=*r**j*). In other words, you should count the sum of: .
Help Yaroslav.
Input Specification:
The first line contains integer *n* β the number of points (1<=β€<=*n*<=β€<=105). The second line contains distinct integers *x*1,<=*x*2,<=...,<=*x**n* β the coordinates of points (|*x**i*|<=β€<=109).
The third line contains integer *m* β the number of queries (1<=β€<=*m*<=β€<=105). The next *m* lines contain the queries. The *j*-th line first contains integer *t**j* (1<=β€<=*t**j*<=β€<=2) β the query type. If *t**j*<==<=1, then it is followed by two integers *p**j* and *d**j* (1<=β€<=*p**j*<=β€<=*n*,<=|*d**j*|<=β€<=1000). If *t**j*<==<=2, then it is followed by two integers *l**j* and *r**j* (<=-<=109<=β€<=*l**j*<=β€<=*r**j*<=β€<=109).
It is guaranteed that at any moment all the points have distinct coordinates.
Output Specification:
For each type 2 query print the answer on a single line. Print the answers in the order, in which the queries follow in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
Demo Input:
['8\n36 50 28 -75 40 -60 -95 -48\n20\n2 -61 29\n1 5 -53\n1 1 429\n1 5 130\n2 -101 -71\n2 -69 53\n1 1 404\n1 5 518\n2 -101 53\n2 50 872\n1 1 -207\n2 -99 -40\n1 7 -389\n1 6 -171\n1 2 464\n1 7 -707\n1 1 -730\n1 1 560\n2 635 644\n1 7 -677\n']
Demo Output:
['176\n20\n406\n1046\n1638\n156\n0\n']
Note:
none
| 529
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
DZY loves colors, and he enjoys painting.
On a colorful day, DZY gets a colorful ribbon, which consists of *n* units (they are numbered from 1 to *n* from left to right). The color of the *i*-th unit of the ribbon is *i* at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first.
DZY loves painting, we know. He takes up a paintbrush with color *x* and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit *i* currently is *y*. When it is painted by this paintbrush, the color of the unit becomes *x*, and the colorfulness of the unit increases by |*x*<=-<=*y*|.
DZY wants to perform *m* operations, each operation can be one of the following:
1. Paint all the units with numbers between *l* and *r* (both inclusive) with color *x*. 1. Ask the sum of colorfulness of the units between *l* and *r* (both inclusive).
Can you help DZY?
Input Specification:
The first line contains two space-separated integers *n*,<=*m*Β (1<=β€<=*n*,<=*m*<=β€<=105).
Each of the next *m* lines begins with a integer *type*Β (1<=β€<=*type*<=β€<=2), which represents the type of this operation.
If *type*<==<=1, there will be 3 more integers *l*,<=*r*,<=*x*Β (1<=β€<=*l*<=β€<=*r*<=β€<=*n*;Β 1<=β€<=*x*<=β€<=108) in this line, describing an operation 1.
If *type*<==<=2, there will be 2 more integers *l*,<=*r*Β (1<=β€<=*l*<=β€<=*r*<=β€<=*n*) in this line, describing an operation 2.
Output Specification:
For each operation 2, print a line containing the answer β sum of colorfulness.
Demo Input:
['3 3\n1 1 2 4\n1 2 3 5\n2 1 3\n', '3 4\n1 1 3 4\n2 1 1\n2 2 2\n2 3 3\n', '10 6\n1 1 5 3\n1 2 7 9\n1 10 10 11\n1 3 8 12\n1 1 10 3\n2 1 10\n']
Demo Output:
['8\n', '3\n2\n1\n', '129\n']
Note:
In the first sample, the color of each unit is initially [1,β2,β3], and the colorfulness is [0,β0,β0].
After the first operation, colors become [4,β4,β3], colorfulness become [3,β2,β0].
After the second operation, colors become [4,β5,β5], colorfulness become [3,β3,β2].
So the answer to the only operation of type 2 is 8.
| 530
|
Title: Laboratory Work
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value *n* times, and then compute the average value to lower the error.
Kirill has already made his measurements, and has got the following integer values: *x*1, *x*2, ..., *x**n*. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.
Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values *y*1, *y*2, ..., *y**n* in her work, that the following conditions are met:
- the average value of *x*1,<=*x*2,<=...,<=*x**n* is equal to the average value of *y*1,<=*y*2,<=...,<=*y**n*;- all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values;- the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work.
Help Anya to write such a set of measurements that the conditions above are met.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=100<=000) β the numeber of measurements made by Kirill.
The second line contains a sequence of integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=100<=000<=β€<=*x**i*<=β€<=100<=000) β the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values *x*1,<=*x*2,<=...,<=*x**n* does not exceed 2.
Output Specification:
In the first line print the minimum possible number of equal measurements.
In the second line print *n* integers *y*1,<=*y*2,<=...,<=*y**n* β the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values.
If there are multiple answers, print any of them.
Demo Input:
['6\n-1 1 1 0 0 -1\n', '3\n100 100 101\n', '7\n-10 -9 -10 -8 -10 -9 -9\n']
Demo Output:
['2\n0 0 0 0 0 0 \n', '3\n101 100 100 \n', '5\n-10 -10 -9 -9 -9 -9 -9 \n']
Note:
In the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.
In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.
In the third example the number of equal measurements is 5.
| 531
|
Title: Masha and geometric depression
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.
You are given geometric progression *b* defined by two integers *b*1 and *q*. Remind that a geometric progression is a sequence of integers *b*1,<=*b*2,<=*b*3,<=..., where for each *i*<=><=1 the respective term satisfies the condition *b**i*<==<=*b**i*<=-<=1Β·*q*, where *q* is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both *b*1 and *q* can equal 0. Also, Dvastan gave Masha *m* "bad" integers *a*1,<=*a*2,<=...,<=*a**m*, and an integer *l*.
Masha writes all progression terms one by one onto the board (including repetitive) while condition |*b**i*|<=β€<=*l* is satisfied (|*x*| means absolute value of *x*). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.
But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
Input Specification:
The first line of input contains four integers *b*1, *q*, *l*, *m* (-109<=β€<=*b*1,<=*q*<=β€<=109, 1<=β€<=*l*<=β€<=109, 1<=β€<=*m*<=β€<=105)Β β the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively.
The second line contains *m* distinct integers *a*1,<=*a*2,<=...,<=*a**m* (-109<=β€<=*a**i*<=β€<=109)Β β numbers that will never be written on the board.
Output Specification:
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
Demo Input:
['3 2 30 4\n6 14 25 48\n', '123 1 2143435 4\n123 11 -5453 141245\n', '123 1 2143435 4\n54343 -13 6 124\n']
Demo Output:
['3', '0', 'inf']
Note:
In the first sample case, Masha will write integers 3,β12,β24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed *l* by absolute value.
In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.
In the third case, Masha will write infinitely integers 123.
| 532
|
Title: Without Text
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You can preview the image in better quality by the link: [http://assets.codeforces.com/files/656/without-text.png](//assets.codeforces.com/files/656/without-text.png)
Input Specification:
The only line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be an alphanumeric character or a full stop ".".
Output Specification:
Output the required answer.
Demo Input:
['Codeforces\n', 'APRIL.1st\n']
Demo Output:
['-87\n', '17\n']
Note:
none
| 533
|
Title: Lengthening Sticks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given three sticks with positive integer lengths of *a*,<=*b*, and *c* centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most *l* centimeters. In particular, it is allowed not to increase the length of any stick.
Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.
Input Specification:
The single line contains 4 integers *a*,<=*b*,<=*c*,<=*l* (1<=β€<=*a*,<=*b*,<=*c*<=β€<=3Β·105, 0<=β€<=*l*<=β€<=3Β·105).
Output Specification:
Print a single integer β the number of ways to increase the sizes of the sticks by the total of at most *l* centimeters, so that you can make a non-degenerate triangle from it.
Demo Input:
['1 1 1 2\n', '1 2 3 1\n', '10 2 1 7\n']
Demo Output:
['4\n', '2\n', '0\n']
Note:
In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.
In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions.
| 534
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A remote island chain contains *n* islands, labeled 1 through *n*. Bidirectional bridges connect the islands to form a simple cycleΒ β a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands *n* and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.
The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.
Determine if it is possible for the islanders to arrange the statues in the desired order.
Input Specification:
The first line contains a single integer *n* (2<=β€<=*n*<=β€<=200<=000)Β β the total number of islands.
The second line contains *n* space-separated integers *a**i* (0<=β€<=*a**i*<=β€<=*n*<=-<=1)Β β the statue currently placed on the *i*-th island. If *a**i*<==<=0, then the island has no statue. It is guaranteed that the *a**i* are distinct.
The third line contains *n* space-separated integers *b**i* (0<=β€<=*b**i*<=β€<=*n*<=-<=1) β the desired statues of the *i*th island. Once again, *b**i*<==<=0 indicates the island desires no statue. It is guaranteed that the *b**i* are distinct.
Output Specification:
Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.
Demo Input:
['3\n1 0 2\n2 0 1\n', '2\n1 0\n0 1\n', '4\n1 2 3 0\n0 3 2 1\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
In the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.
In the second sample, the islanders can simply move statue 1 from island 1 to island 2.
In the third sample, no sequence of movements results in the desired position.
| 535
|
Title: Lazy Security Guard
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
Input Specification:
Input will consist of a single integer *N* (1<=β€<=*N*<=β€<=106), the number of city blocks that must be enclosed by the route.
Output Specification:
Print the minimum perimeter that can be achieved.
Demo Input:
['4\n', '11\n', '22\n']
Demo Output:
['8\n', '14\n', '20\n']
Note:
Here are some possible shapes for the examples:
<img class="tex-graphics" src="https://espresso.codeforces.com/e11bef2cf82b55dd583cfc97d12b5aee5e483a65.png" style="max-width: 100.0%;max-height: 100.0%;"/>
| 536
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There have recently been elections in the zoo. Overall there were 7 main political parties: one of them is the Little Elephant Political Party, 6 other parties have less catchy names.
Political parties find their number in the ballot highly important. Overall there are *m* possible numbers: 1,<=2,<=...,<=*m*. Each of these 7 parties is going to be assigned in some way to exactly one number, at that, two distinct parties cannot receive the same number.
The Little Elephant Political Party members believe in the lucky digits 4 and 7. They want to evaluate their chances in the elections. For that, they need to find out, how many correct assignments are there, such that the number of lucky digits in the Little Elephant Political Party ballot number is strictly larger than the total number of lucky digits in the ballot numbers of 6 other parties.
Help the Little Elephant Political Party, calculate this number. As the answer can be rather large, print the remainder from dividing it by 1000000007 (109<=+<=7).
Input Specification:
A single line contains a single positive integer *m* (7<=β€<=*m*<=β€<=109) β the number of possible numbers in the ballot.
Output Specification:
In a single line print a single integer β the answer to the problem modulo 1000000007 (109<=+<=7).
Demo Input:
['7\n', '8\n']
Demo Output:
['0\n', '1440\n']
Note:
none
| 537
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
From beginning till end, this message has been waiting to be conveyed.
For a given unordered multiset of *n* lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation *n*<=-<=1 times:
- Remove any two elements *s* and *t* from the set, and add their concatenation *s*<=+<=*t* to the set.
The cost of such operation is defined to be , where *f*(*s*,<=*c*) denotes the number of times character *c* appears in string *s*.
Given a non-negative integer *k*, construct any valid non-empty set of no more than 100<=000 letters, such that the minimum accumulative cost of the whole process is exactly *k*. It can be shown that a solution always exists.
Input Specification:
The first and only line of input contains a non-negative integer *k* (0<=β€<=*k*<=β€<=100<=000) β the required minimum cost.
Output Specification:
Output a non-empty string of no more than 100<=000 lowercase English letters β any multiset satisfying the requirements, concatenated to be a string.
Note that the printed string doesn't need to be the final concatenated string. It only needs to represent an unordered multiset of letters.
Demo Input:
['12\n', '3\n']
Demo Output:
['abababab\n', 'codeforces\n']
Note:
For the multiset {'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'}, one of the ways to complete the process is as follows:
- {"ab", "a", "b", "a", "b", "a", "b"}, with a cost of 0; - {"aba", "b", "a", "b", "a", "b"}, with a cost of 1; - {"abab", "a", "b", "a", "b"}, with a cost of 1; - {"abab", "ab", "a", "b"}, with a cost of 0; - {"abab", "aba", "b"}, with a cost of 1; - {"abab", "abab"}, with a cost of 1; - {"abababab"}, with a cost of 8.
The total cost is 12, and it can be proved to be the minimum cost of the process.
| 538
|
Title: Martian Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up.
Imagine a Martian who has exactly *n* eyes located in a row and numbered from the left to the right from 1 to *n*. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string *s* consisting of uppercase Latin letters. The string's length is *n*.
"Ding dong!" β the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only *m* Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers *a*, *b*, *c*, *d*, (1<=β€<=*a*<=β€<=*b*<=<<=*c*<=β€<=*d*<=β€<=*n*) and opens all eyes with numbers *i* such that *a*<=β€<=*i*<=β€<=*b* or *c*<=β€<=*i*<=β€<=*d*. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.
Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.
Input Specification:
The first line contains a non-empty string *s* consisting of uppercase Latin letters. The strings' length is *n* (2<=β€<=*n*<=β€<=105). The second line contains an integer *m* (1<=β€<=*m*<=β€<=100) β the number of beautiful words. Next *m* lines contain the beautiful words *p**i*, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.
Output Specification:
Print the single integer β the number of different beautiful strings the Martian can see this morning.
Demo Input:
['ABCBABA\n2\nBAAB\nABBA\n']
Demo Output:
['1\n']
Note:
Let's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes *a*β=β1,β*b*β=β2 and *c*β=β4,β*d*β=β5 or of he opens segments of eyes *a*β=β1,β*b*β=β2 and *c*β=β6,β*d*β=β7.
| 539
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Artem is fond of dancing. Most of all dances Artem likes ruedaΒ β Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.
More detailed, there are *n* pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves:
1. Value *x* and some direction are announced, and all boys move *x* positions in the corresponding direction. 1. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that *n* is even.
Your task is to determine the final position of each boy.
Input Specification:
The first line of the input contains two integers *n* and *q* (2<=β€<=*n*<=β€<=1<=000<=000, 1<=β€<=*q*<=β€<=2<=000<=000)Β β the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that *n* is even.
Next *q* lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as *x* (<=-<=*n*<=β€<=*x*<=β€<=*n*), where 0<=β€<=*x*<=β€<=*n* means all boys moves *x* girls in clockwise direction, while <=-<=*x* means all boys move *x* positions in counter-clockwise direction. There is no other input for commands of the second type.
Output Specification:
Output *n* integers, the *i*-th of them should be equal to the index of boy the *i*-th girl is dancing with after performing all *q* moves.
Demo Input:
['6 3\n1 2\n2\n1 2\n', '2 3\n1 1\n2\n1 -2\n', '4 2\n2\n1 3\n']
Demo Output:
['4 3 6 5 2 1\n', '1 2\n', '1 4 3 2\n']
Note:
none
| 540
|
Title: Two Squares
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.
The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.
Input Specification:
The input data consists of two lines, one for each square, both containing 4 pairs of integers. Each pair represents coordinates of one vertex of the square. Coordinates within each line are either in clockwise or counterclockwise order.
The first line contains the coordinates of the square with sides parallel to the coordinate axes, the second line contains the coordinates of the square at 45 degrees.
All the values are integer and between $-100$ and $100$.
Output Specification:
Print "Yes" if squares intersect, otherwise print "No".
You can print each letter in any case (upper or lower).
Demo Input:
['0 0 6 0 6 6 0 6\n1 3 3 5 5 3 3 1\n', '0 0 6 0 6 6 0 6\n7 3 9 5 11 3 9 1\n', '6 0 6 6 0 6 0 0\n7 4 4 7 7 10 10 7\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
In the first example the second square lies entirely within the first square, so they do intersect.
In the second sample squares do not have any points in common.
Here are images corresponding to the samples:
| 541
|
Title: Online Courses In BSU
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Now you can take online courses in the Berland State University! Polycarp needs to pass *k* main online courses of his specialty to get a diploma. In total *n* courses are availiable for the passage.
The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).
Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses.
Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.
Input Specification:
The first line contains *n* and *k* (1<=β€<=*k*<=β€<=*n*<=β€<=105) β the number of online-courses and the number of main courses of Polycarp's specialty.
The second line contains *k* distinct integers from 1 to *n* β numbers of main online-courses of Polycarp's specialty.
Then *n* lines follow, each of them describes the next course: the *i*-th of them corresponds to the course *i*. Each line starts from the integer *t**i* (0<=β€<=*t**i*<=β€<=*n*<=-<=1) β the number of courses on which the *i*-th depends. Then there follows the sequence of *t**i* distinct integers from 1 to *n* β numbers of courses in random order, on which the *i*-th depends. It is guaranteed that no course can depend on itself.
It is guaranteed that the sum of all values *t**i* doesn't exceed 105.
Output Specification:
Print -1, if there is no the way to get a specialty.
Otherwise, in the first line print the integer *m* β the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print *m* distinct integers β numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them.
Demo Input:
['6 2\n5 3\n0\n0\n0\n2 2 1\n1 4\n1 5\n', '9 3\n3 9 5\n0\n0\n3 9 4 5\n0\n0\n1 8\n1 6\n1 2\n2 1 2\n', '3 3\n1 2 3\n1 2\n1 3\n1 1\n']
Demo Output:
['5\n1 2 3 4 5 \n', '6\n1 2 9 4 5 3 \n', '-1\n']
Note:
In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
| 542
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration.
Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?
Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than 4*n* places.
Input Specification:
The first line contains two integers *n* and *m* (2<=β€<=*n*<=β€<=105;Β 0<=β€<=*m*<=β€<=105) β the number of places and the number of roads in Ponyville. Each of the following *m* lines contains two integers *u**i*,<=*v**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*;Β *u**i*<=β <=*v**i*), these integers describe a road between places *u**i* and *v**i*.
The next line contains *n* integers: *x*1,<=*x*2,<=...,<=*x**n* (0<=β€<=*x**i*<=β€<=1) β the parity of the number of times that each place must be visited. If *x**i*<==<=0, then the *i*-th place must be visited even number of times, else it must be visited odd number of times.
Output Specification:
Output the number of visited places *k* in the first line (0<=β€<=*k*<=β€<=4*n*). Then output *k* integers β the numbers of places in the order of path. If *x**i*<==<=0, then the *i*-th place must appear in the path even number of times, else *i*-th place must appear in the path odd number of times. Note, that given road system has no self-loops, therefore any two neighbouring places in the path must be distinct.
If there is no required path, output -1. If there multiple possible paths, you can output any of them.
Demo Input:
['3 2\n1 2\n2 3\n1 1 1\n', '5 7\n1 2\n1 3\n1 4\n1 5\n3 4\n3 5\n4 5\n0 1 0 1 0\n', '2 0\n0 0\n']
Demo Output:
['3\n1 2 3\n', '10\n2 1 3 4 5 4 5 4 3 1 ', '0\n']
Note:
none
| 543
|
Title: Digits Permutations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Andrey's favourite number is *n*. Andrey's friends gave him two identical numbers *n* as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.
Given number *n*, can you find the two digit permutations that have this property?
Input Specification:
The first line contains a positive integer *n* β the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.
Output Specification:
Print two permutations of digits of number *n*, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.
Demo Input:
['198\n', '500\n']
Demo Output:
['981\n819\n', '500\n500\n']
Note:
none
| 544
|
Title: Dorm Water Supply
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
The German University in Cairo (GUC) dorm houses are numbered from 1 to *n*. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).
For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.
In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.
Input Specification:
The first line contains two space-separated integers *n* and *p* (1<=β€<=*n*<=β€<=1000,<=0<=β€<=*p*<=β€<=*n*) β the number of houses and the number of pipes correspondingly.
Then *p* lines follow β the description of *p* pipes. The *i*-th line contains three integers *a**i* *b**i* *d**i*, indicating a pipe of diameter *d**i* going from house *a**i* to house *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*,<=*a**i*<=β <=*b**i*,<=1<=β€<=*d**i*<=β€<=106).
It is guaranteed that for each house there is at most one pipe going into it and at most one pipe going out of it.
Output Specification:
Print integer *t* in the first line β the number of tank-tap pairs of houses.
For the next *t* lines, print 3 integers per line, separated by spaces: *tank**i*, *tap**i*, and *diameter**i*, where *tank**i*<=β <=*tap**i* (1<=β€<=*i*<=β€<=*t*). Here *tank**i* and *tap**i* are indexes of tank and tap houses respectively, and *diameter**i* is the maximum amount of water that can be conveyed. All the *t* lines should be ordered (increasingly) by *tank**i*.
Demo Input:
['3 2\n1 2 10\n2 3 20\n', '3 3\n1 2 20\n2 3 10\n3 1 5\n', '4 2\n1 2 60\n3 4 50\n']
Demo Output:
['1\n1 3 10\n', '0\n', '2\n1 2 60\n3 4 50\n']
Note:
none
| 545
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are *n* destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The *n* destinations are described by a non-negative integers sequence *a*1, *a*2, ..., *a**n*. The number *a**k* represents that the *k*th destination is at distance *a**k* kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer *x* and next destination, located at kilometer *y*, is |*x*<=-<=*y*| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all *n* destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
Input Specification:
The first line contains integer *n* (2<=β€<=*n*<=β€<=105). Next line contains *n* distinct integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=107).
Output Specification:
Output two integers β the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.
Demo Input:
['3\n2 3 5\n']
Demo Output:
['22 3']
Note:
Consider 6 possible routes:
- [2, 3, 5]: total distance traveled: |2 β 0| + |3 β 2| + |5 β 3| = 5; - [2, 5, 3]: |2 β 0| + |5 β 2| + |3 β 5| = 7; - [3, 2, 5]: |3 β 0| + |2 β 3| + |5 β 2| = 7; - [3, 5, 2]: |3 β 0| + |5 β 3| + |2 β 5| = 8; - [5, 2, 3]: |5 β 0| + |2 β 5| + |3 β 2| = 9; - [5, 3, 2]: |5 β 0| + |3 β 5| + |2 β 3| = 8.
The average travel distance is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29119d3733c79f70eb2d77186ac1606bf938508a.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ee9d5516ed2ca1d2b65ed21f8a64f58f94954c30.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ed5cc8cb7dd43cfb27f2459586062538e44de7bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
| 546
|
Title: Tree-String Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of *n* vertices, numbered from 1 to *n*. In this problem the tree root is the vertex number 1.
Let's represent the length of the shortest by the number of edges path in the tree between vertices *v* and *u* as *d*(*v*,<=*u*).
A parent of vertex *v* in the rooted tree with the root in vertex *r* (*v*<=β <=*r*) is vertex *p**v*, such that *d*(*r*,<=*p**v*)<=+<=1<==<=*d*(*r*,<=*v*) and *d*(*p**v*,<=*v*)<==<=1. For example, on the picture the parent of vertex *v*<==<=5 is vertex *p*5<==<=2.
One day Polycarpus came across a rooted tree, consisting of *n* vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex *p**v* to vertex *v* (1<=<<=*v*<=β€<=*n*), he knows string *s**v* that is written on it. All strings are written on the edges from top to bottom. For example, on the picture *s*7="ba". The characters in the strings are numbered starting from 0.
Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (*v*,<=*x*) that means that the position is the *x*-th letter of the string *s**v* (1<=<<=*v*<=β€<=*n*, 0<=β€<=*x*<=<<=|*s**v*|), where |*s**v*| is the length of string *s**v*. For example, the highlighted letters are positions (2,<=1) and (3,<=1).
Let's consider the pair of positions (*v*,<=*x*) and (*u*,<=*y*) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string *z*. String *z* consists of all letters on the way from (*v*,<=*x*) to (*u*,<=*y*), written in the order of this path. For example, in the picture the highlighted positions define string "bacaba".
Polycarpus has a string *t*, he wants to know the number of pairs of positions that define string *t*. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!
Input Specification:
The first line contains integer *n* (2<=β€<=*n*<=β€<=105) β the number of vertices of Polycarpus's tree. Next *n*<=-<=1 lines contain the tree edges. The *i*-th of them contains number *p**i*<=+<=1 and string *s**i*<=+<=1 (1<=β€<=*p**i*<=+<=1<=β€<=*n*;Β *p**i*<=+<=1<=β <=(*i*<=+<=1)). String *s**i*<=+<=1 is non-empty and consists of lowercase English letters. The last line contains string *t*. String *t* consists of lowercase English letters, its length is at least 2.
It is guaranteed that the input contains at most 3Β·105 English letters.
Output Specification:
Print a single integer β the required number.
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:
['7\n1 ab\n5 bacaba\n1 abacaba\n2 aca\n5 ba\n2 ba\naba\n', '7\n1 ab\n5 bacaba\n1 abacaba\n2 aca\n5 ba\n2 ba\nbacaba\n']
Demo Output:
['6\n', '4\n']
Note:
In the first test case string "aba" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).
Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down.
| 547
|
Title: Tram
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.
Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.
Input Specification:
The first line contains a single number *n* (2<=β€<=*n*<=β€<=1000) β the number of the tram's stops.
Then *n* lines follow, each contains two integers *a**i* and *b**i* (0<=β€<=*a**i*,<=*b**i*<=β€<=1000) β the number of passengers that exits the tram at the *i*-th stop, and the number of passengers that enter the tram at the *i*-th stop. The stops are given from the first to the last stop in the order of tram's movement.
- The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that *a*1<==<=0. - At the last stop, all the passengers exit the tram and it becomes empty. More formally, . - No passenger will enter the train at the last stop. That is, *b**n*<==<=0.
Output Specification:
Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).
Demo Input:
['4\n0 3\n2 5\n4 2\n4 0\n']
Demo Output:
['6\n']
Note:
For the first example, a capacity of 6 is sufficient:
- At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. - At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now. - At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now. - Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints.
Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.
| 548
|
Title: Bear and Chemistry
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Limak is a smart brown bear who loves chemistry, reactions and transforming elements.
In Bearland (Limak's home) there are *n* elements, numbered 1 through *n*. There are also special machines, that can transform elements. Each machine is described by two integers *a**i*,<=*b**i* representing two elements, not necessarily distinct. One can use a machine either to transform an element *a**i* to *b**i* or to transform *b**i* to *a**i*. Machines in Bearland aren't very resistant and each of them can be used at most once. It is possible that *a**i*<==<=*b**i* and that many machines have the same pair *a**i*,<=*b**i*.
Radewoosh is Limak's biggest enemy and rival. He wants to test Limak in the chemistry. They will meet tomorrow and both of them will bring all their machines. Limak has *m* machines but he doesn't know much about his enemy. They agreed Radewoosh will choose two distinct elements, let's denote them as *x* and *y*. Limak will be allowed to use both his and Radewoosh's machines. He may use zero or more (maybe even all) machines to achieve the goal, each machine at most once. Limak will start from an element *x* and his task will be to first get an element *y* and then to again get an element *x*Β β then we say that he succeeds. After that Radewoosh would agree that Limak knows the chemistry (and Radewoosh would go away).
Radewoosh likes some particular non-empty set of favorite elements and he will choose *x*,<=*y* from that set. Limak doesn't know exactly which elements are in the set and also he doesn't know what machines Radewoosh has. Limak has heard *q* gossips (queries) though and each of them consists of Radewoosh's machines and favorite elements. For each gossip Limak wonders if he would be able to succeed tomorrow for every pair *x*,<=*y* chosen from the set of favorite elements. If yes then print "YES" (without the quotes). But if there exists a pair (*x*,<=*y*) from the given set that Limak wouldn't be able to succeed then you should print "NO" (without the quotes).
Input Specification:
The first line contains three integers *n*, *m* and *q* (1<=β€<=*n*,<=*q*<=β€<=300<=000,<=0<=β€<=*m*<=β€<=300<=000)Β β the number of elements, the number of Limak's machines and the number of gossips, respectively.
Each of the next *m* lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*) describing one of Limak's machines.
Then, the description of *q* gossips follows.
The first line of the description of the *i*-th gossip contains two integers *n**i* and *m**i* (1<=β€<=*n**i*<=β€<=300<=000,<=0<=β€<=*m**i*<=β€<=300<=000). The second line contains *n**i* distinct integers *x**i*,<=1,<=*x**i*,<=2,<=...,<=*x**i*,<=*n**i* (1<=β€<=*x**i*,<=*j*<=β€<=*n*)Β β Radewoosh's favorite elements in the *i*-th gossip. Note that *n**i*<==<=1 is allowed, in this case there are no pairs of distinct elements, so Limak automatically wins (the answer is "YES"). Then *m**i* lines follow, each containing two integers *a**i*,<=*j*,<=*b**i*,<=*j* (1<=β€<=*a**i*,<=*j*,<=*b**i*,<=*j*) describing one of Radewoosh's machines in the *i*-th gossip.
The sum of *n**i* over all gossips won't exceed 300<=000. Also, the sum of *m**i* over all gossips won't exceed 300<=000.
Important: Because we want you to process the gossips online, in order to know the elements in Radewoosh's favorite set and elements that his machines can transform, for on each number that denotes them in the input you should use following function:
where *R* is initially equal to 0 and is increased by the number of the query any time the answer is "YES". Queries are numbered starting with 1 in the order they appear in the input.
Output Specification:
You should print *q* lines. The *i*-th of them should contain "YES" (without quotes) if for the *i*-th gossip for each pair of elements *x* and *y* (in the set *x**i*,<=1,<=*x**i*,<=2,<=...,<=*x**i*,<=*n**i*) Limak is able to succeed. Otherwise you should print "NO" (without quotes).
Demo Input:
['6 5 4\n1 2\n2 3\n3 4\n2 4\n5 6\n2 0\n4 2\n2 1\n6 2\n3 4\n3 2\n6 3 4\n2 5\n4 6\n2 1\n1 2\n1 2\n', '7 6 2\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n7 2\n1 2 3 4 5 6 7\n4 5\n6 7\n7 2\n1 2 3 4 5 6 7\n4 6\n5 7\n']
Demo Output:
['YES\nNO\nYES\nYES\n', 'NO\nYES\n']
Note:
Lets look at first sample:
In first gossip Radewoosh's favorite set is {4,β2} and he has no machines. Limak can tranform element 4 into 2 (so half of a task is complete) and then 2 into 3, and 3 into 4. Answer is "YES", so *R* is increased by 1.
In second gossip set in the input is denoted by {6,β2} and machine by (3,β4), but *R* is equal to 1, so set is {1,β3} and machine is (4,β5). Answer is "NO", so *R* isn't changed.
In third gossip set {6,β4,β3} and machines (2,β5) and (4,β6) are deciphered to be {1,β5,β4}, (3,β6) and (5,β1).
Consider Radewoosh's choices:
- If he chooses elements 1 and 5, then Limak is able to transform 1 into 5, then 6 into 3, 3 into 2 and 2 into 1.- If he chooses elements 5 and 4, then Limak is able to transform 5 into 6, 6 into 3, 3 into 4 (half way already behind him), 4 into 2, 2 into 1, 1 into 5.- If he chooses elements 1 and 4, then Limak is able to transform 1 into 2, 2 into 4, 4 into 3, 3 into 6, 6 into 5 and 5 into 1.
So Limak is able to execute task. Answer is "YES" and *R* is increased by 3 (it's equal to 4 now).
In last gossip {1,β2} and (1,β2) are deciphered to be {5,β6} and (5,β6). Now there are 2 machines (5,β6) so Limak is able to execute task again.
| 549
|
Title: Graph Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In computer science, there is a method called "Divide And Conquer By Node" to solve some hard problems about paths on a tree. Let's desribe how this method works by function:
*solve*(*t*) (*t* is a tree):
1. Chose a node *x* (it's common to chose weight-center) in tree *t*. Let's call this step "Line A". 1. Deal with all paths that pass *x*. 1. Then delete *x* from tree *t*. 1. After that *t* becomes some subtrees. 1. Apply *solve* on each subtree.
This ends when *t* has only one node because after deleting it, there's nothing.
Now, WJMZBMR has mistakenly believed that it's ok to chose any node in "Line A". So he'll chose a node at random. To make the situation worse, he thinks a "tree" should have the same number of edges and nodes! So this procedure becomes like that.
Let's define the variable *totalCost*. Initially the value of *totalCost* equal to 0. So, *solve*(*t*) (now *t* is a graph):
1. *totalCost*<==<=*totalCost*<=+<=(*size*Β *of*Β *t*). The operation "=" means assignment. (*Size*Β *of*Β *t*) means the number of nodes in *t*. 1. Choose a node *x* in graph *t* at random (uniformly among all nodes of *t*). 1. Then delete *x* from graph *t*. 1. After that *t* becomes some connected components. 1. Apply *solve* on each component.
He'll apply *solve* on a connected graph with *n* nodes and *n* edges. He thinks it will work quickly, but it's very slow. So he wants to know the expectation of *totalCost* of this procedure. Can you help him?
Input Specification:
The first line contains an integer *n* (3<=β€<=*n*<=β€<=3000) β the number of nodes and edges in the graph. Each of the next *n* lines contains two space-separated integers *a**i*,<=*b**i* (0<=β€<=*a**i*,<=*b**i*<=β€<=*n*<=-<=1) indicating an edge between nodes *a**i* and *b**i*.
Consider that the graph nodes are numbered from 0 to (*n*<=-<=1). It's guaranteed that there are no self-loops, no multiple edges in that graph. It's guaranteed that the graph is connected.
Output Specification:
Print a single real number β the expectation of *totalCost*. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
Demo Input:
['5\n3 4\n2 3\n2 4\n0 4\n1 2\n', '3\n0 1\n1 2\n0 2\n', '5\n0 1\n1 2\n2 0\n3 0\n4 1\n']
Demo Output:
['13.166666666666666\n', '6.000000000000000\n', '13.166666666666666\n']
Note:
Consider the second example. No matter what we choose first, the *totalCost* will always be 3β+β2β+β1β=β6.
| 550
|
Title: Parking Lot
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.
The parking lot before the office consists of one line of (2*n*<=-<=2) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.
Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly *n* successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.
Input Specification:
The only line of the input contains one integer *n* (3<=β€<=*n*<=β€<=30) β the amount of successive cars of the same make.
Output Specification:
Output one integer β the number of ways to fill the parking lot by cars of four makes using the described way.
Demo Input:
['3\n']
Demo Output:
['24']
Note:
Let's denote car makes in the following way: A β Aston Martin, B β Bentley, M β Mercedes-Maybach, Z β Zaporozhets. For *n*β=β3 there are the following appropriate ways to fill the parking lot: AAAB AAAM AAAZ ABBB AMMM AZZZ BBBA BBBM BBBZ BAAA BMMM BZZZ MMMA MMMB MMMZ MAAA MBBB MZZZ ZZZA ZZZB ZZZM ZAAA ZBBB ZMMM
Originally it was planned to grant sport cars of Ferrari, Lamborghini, Maserati and Bugatti makes but this idea was renounced because it is impossible to drive these cars having small road clearance on the worn-down roads of IT City.
| 551
|
Title: Card Game Again
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vova again tries to play some computer card game.
The rules of deck creation in this game are simple. Vova is given an existing deck of *n* cards and a magic number *k*. The order of the cards in the deck is fixed. Each card has a number written on it; number *a**i* is written on the *i*-th card in the deck.
After receiving the deck and the magic number, Vova removes *x* (possibly *x*<==<=0) cards from the top of the deck, *y* (possibly *y*<==<=0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards *x*<=+<=1, *x*<=+<=2, ... *n*<=-<=*y*<=-<=1, *n*<=-<=*y* from the original deck.
Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by *k*. So Vova received a deck (possibly not a valid one) and a number *k*, and now he wonders, how many ways are there to choose *x* and *y* so the deck he will get after removing *x* cards from the top and *y* cards from the bottom is valid?
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*n*<=β€<=100<=000, 1<=β€<=*k*<=β€<=109).
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=109) β the numbers written on the cards.
Output Specification:
Print the number of ways to choose *x* and *y* so the resulting deck is valid.
Demo Input:
['3 4\n6 2 8\n', '3 6\n9 1 14\n']
Demo Output:
['4\n', '1\n']
Note:
In the first example the possible values of *x* and *y* are:
1. *x*β=β0,β*y*β=β0; 1. *x*β=β1,β*y*β=β0; 1. *x*β=β2,β*y*β=β0; 1. *x*β=β0,β*y*β=β1.
| 552
|
Title: Code obfuscation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol *a*, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with *b*, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input Specification:
In the only line of input there is a string *S* of lowercase English letters (1<=β€<=|*S*|<=β€<=500)Β β the identifiers of a program with removed whitespace characters.
Output Specification:
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Demo Input:
['abacaba\n', 'jinotega\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
- replace all occurences of number with a, the result would be "a string a character a string a",- replace all occurences of string with b, the result would be "a b a character a b a",- replace all occurences of character with c, the result would be "a b a c a b a",- all identifiers have been replaced, thus the obfuscation is finished.
| 553
|
Title: Ksenia and Pan Scales
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.
The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.
Input Specification:
The first line has a non-empty sequence of characters describing the scales. In this sequence, an uppercase English letter indicates a weight, and the symbol "|" indicates the delimiter (the character occurs in the sequence exactly once). All weights that are recorded in the sequence before the delimiter are initially on the left pan of the scale. All weights that are recorded in the sequence after the delimiter are initially on the right pan of the scale.
The second line contains a non-empty sequence containing uppercase English letters. Each letter indicates a weight which is not used yet.
It is guaranteed that all the English letters in the input data are different. It is guaranteed that the input does not contain any extra characters.
Output Specification:
If you cannot put all the weights on the scales so that the scales were in equilibrium, print string "Impossible". Otherwise, print the description of the resulting scales, copy the format of the input.
If there are multiple answers, print any of them.
Demo Input:
['AC|T\nL\n', '|ABC\nXYZ\n', 'W|T\nF\n', 'ABC|\nD\n']
Demo Output:
['AC|TL\n', 'XYZ|ABC\n', 'Impossible\n', 'Impossible\n']
Note:
none
| 554
|
Title: A and B and Chess
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
- the queen's weight is 9, - the rook's weight is 5, - the bishop's weight is 3, - the knight's weight is 3, - the pawn's weight is 1, - the king's weight isn't considered in evaluating position.
The player's weight equals to the sum of weights of all his pieces on the board.
As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
Input Specification:
The input contains eight lines, eight characters each β the board's description.
The white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters.
The white pieces are denoted as follows: the queen is represented is 'Q', the rook β as 'R', the bishop β as'B', the knight β as 'N', the pawn β as 'P', the king β as 'K'.
The black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively.
An empty square of the board is marked as '.' (a dot).
It is not guaranteed that the given chess position can be achieved in a real game. Specifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.
Output Specification:
Print "White" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, print "Black" if the weight of the black pieces is more than the weight of the white pieces and print "Draw" if the weights of the white and black pieces are equal.
Demo Input:
['...QK...\n........\n........\n........\n........\n........\n........\n...rk...\n', 'rnbqkbnr\npppppppp\n........\n........\n........\n........\nPPPPPPPP\nRNBQKBNR\n', 'rppppppr\n...k....\n........\n........\n........\n........\nK...Q...\n........\n']
Demo Output:
['White\n', 'Draw\n', 'Black\n']
Note:
In the first test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals 5.
In the second test sample the weights of the positions of the black and the white pieces are equal to 39.
In the third test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals to 16.
| 555
|
Title: Greg and Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Greg has an array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n* and *m* operations. Each operation looks as: *l**i*, *r**i*, *d**i*, (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*). To apply operation *i* to the array means to increase all array elements with numbers *l**i*,<=*l**i*<=+<=1,<=...,<=*r**i* by value *d**i*.
Greg wrote down *k* queries on a piece of paper. Each query has the following form: *x**i*, *y**i*, (1<=β€<=*x**i*<=β€<=*y**i*<=β€<=*m*). That means that one should apply operations with numbers *x**i*,<=*x**i*<=+<=1,<=...,<=*y**i* to the array.
Now Greg is wondering, what the array *a* will be after all the queries are executed. Help Greg.
Input Specification:
The first line contains integers *n*, *m*, *k* (1<=β€<=*n*,<=*m*,<=*k*<=β€<=105). The second line contains *n* integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=105) β the initial array.
Next *m* lines contain operations, the operation number *i* is written as three integers: *l**i*, *r**i*, *d**i*, (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*), (0<=β€<=*d**i*<=β€<=105).
Next *k* lines contain the queries, the query number *i* is written as two integers: *x**i*, *y**i*, (1<=β€<=*x**i*<=β€<=*y**i*<=β€<=*m*).
The numbers in the lines are separated by single spaces.
Output Specification:
On a single line print *n* integers *a*1,<=*a*2,<=...,<=*a**n* β the array after executing all the queries. Separate the printed numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
Demo Input:
['3 3 3\n1 2 3\n1 2 1\n1 3 2\n2 3 4\n1 2\n1 3\n2 3\n', '1 1 1\n1\n1 1 1\n1 1\n', '4 3 6\n1 2 3 4\n1 2 1\n2 3 2\n3 4 4\n1 2\n1 3\n2 3\n1 2\n1 3\n2 3\n']
Demo Output:
['9 18 17\n', '2\n', '5 18 31 20\n']
Note:
none
| 556
|
Title: Boredom
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=105) that shows how many numbers are in Alex's sequence.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=105).
Output Specification:
Print a single integer β the maximum number of points that Alex can earn.
Demo Input:
['2\n1 2\n', '3\n1 2 3\n', '9\n1 2 1 3 2 2 2 2 3\n']
Demo Output:
['2\n', '4\n', '10\n']
Note:
Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.
| 557
|
Title: Wall Bars
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Manao is working for a construction company. Recently, an order came to build wall bars in a children's park. Manao was commissioned to develop a plan of construction, which will enable the company to save the most money.
After reviewing the formal specifications for the wall bars, Manao discovered a number of controversial requirements and decided to treat them to the company's advantage. His resulting design can be described as follows:
- Let's introduce some unit of length. The construction center is a pole of height *n*. - At heights 1,<=2,<=...,<=*n* exactly one horizontal bar sticks out from the pole. Each bar sticks in one of four pre-fixed directions. - A child can move from one bar to another if the distance between them does not exceed *h* and they stick in the same direction. If a child is on the ground, he can climb onto any of the bars at height between 1 and *h*. In Manao's construction a child should be able to reach at least one of the bars at heights *n*<=-<=*h*<=+<=1,<=*n*<=-<=*h*<=+<=2,<=...,<=*n* if he begins at the ground.
Manao is wondering how many distinct construction designs that satisfy his requirements exist. As this number can be rather large, print the remainder after dividing it by 1000000009Β (109<=+<=9). Two designs are considered distinct if there is such height *i*, that the bars on the height *i* in these designs don't stick out in the same direction.
Input Specification:
A single line contains two space-separated integers, *n* and *h* (1<=β€<=*n*<=β€<=1000, 1<=β€<=*h*<=β€<=*min*(*n*,<=30)).
Output Specification:
In a single line print the remainder after dividing the number of designs by 1000000009Β (109<=+<=9).
Demo Input:
['5 1\n', '4 2\n', '4 3\n', '5 2\n']
Demo Output:
['4\n', '148\n', '256\n', '376\n']
Note:
Consider several designs for *h*β=β2. A design with the first bar sticked out in direction *d*<sub class="lower-index">1</sub>, the second β in direction *d*<sub class="lower-index">2</sub> and so on (1ββ€β*d*<sub class="lower-index">*i*</sub>ββ€β4) is denoted as string *d*<sub class="lower-index">1</sub>*d*<sub class="lower-index">2</sub>...*d*<sub class="lower-index">*n*</sub>.
Design "1231" (the first three bars are sticked out in different directions, the last one β in the same as first). A child can reach neither the bar at height 3 nor the bar at height 4.
Design "414141". A child can reach the bar at height 5. To do this, he should first climb at the first bar, then at the third and then at the fifth one. He can also reach bar at height 6 by the route second βββ fourth βββ sixth bars.
Design "123333". The child can't reach the upper two bars.
Design "323323". The bar at height 6 can be reached by the following route: first βββ third βββ fourth βββ sixth bars.
| 558
|
Title: Timofey and rectangles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane *n* rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
Input Specification:
The first line contains single integer *n* (1<=β€<=*n*<=β€<=5Β·105)Β β the number of rectangles.
*n* lines follow. The *i*-th of these lines contains four integers *x*1, *y*1, *x*2 and *y*2 (<=-<=109<=β€<=*x*1<=<<=*x*2<=β€<=109, <=-<=109<=β€<=*y*1<=<<=*y*2<=β€<=109), that means that points (*x*1,<=*y*1) and (*x*2,<=*y*2) are the coordinates of two opposite corners of the *i*-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output Specification:
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print *n* lines, in the *i*-th of them print single integer *c**i* (1<=β€<=*c**i*<=β€<=4)Β β the color of *i*-th rectangle.
Demo Input:
['8\n0 0 5 3\n2 -1 5 0\n-3 -4 2 -1\n-1 -1 2 0\n-3 0 0 5\n5 2 10 3\n7 -3 10 2\n4 -2 7 -1\n']
Demo Output:
['YES\n1\n2\n2\n3\n2\n2\n4\n1\n']
Note:
none
| 559
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with *n* nodes and *m* edges. *k* of the nodes are home to the governments of the *k* countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input Specification:
The first line of input will contain three integers *n*, *m* and *k* (1<=β€<=*n*<=β€<=1<=000, 0<=β€<=*m*<=β€<=100<=000, 1<=β€<=*k*<=β€<=*n*)Β β the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain *k* integers *c*1,<=*c*2,<=...,<=*c**k* (1<=β€<=*c**i*<=β€<=*n*). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following *m* lines of input will contain two integers *u**i* and *v**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*). This denotes an undirected edge between nodes *u**i* and *v**i*.
It is guaranteed that the graph described by the input is stable.
Output Specification:
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Demo Input:
['4 1 2\n1 3\n1 2\n', '3 3 1\n2\n1 2\n1 3\n2 3\n']
Demo Output:
['2\n', '0\n']
Note:
For the first sample test, the graph looks like this:
For the second sample test, the graph looks like this:
| 560
|
Title: Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a node of the tree with index 1 and with weight 0. Let *cnt* be the number of nodes in the tree at any instant (initially, *cnt* is set to 1). Support *Q* queries of following two types:
- Add a new node (index *cnt*<=+<=1) with weight *W* and add edge between node *R* and this node. - Output the maximum length of sequence of nodes which starts with *R*. - Every node in the sequence is an ancestor of its predecessor. - Sum of weight of nodes in sequence does not exceed *X*. - For some nodes *i*,<=*j* that are consecutive in the sequence if *i* is an ancestor of *j* then *w*[*i*]<=β₯<=*w*[*j*] and there should not exist a node *k* on simple path from *i* to *j* such that *w*[*k*]<=β₯<=*w*[*j*]
The tree is rooted at node 1 at any instant.
Note that the queries are given in a modified way.
Input Specification:
First line containing the number of queries *Q* (1<=β€<=*Q*<=β€<=400000).
Let *last* be the answer for previous query of type 2 (initially *last* equals 0).
Each of the next *Q* lines contains a query of following form:
- 1 p q (1<=β€<=*p*,<=*q*<=β€<=1018): This is query of first type where and . It is guaranteed that 1<=β€<=*R*<=β€<=*cnt* and 0<=β€<=*W*<=β€<=109. - 2 p q (1<=β€<=*p*,<=*q*<=β€<=1018): This is query of second type where and . It is guaranteed that 1<=β€<=*R*<=β€<=*cnt* and 0<=β€<=*X*<=β€<=1015.
denotes bitwise XOR of *a* and *b*.
It is guaranteed that at least one query of type 2 exists.
Output Specification:
Output the answer to each query of second type in separate line.
Demo Input:
['6\n1 1 1\n2 2 0\n2 2 1\n1 3 0\n2 2 0\n2 2 2\n', '6\n1 1 0\n2 2 0\n2 0 3\n1 0 2\n2 1 3\n2 1 6\n', '7\n1 1 2\n1 2 3\n2 3 3\n1 0 0\n1 5 1\n2 5 0\n2 4 0\n', '7\n1 1 3\n1 2 3\n2 3 4\n1 2 0\n1 5 3\n2 5 5\n2 7 22\n']
Demo Output:
['0\n1\n1\n2\n', '2\n2\n3\n2\n', '1\n1\n2\n', '1\n2\n3\n']
Note:
In the first example,
*last*β=β0
- Query 1: 1 1 1, Node 2 with weight 1 is added to node 1.
- Query 2: 2 2 0, No sequence of nodes starting at 2 has weight less than or equal to 0. *last*β=β0
- Query 3: 2 2 1, Answer is 1 as sequence will be {2}. *last*β=β1
- Query 4: 1 2 1, Node 3 with weight 1 is added to node 2.
- Query 5: 2 3 1, Answer is 1 as sequence will be {3}. Node 2 cannot be added as sum of weights cannot be greater than 1. *last*β=β1
- Query 6: 2 3 3, Answer is 2 as sequence will be {3,β2}. *last*β=β2
| 561
|
Title: Testing Pants for Sadness
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".
The test consists of *n* questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question *n*. Question *i* contains *a**i* answer variants, exactly one of them is correct.
A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the *n* questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.
Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?
Input Specification:
The first line contains a positive integer *n* (1<=β€<=*n*<=β€<=100). It is the number of questions in the test. The second line contains space-separated *n* positive integers *a**i* (1<=β€<=*a**i*<=β€<=109), the number of answer variants to question *i*.
Output Specification:
Print a single number β the minimal number of clicks needed to pass the test it the worst-case scenario.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Demo Input:
['2\n1 1\n', '2\n2 2\n', '1\n10\n']
Demo Output:
['2', '5', '10']
Note:
Note to the second sample. In the worst-case scenario you will need five clicks:
- the first click selects the first variant to the first question, this answer turns out to be wrong. - the second click selects the second variant to the first question, it proves correct and we move on to the second question; - the third click selects the first variant to the second question, it is wrong and we go back to question 1; - the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; - the fifth click selects the second variant to the second question, it proves correct, the test is finished.
| 562
|
Title: The Monster and the Squirrel
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1,<=2,<=...,<=*n* in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2,<=3,<=...,<=*n* (in this particular order). And then she puts a walnut in each region inside the polygon.
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input Specification:
The first and only line of the input contains a single integer *n* (3<=β€<=*n*<=β€<=54321) - the number of vertices of the regular polygon drawn by Ari.
Output Specification:
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Demo Input:
['5\n', '3\n']
Demo Output:
['9\n', '1\n']
Note:
One of the possible solutions for the first sample is shown on the picture above.
| 563
|
Title: Bears and Juice
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* bears in the inn and *p* places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.
Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.
Each night, the following happens in this exact order:
1. Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears. 1. Each bear drinks a glass from each barrel he chose. 1. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.
At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).
Radewoosh wants to allow bears to win. He considers *q* scenarios. In the *i*-th scenario the party will last for *i* nights. Then, let *R**i* denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define . Your task is to find , where denotes the exclusive or (also denoted as XOR).
Note that the same barrel may be chosen by many bears and all of them will go to sleep at once.
Input Specification:
The only line of the input contains three integers *n*, *p* and *q* (1<=β€<=*n*<=β€<=109, 1<=β€<=*p*<=β€<=130, 1<=β€<=*q*<=β€<=2<=000<=000)Β β the number of bears, the number of places to sleep and the number of scenarios, respectively.
Output Specification:
Print one integer, equal to .
Demo Input:
['5 1 3\n', '1 100 4\n', '3 2 1\n', '100 100 100\n']
Demo Output:
['32\n', '4\n', '7\n', '381863924\n']
Note:
In the first sample, there are 5 bears and only 1 place to sleep. We have *R*<sub class="lower-index">1</sub>β=β6,β*R*<sub class="lower-index">2</sub>β=β11,β*R*<sub class="lower-index">3</sub>β=β16 so the answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b3272ae710321a0a8ceffa5d8c9afe3bf54e75eb.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Let's analyze the optimal strategy for scenario with 2 days. There are *R*<sub class="lower-index">2</sub>β=β11 barrels and 10 of them contain juice.
- In the first night, the *i*-th bear chooses a barrel *i* only. <ul> <li> If one of the first 5 barrels contains wine then one bear goes to sleep. Then, bears win because they know where wine is and there is at least one awake bear. - But let's say none of the first 5 barrels contains wine. In the second night, the *i*-th bear chooses a barrel 5β+β*i*. <ul> <li> If one of barrels 6βββ10 contains wine then one bear goes to sleep. And again, bears win in such a situation. - If nobody went to sleep then wine is in a barrel 11.
In the second sample, there is only one bear. He should choose an empty set of barrels in each night. Otherwise, he would maybe get wine and bears would lose (because there must be at least one awake bear). So, for any number of days we have *R*<sub class="lower-index">*i*</sub>β=β1. The answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c8b4cc3bcaf1329398e221289359b01c0a392ec5.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
| 564
|
Title: Tavas and Pashmaks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Tavas is a cheerleader in the new sports competition named "Pashmaks".
This competition consists of two part: swimming and then running. People will immediately start running *R* meters after they finished swimming exactly *S* meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).
Before the match starts, Tavas knows that there are *n* competitors registered for the match. Also, he knows that *i*-th person's swimming speed is *s**i* meters per second and his/her running speed is *r**i* meters per second. Unfortunately, he doesn't know the values of *R* and *S*, but he knows that they are real numbers greater than 0.
As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of *R* and *S* such that with these values, (s)he will be a winner.
Tavas isn't really familiar with programming, so he asked you to help him.
Input Specification:
The first line of input contains a single integer *n* (1<=β€<=*n*<=β€<=2<=Γ<=105).
The next *n* lines contain the details of competitors. *i*-th line contains two integers *s**i* and *r**i* (1<=β€<=*s**i*,<=*r**i*<=β€<=104).
Output Specification:
In the first and the only line of output, print a sequence of numbers of possible winners in increasing order.
Demo Input:
['3\n1 3\n2 2\n3 1\n', '3\n1 2\n1 1\n2 1\n']
Demo Output:
['1 2 3 \n', '1 3 \n']
Note:
none
| 565
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.
A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes *u* and *v* connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with *h* nodes, which are the hydra's heads. The stomach is connected with *t* nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of *h*<=+<=*t*<=+<=2 nodes.
Also, Petya's got a non-directed graph *G*, consisting of *n* nodes and *m* edges. Petya got this graph as a last year birthday present from his mom. Graph *G* contains no self-loops or multiple edges.
Now Petya wants to find a hydra in graph *G*. Or else, to make sure that the graph doesn't have a hydra.
Input Specification:
The first line contains four integers *n*, *m*, *h*, *t* (1<=β€<=*n*,<=*m*<=β€<=105, 1<=β€<=*h*,<=*t*<=β€<=100) β the number of nodes and edges in graph *G*, and the number of a hydra's heads and tails.
Next *m* lines contain the description of the edges of graph *G*. The *i*-th of these lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*, *a*<=β <=*b*) β the numbers of the nodes, connected by the *i*-th edge.
It is guaranteed that graph *G* contains no self-loops and multiple edges. Consider the nodes of graph *G* numbered with integers from 1 to *n*.
Output Specification:
If graph *G* has no hydra, print "NO" (without the quotes).
Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers β the numbers of nodes *u* and *v*. In the third line print *h* numbers β the numbers of the nodes that are the heads. In the fourth line print *t* numbers β the numbers of the nodes that are the tails. All printed numbers should be distinct.
If there are multiple possible answers, you are allowed to print any of them.
Demo Input:
['9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1\n', '7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n']
Demo Output:
['YES\n4 1\n5 6 \n9 3 2 \n', 'NO\n']
Note:
The first sample is depicted on the picture below:
| 566
|
Title: Brain Network (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of *n* brains and *m* brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains *u* and *v* (1<=β€<=*u*,<=*v*<=β€<=*n*) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input Specification:
The first line of the input contains two space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100000) denoting the number of brains (which are conveniently numbered from 1 to *n*) and the number of brain connectors in the nervous system, respectively. In the next *m* lines, descriptions of brain connectors follow. Every connector is given as a pair of brains *a*β*b* it connects (1<=β€<=*a*,<=*b*<=β€<=*n* and *a*<=β <=*b*).
Output Specification:
Print one number β the brain latency.
Demo Input:
['4 3\n1 2\n1 3\n1 4\n', '5 4\n1 2\n2 3\n3 4\n3 5\n']
Demo Output:
['2', '3']
Note:
none
| 567
|
Title: Coins Exhibition
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from 1 to *k*, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.
Arkady and Kirill made some photos of the coins, each photo contained a segment of neighboring coins. Akrady is interested in obverses, so on each photo made by him there is at least one coin with obverse side up. On the contrary, Kirill is interested in reverses, so on each photo made by him there is at least one coin with its reverse side up.
The photos are lost now, but Arkady and Kirill still remember the bounds of the segments of coins each photo contained. Given this information, compute the remainder of division by 109<=+<=7 of the number of ways to choose the upper side of each coin in such a way, that on each Arkady's photo there is at least one coin with obverse side up, and on each Kirill's photo there is at least one coin with reverse side up.
Input Specification:
The first line contains three integers *k*, *n* and *m* (1<=β€<=*k*<=β€<=109, 0<=β€<=*n*,<=*m*<=β€<=105)Β β the total number of coins, the number of photos made by Arkady, and the number of photos made by Kirill, respectively.
The next *n* lines contain the descriptions of Arkady's photos, one per line. Each of these lines contains two integers *l* and *r* (1<=β€<=*l*<=β€<=*r*<=β€<=*k*), meaning that among coins from the *l*-th to the *r*-th there should be at least one with obverse side up.
The next *m* lines contain the descriptions of Kirill's photos, one per line. Each of these lines contains two integers *l* and *r* (1<=β€<=*l*<=β€<=*r*<=β€<=*k*), meaning that among coins from the *l*-th to the *r*-th there should be at least one with reverse side up.
Output Specification:
Print the only lineΒ β the number of ways to choose the side for each coin modulo 109<=+<=7<==<=1000000007.
Demo Input:
['5 2 2\n1 3\n3 5\n2 2\n4 5\n', '5 3 2\n1 3\n2 2\n3 5\n2 2\n4 5\n', '60 5 7\n1 3\n50 60\n1 60\n30 45\n20 40\n4 5\n6 37\n5 18\n50 55\n22 27\n25 31\n44 45\n']
Demo Output:
['8\n', '0\n', '732658600\n']
Note:
In the first example the following ways are possible ('O'Β β obverse, 'R'Β β reverse side):
- OROOR, - ORORO, - ORORR, - RROOR, - RRORO, - RRORR, - ORROR, - ORRRO.
In the second example the information is contradictory: the second coin should have obverse and reverse sides up at the same time, that is impossible. So, the answer is 0.
| 568
|
Title: A polyline
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains two integers *a*,<=*b* (1<=β€<=*a*<=β€<=10,<=0<=β€<=*b*<=β€<=22Β·*a*<=-<=1) separated by a single space.
Output Specification:
Output two integers separated by a single space.
Demo Input:
['1 0\n', '2 15\n', '4 160\n']
Demo Output:
['0 0\n', '3 0\n', '12 12\n']
Note:
none
| 569
|
Title: Change-free
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Student Arseny likes to plan his life for *n* days ahead. He visits a canteen every day and he has already decided what he will order in each of the following *n* days. Prices in the canteen do not change and that means Arseny will spend *c**i* rubles during the *i*-th day.
There are 1-ruble coins and 100-ruble notes in circulation. At this moment, Arseny has *m* coins and a sufficiently large amount of notes (you can assume that he has an infinite amount of them). Arseny loves modern technologies, so he uses his credit card everywhere except the canteen, but he has to pay in cash in the canteen because it does not accept cards.
Cashier always asks the student to pay change-free. However, it's not always possible, but Arseny tries to minimize the dissatisfaction of the cashier. Cashier's dissatisfaction for each of the days is determined by the total amount of notes and coins in the change. To be precise, if the cashier gives Arseny *x* notes and coins on the *i*-th day, his dissatisfaction for this day equals *x*Β·*w**i*. Cashier always gives change using as little coins and notes as possible, he always has enough of them to be able to do this.
Arseny wants to pay in such a way that the total dissatisfaction of the cashier for *n* days would be as small as possible. Help him to find out how he needs to pay in each of the *n* days!
Note that Arseny always has enough money to pay, because he has an infinite amount of notes. Arseny can use notes and coins he received in change during any of the following days.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=105, 0<=β€<=*m*<=β€<=109)Β β the amount of days Arseny planned his actions for and the amount of coins he currently has.
The second line contains a sequence of integers *c*1,<=*c*2,<=...,<=*c**n* (1<=β€<=*c**i*<=β€<=105)Β β the amounts of money in rubles which Arseny is going to spend for each of the following days.
The third line contains a sequence of integers *w*1,<=*w*2,<=...,<=*w**n* (1<=β€<=*w**i*<=β€<=105)Β β the cashier's dissatisfaction coefficients for each of the following days.
Output Specification:
In the first line print one integerΒ β minimum possible total dissatisfaction of the cashier.
Then print *n* lines, the *i*-th of then should contain two numbersΒ β the amount of notes and the amount of coins which Arseny should use to pay in the canteen on the *i*-th day.
Of course, the total amount of money Arseny gives to the casher in any of the days should be no less than the amount of money he has planned to spend. It also shouldn't exceed 106 rubles: Arseny never carries large sums of money with him.
If there are multiple answers, print any of them.
Demo Input:
['5 42\n117 71 150 243 200\n1 1 1 1 1\n', '3 0\n100 50 50\n1 3 2\n', '5 42\n117 71 150 243 200\n5 4 3 2 1\n']
Demo Output:
['79\n1 17\n1 0\n2 0\n2 43\n2 0\n', '150\n1 0\n1 0\n0 50\n', '230\n1 17\n1 0\n1 50\n3 0\n2 0\n']
Note:
none
| 570
|
Title: Game Shopping
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$.
Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$.
Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.
When Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop.
Maxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.
For example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$.
Your task is to get the number of games Maxim will buy.
Input Specification:
The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 1000$) β the number of games and the number of bills in Maxim's wallet.
The second line of the input contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 1000$), where $c_i$ is the cost of the $i$-th game.
The third line of the input contains $m$ integers $a_1, a_2, \dots, a_m$ ($1 \le a_j \le 1000$), where $a_j$ is the value of the $j$-th bill from the Maxim's wallet.
Output Specification:
Print a single integer β the number of games Maxim will buy.
Demo Input:
['5 4\n2 4 5 2 4\n5 3 4 6\n', '5 2\n20 40 50 20 40\n19 20\n', '6 4\n4 8 15 16 23 42\n1000 1000 1000 1000\n']
Demo Output:
['3\n', '0\n', '4\n']
Note:
The first example is described in the problem statement.
In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.
In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.
| 571
|
Title: Name Quest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A Martian boy is named *s* β he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if *s*=Β«abaΒ», then strings Β«baobabΒ», Β«aabbaaΒ», Β«helloabahelloΒ» make him very happy and strings Β«aabΒ», Β«baaaΒ» and Β«helloabhelloΒ» do not.
However rather than being happy once, he loves twice as much being happy twice! So, when he got string *t* as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.
Help *s* determine the number of distinct ways to cut the given string *t* into two parts in the required manner.
Input Specification:
The first line contains string *s*, consisting of lowercase English letters. The length of string *s* is from 1 to 1000 letters.
The second line contains string *t*, that also consists of lowercase English letters. The length of string *t* is from 1 to 106 letters.
Output Specification:
Print the sought number of ways to cut string *t* in two so that each part made *s* happy.
Demo Input:
['aba\nbaobababbah\n', 'mars\nsunvenusearthmarsjupitersaturnuranusneptune\n']
Demo Output:
['2\n', '0\n']
Note:
none
| 572
|
Title: Good Number
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's call a number *k*-good if it contains all digits not exceeding *k* (0,<=...,<=*k*). You've got a number *k* and an array *a* containing *n* numbers. Find out how many *k*-good numbers are in *a* (count each number every time it occurs in array *a*).
Input Specification:
The first line contains integers *n* and *k* (1<=β€<=*n*<=β€<=100, 0<=β€<=*k*<=β€<=9). The *i*-th of the following *n* lines contains integer *a**i* without leading zeroes (1<=β€<=*a**i*<=β€<=109).
Output Specification:
Print a single integer β the number of *k*-good numbers in *a*.
Demo Input:
['10 6\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n', '2 1\n1\n10\n']
Demo Output:
['10\n', '1\n']
Note:
none
| 573
|
Title: Help General
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply).
As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "If the squared distance between some two soldiers equals to 5, then those soldiers will conflict with each other!"
The drill exercises are held on a rectangular *n*<=Γ<=*m* field, split into *nm* square 1<=Γ<=1 segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares (*x*1,<=*y*1) and (*x*2,<=*y*2) equals exactly (*x*1<=-<=*x*2)2<=+<=(*y*1<=-<=*y*2)2. Now not all *nm* squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square (2,<=2), then he cannot put soldiers in the squares (1,<=4), (3,<=4), (4,<=1) and (4,<=3) β each of them will conflict with the soldier in the square (2,<=2).
Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.
Input Specification:
The single line contains space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=1000) that represent the size of the drill exercise field.
Output Specification:
Print the desired maximum number of warriors.
Demo Input:
['2 4\n', '3 4\n']
Demo Output:
['4', '6']
Note:
In the first sample test Sir Lancelot can place his 4 soldiers on the 2βΓβ4 court as follows (the soldiers' locations are marked with gray circles on the scheme):
In the second sample test he can place 6 soldiers on the 3βΓβ4 site in the following manner:
| 574
|
Title: Gluttony
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* with *n* distinct integers. Construct an array *b* by permuting *a* such that for every non-empty subset of indices *S*<==<={*x*1,<=*x*2,<=...,<=*x**k*} (1<=β€<=*x**i*<=β€<=*n*, 0<=<<=*k*<=<<=*n*) the sums of elements on that positions in *a* and *b* are different, i.Β e.
Input Specification:
The first line contains one integer *n* (1<=β€<=*n*<=β€<=22)Β β the size of the array.
The second line contains *n* space-separated distinct integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=109)Β β the elements of the array.
Output Specification:
If there is no such array *b*, print -1.
Otherwise in the only line print *n* space-separated integers *b*1,<=*b*2,<=...,<=*b**n*. Note that *b* must be a permutation of *a*.
If there are multiple answers, print any of them.
Demo Input:
['2\n1 2\n', '4\n1000 100 10 1\n']
Demo Output:
['2 1 \n', '100 1 1000 10\n']
Note:
An array *x* is a permutation of *y*, if we can shuffle elements of *y* such that it will coincide with *x*.
Note that the empty subset and the subset containing all indices are not counted.
| 575
|
Title: Handshakes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
On February, 30th *n* students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left.
At any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times.
Given how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible.
Please note that some students could work independently until the end of the day, without participating in a team contest.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=2Β·105) β the number of students who came to CTOP. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=<<=*n*), where *a**i* is the number of students with who the *i*-th student shook hands.
Output Specification:
If the sought order of students exists, print in the first line "Possible" and in the second line print the permutation of the students' numbers defining the order in which the students entered the center. Number *i* that stands to the left of number *j* in this permutation means that the *i*-th student came earlier than the *j*-th student. If there are multiple answers, print any of them.
If the sought order of students doesn't exist, in a single line print "Impossible".
Demo Input:
['5\n2 1 3 0 1\n', '9\n0 2 3 4 1 1 0 2 2\n', '4\n0 2 1 1\n']
Demo Output:
['Possible\n4 5 1 3 2 ', 'Possible\n7 5 2 1 6 8 3 4 9', 'Impossible\n']
Note:
In the first sample from the statement the order of events could be as follows:
- student 4 comes in (*a*<sub class="lower-index">4</sub>β=β0), he has no one to greet; - student 5 comes in (*a*<sub class="lower-index">5</sub>β=β1), he shakes hands with student 4; - student 1 comes in (*a*<sub class="lower-index">1</sub>β=β2), he shakes hands with two students (students 4, 5); - student 3 comes in (*a*<sub class="lower-index">3</sub>β=β3), he shakes hands with three students (students 4, 5, 1); - students 4, 5, 3 form a team and start writing a contest; - student 2 comes in (*a*<sub class="lower-index">2</sub>β=β1), he shakes hands with one student (number 1).
In the second sample from the statement the order of events could be as follows:
- student 7 comes in (*a*<sub class="lower-index">7</sub>β=β0), he has nobody to greet; - student 5 comes in (*a*<sub class="lower-index">5</sub>β=β1), he shakes hands with student 7; - student 2 comes in (*a*<sub class="lower-index">2</sub>β=β2), he shakes hands with two students (students 7, 5); - students 7, 5, 2 form a team and start writing a contest; - student 1 comes in(*a*<sub class="lower-index">1</sub>β=β0), he has no one to greet (everyone is busy with the contest); - student 6 comes in (*a*<sub class="lower-index">6</sub>β=β1), he shakes hands with student 1; - student 8 comes in (*a*<sub class="lower-index">8</sub>β=β2), he shakes hands with two students (students 1, 6); - student 3 comes in (*a*<sub class="lower-index">3</sub>β=β3), he shakes hands with three students (students 1, 6, 8); - student 4 comes in (*a*<sub class="lower-index">4</sub>β=β4), he shakes hands with four students (students 1, 6, 8, 3); - students 8, 3, 4 form a team and start writing a contest; - student 9 comes in (*a*<sub class="lower-index">9</sub>β=β2), he shakes hands with two students (students 1, 6).
In the third sample from the statement the order of events is restored unambiguously:
- student 1 comes in (*a*<sub class="lower-index">1</sub>β=β0), he has no one to greet; - student 3 comes in (or student 4) (*a*<sub class="lower-index">3</sub>β=β*a*<sub class="lower-index">4</sub>β=β1), he shakes hands with student 1; - student 2 comes in (*a*<sub class="lower-index">2</sub>β=β2), he shakes hands with two students (students 1, 3 (or 4)); - the remaining student 4 (or student 3), must shake one student's hand (*a*<sub class="lower-index">3</sub>β=β*a*<sub class="lower-index">4</sub>β=β1) but it is impossible as there are only two scenarios: either a team formed and he doesn't greet anyone, or he greets all the three present people who work individually.
| 576
|
Title: Misha and LCP on Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Misha has a tree with characters written on the vertices. He can choose two vertices *s* and *t* of this tree and write down characters of vertices lying on a path from *s* to *t*. We'll say that such string corresponds to pair (*s*,<=*t*).
Misha has *m* queries of type: you are given 4 vertices *a*, *b*, *c*, *d*; you need to find the largest common prefix of the strings that correspond to pairs (*a*,<=*b*) and (*c*,<=*d*). Your task is to help him.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=300<=000) β the number of vertices in the tree.
Next follows a line consisting of *n* small English letters. The *i*-th character of the string corresponds to the character written on the *i*-th vertex.
Next *n*<=-<=1 lines contain information about edges. An edge is defined by a pair of integers *u*, *v* (1<=β€<=*u*,<=*v*<=β€<=*n*, *u*<=β <=*v*), separated by spaces.
The next line contains integer *m* (1<=β€<=*m*<=β€<=1<=000<=000) β the number of queries.
Next *m* lines contain information about queries. A query is defined by four integers *a*, *b*, *c*, *d* (1<=β€<=*a*,<=*b*,<=*c*,<=*d*<=β€<=*n*), separated by spaces.
Output Specification:
For each query print the length of the largest common prefix on a separate line.
Demo Input:
['6\nbbbabb\n2 1\n3 2\n4 3\n5 2\n6 5\n6\n2 5 3 1\n1 5 2 3\n5 6 5 6\n6 3 4 1\n6 2 3 4\n2 2 4 5\n']
Demo Output:
['2\n2\n2\n0\n1\n0\n']
Note:
none
| 577
|
Title: Mike and strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mike has *n* strings *s*1,<=*s*2,<=...,<=*s**n* each consisting of lowercase English letters. In one move he can choose a string *s**i*, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=50) β the number of strings.
This is followed by *n* lines which contain a string each. The *i*-th line corresponding to string *s**i*. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.
Output Specification:
Print the minimal number of moves Mike needs in order to make all the strings equal or print <=-<=1 if there is no solution.
Demo Input:
['4\nxzzwo\nzwoxz\nzzwox\nxzzwo\n', '2\nmolzv\nlzvmo\n', '3\nkc\nkc\nkc\n', '3\naa\naa\nab\n']
Demo Output:
['5\n', '2\n', '0\n', '-1\n']
Note:
In the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".
| 578
|
Title: Lecture
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
Input Specification:
The first line contains two integers, *n* and *m* (1<=β€<=*n*<=β€<=3000, 1<=β€<=*m*<=β€<=3000) β the number of words in the professor's lecture and the number of words in each of these languages.
The following *m* lines contain the words. The *i*-th line contains two strings *a**i*, *b**i* meaning that the word *a**i* belongs to the first language, the word *b**i* belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once.
The next line contains *n* space-separated strings *c*1,<=*c*2,<=...,<=*c**n* β the text of the lecture. It is guaranteed that each of the strings *c**i* belongs to the set of strings {*a*1,<=*a*2,<=... *a**m*}.
All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.
Output Specification:
Output exactly *n* words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.
Demo Input:
['4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest\n', '5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll\n']
Demo Output:
['codeforces round letter round\n', 'hbnyiyc joll joll un joll\n']
Note:
none
| 579
|
Title: Dog Show
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win!
On the show a dog needs to eat as many bowls of dog food as possible (bottomless stomach helps here). Dogs compete separately of each other and the rules are as follows:
At the start of the show the dog and the bowls are located on a line. The dog starts at position *x*<==<=0 and *n* bowls are located at positions *x*<==<=1,<=*x*<==<=2,<=...,<=*x*<==<=*n*. The bowls are numbered from 1 to *n* from left to right. After the show starts the dog immediately begins to run to the right to the first bowl.
The food inside bowls is not ready for eating at the start because it is too hot (dog's self-preservation instinct prevents eating). More formally, the dog can eat from the *i*-th bowl after *t**i* seconds from the start of the show or later.
It takes dog 1 second to move from the position *x* to the position *x*<=+<=1. The dog is not allowed to move to the left, the dog runs only to the right with the constant speed 1 distance unit per second. When the dog reaches a bowl (say, the bowl *i*), the following cases are possible:
- the food had cooled down (i.e. it passed at least *t**i* seconds from the show start): the dog immediately eats the food and runs to the right without any stop, - the food is hot (i.e. it passed less than *t**i* seconds from the show start): the dog has two options: to wait for the *i*-th bowl, eat the food and continue to run at the moment *t**i* or to skip the *i*-th bowl and continue to run to the right without any stop.
After *T* seconds from the start the show ends. If the dog reaches a bowl of food at moment *T* the dog can not eat it. The show stops before *T* seconds if the dog had run to the right of the last bowl.
You need to help your dog create a strategy with which the maximum possible number of bowls of food will be eaten in *T* seconds.
Input Specification:
Two integer numbers are given in the first line - *n* and *T* (1<=β€<=*n*<=β€<=200<=000, 1<=β€<=*T*<=β€<=2Β·109) β the number of bowls of food and the time when the dog is stopped.
On the next line numbers *t*1,<=*t*2,<=...,<=*t**n* (1<=β€<=*t**i*<=β€<=109) are given, where *t**i* is the moment of time when the *i*-th bowl of food is ready for eating.
Output Specification:
Output a single integer β the maximum number of bowls of food the dog will be able to eat in *T* seconds.
Demo Input:
['3 5\n1 5 3\n', '1 2\n1\n', '1 1\n1\n']
Demo Output:
['2\n', '1\n', '0\n']
Note:
In the first example the dog should skip the second bowl to eat from the two bowls (the first and the third).
| 580
|
Title: Game
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1<=Γ<=*n* square and paints the squares black and white. After that Petya can start moves β during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petyaβs aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.
Input Specification:
The first line contains number *n* (1<=β€<=*n*<=β€<=1000) which represents the stripeβs length. The second line contains exactly *n* symbols β the lineβs initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.
Output Specification:
If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.
Demo Input:
['6\n111010\n', '5\n10001\n', '7\n1100010\n', '5\n00100\n']
Demo Output:
['1\n', '1\n', '2\n', '2\n']
Note:
In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white.
In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black.
| 581
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).
A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.
You are a spy in the enemy's camp. You noticed *n* soldiers standing in a row, numbered 1 through *n*. The general wants to choose a group of *k* consecutive soldiers. For every *k* consecutive soldiers, the general wrote down whether they would be an effective group or not.
You managed to steal the general's notes, with *n*<=-<=*k*<=+<=1 strings *s*1,<=*s*2,<=...,<=*s**n*<=-<=*k*<=+<=1, each either "YES" or "NO".
- The string *s*1 describes a group of soldiers 1 through *k* ("YES" if the group is effective, and "NO" otherwise). - The string *s*2 describes a group of soldiers 2 through *k*<=+<=1. - And so on, till the string *s**n*<=-<=*k*<=+<=1 that describes a group of soldiers *n*<=-<=*k*<=+<=1 through *n*.
Your task is to find possible names of *n* soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.
Find and print any solution. It can be proved that there always exists at least one solution.
Input Specification:
The first line of the input contains two integers *n* and *k* (2<=β€<=*k*<=β€<=*n*<=β€<=50)Β β the number of soldiers and the size of a group respectively.
The second line contains *n*<=-<=*k*<=+<=1 strings *s*1,<=*s*2,<=...,<=*s**n*<=-<=*k*<=+<=1. The string *s**i* is "YES" if the group of soldiers *i* through *i*<=+<=*k*<=-<=1 is effective, and "NO" otherwise.
Output Specification:
Find any solution satisfying all given conditions. In one line print *n* space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10.
If there are multiple valid solutions, print any of them.
Demo Input:
['8 3\nNO NO YES YES YES NO\n', '9 8\nYES NO\n', '3 2\nNO NO\n']
Demo Output:
['Adam Bob Bob Cpqepqwer Limak Adam Bob Adam', 'R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc', 'Na Na Na']
Note:
In the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output:
- First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string *s*<sub class="lower-index">1</sub> is "NO". - Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string *s*<sub class="lower-index">2</sub> is "NO". - Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string *s*<sub class="lower-index">3</sub> is "YES". - ..., - Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string *s*<sub class="lower-index">6</sub> is "NO".
| 582
|
Title: Correct Solution?
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number *n* to Bob and said:
βShuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.
βNo problem! β said Bob and immediately gave her an answer.
Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.
Input Specification:
The first line contains one integer *n* (0<=β€<=*n*<=β€<=109) without leading zeroes. The second lines contains one integer *m* (0<=β€<=*m*<=β€<=109) β Bob's answer, possibly with leading zeroes.
Output Specification:
Print OK if Bob's answer is correct and WRONG_ANSWER otherwise.
Demo Input:
['3310\n1033\n', '4\n5\n']
Demo Output:
['OK\n', 'WRONG_ANSWER\n']
Note:
none
| 583
|
Title: Cutting Figure
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've gotten an *n*<=Γ<=*m* sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as *A*. Set *A* is connected. Your task is to find the minimum number of squares that we can delete from set *A* to make it not connected.
A set of painted squares is called connected, if for every two squares *a* and *b* from this set there is a sequence of squares from the set, beginning in *a* and ending in *b*, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input Specification:
The first input line contains two space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=50) β the sizes of the sheet of paper.
Each of the next *n* lines contains *m* characters β the description of the sheet of paper: the *j*-th character of the *i*-th line equals either "#", if the corresponding square is painted (belongs to set *A*), or equals "." if the corresponding square is not painted (does not belong to set *A*). It is guaranteed that the set of all painted squares *A* is connected and isn't empty.
Output Specification:
On the first line print the minimum number of squares that need to be deleted to make set *A* not connected. If it is impossible, print -1.
Demo Input:
['5 4\n####\n#..#\n#..#\n#..#\n####\n', '5 5\n#####\n#...#\n#####\n#...#\n#####\n']
Demo Output:
['2\n', '2\n']
Note:
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
| 584
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens.
All characters in this game are lowercase English letters. There are two players: Mister B and his competitor.
Initially the players have a string *s* consisting of the first *a* English letters in alphabetical order (for example, if *a*<==<=5, then *s* equals to "abcde").
The players take turns appending letters to string *s*. Mister B moves first.
Mister B must append exactly *b* letters on each his move. He can arbitrary choose these letters. His opponent adds exactly *a* letters on each move.
Mister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string *s* of length *a* and generates a string *t* of length *a* such that all letters in the string *t* are distinct and don't appear in the considered suffix. From multiple variants of *t* lexicographically minimal is chosen (if *a*<==<=4 and the suffix is "bfdd", the computer chooses string *t* equal to "aceg"). After that the chosen string *t* is appended to the end of *s*.
Mister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string *s* on the segment between positions *l* and *r*, inclusive. Letters of string *s* are numerated starting from 1.
Input Specification:
First and only line contains four space-separated integers: *a*, *b*, *l* and *r* (1<=β€<=*a*,<=*b*<=β€<=12, 1<=β€<=*l*<=β€<=*r*<=β€<=109) β the numbers of letters each player appends and the bounds of the segment.
Output Specification:
Print one integer β the minimum possible number of different letters in the segment from position *l* to position *r*, inclusive, in string *s*.
Demo Input:
['1 1 1 8\n', '4 2 2 6\n', '3 7 4 6\n']
Demo Output:
['2', '3', '1']
Note:
In the first sample test one of optimal strategies generate string *s*β=β"abababab...", that's why answer is 2.
In the second sample test string *s*β=β"abcdbcaefg..." can be obtained, chosen segment will look like "bcdbc", that's why answer is 3.
In the third sample test string *s*β=β"abczzzacad..." can be obtained, chosen, segment will look like "zzz", that's why answer is 1.
| 585
|
Title: Road Widening
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!
The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.
The street is split into *n* equal length parts from left to right, the *i*-th part is characterized by two integers: width of road *s**i* and width of lawn *g**i*.
For each of *n* parts the Mayor should decide the size of lawn to demolish. For the *i*-th part he can reduce lawn width by integer *x**i* (0<=β€<=*x**i*<=β€<=*g**i*). After it new road width of the *i*-th part will be equal to *s*'*i*<==<=*s**i*<=+<=*x**i* and new lawn width will be equal to *g*'*i*<==<=*g**i*<=-<=*x**i*.
On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each *i* (1<=β€<=*i*<=<<=*n*) the inequation |*s*'*i*<=+<=1<=-<=*s*'*i*|<=β€<=1 should hold. Initially this condition might not be true.
You need to find the the total width of lawns the Mayor will destroy according to his plan.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=2Β·105) β number of parts of the street.
Each of the following *n* lines contains two integers *s**i*,<=*g**i* (1<=β€<=*s**i*<=β€<=106, 0<=β€<=*g**i*<=β€<=106) β current width of road and width of the lawn on the *i*-th part of the street.
Output Specification:
In the first line print the total width of lawns which will be removed.
In the second line print *n* integers *s*'1,<=*s*'2,<=...,<=*s*'*n* (*s**i*<=β€<=*s*'*i*<=β€<=*s**i*<=+<=*g**i*) β new widths of the road starting from the first part and to the last.
If there is no solution, print the only integer -1 in the first line.
Demo Input:
['3\n4 5\n4 5\n4 10\n', '4\n1 100\n100 1\n1 100\n100 1\n', '3\n1 1\n100 100\n1 1\n']
Demo Output:
['16\n9 9 10 \n', '202\n101 101 101 101 \n', '-1\n']
Note:
none
| 586
|
Title: Curfew
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Instructors of Some Informatics School make students go to bed.
The house contains *n* rooms, in each room exactly *b* students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to *n*. Initially, in *i*-th room there are *a**i* students. All students are currently somewhere in the house, therefore *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*. Also 2 instructors live in this house.
The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room *n*, while the second instructor starts near room *n* and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if *n* is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends.
When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to *b*, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students.
While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most *d* rooms, that is she can move to a room with number that differs my at most *d*. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously.
Formally, here is what's happening:
- A curfew is announced, at this point in room *i* there are *a**i* students. - Each student can run to another room but not further than *d* rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed. - Instructors enter room 1 and room *n*, they count students there and lock the room (after it no one can enter or leave this room). - Each student from rooms with numbers from 2 to *n*<=-<=1 can run to another room but not further than *d* rooms away from her current room, or stay in place. Each student can optionally hide under a bed. - Instructors move from room 1 to room 2 and from room *n* to room *n*<=-<=1. - This process continues until all rooms are processed.
Let *x*1 denote the number of rooms in which the first instructor counted the number of non-hidden students different from *b*, and *x*2 be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers *x**i*. Help them find this value if they use the optimal strategy.
Input Specification:
The first line contains three integers *n*, *d* and *b* (2<=β€<=*n*<=β€<=100<=000, 1<=β€<=*d*<=β€<=*n*<=-<=1, 1<=β€<=*b*<=β€<=10<=000), number of rooms in the house, running distance of a student, official number of students in a room.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=109), *i*-th of which stands for the number of students in the *i*-th room before curfew announcement.
It is guaranteed that *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*.
Output Specification:
Output one integer, the minimal possible value of the maximum of *x**i*.
Demo Input:
['5 1 1\n1 0 0 0 4\n', '6 1 2\n3 8 0 1 0 0\n']
Demo Output:
['1\n', '2\n']
Note:
In the first sample the first three rooms are processed by the first instructor, and the last two are processed by the second instructor. One of the optimal strategies is the following: firstly three students run from room 5 to room 4, on the next stage two of them run to room 3, and one of those two hides under a bed. This way, the first instructor writes down room 2, and the second writes down nothing.
In the second sample one of the optimal strategies is the following: firstly all students in room 1 hide, all students from room 2 run to room 3. On the next stage one student runs from room 3 to room 4, and 5 students hide. This way, the first instructor writes down rooms 1 and 2, the second instructor writes down rooms 5 and 6.
| 587
|
Title: Interesting Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We'll call an array of *n* non-negative integers *a*[1],<=*a*[2],<=...,<=*a*[*n*] interesting, if it meets *m* constraints. The *i*-th of the *m* constraints consists of three integers *l**i*, *r**i*, *q**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*) meaning that value should be equal to *q**i*.
Your task is to find any interesting array of *n* elements or state that such array doesn't exist.
Expression *x*&*y* means the bitwise AND of numbers *x* and *y*. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β as "and".
Input Specification:
The first line contains two integers *n*, *m* (1<=β€<=*n*<=β€<=105, 1<=β€<=*m*<=β€<=105)Β β the number of elements in the array and the number of limits.
Each of the next *m* lines contains three integers *l**i*, *r**i*, *q**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*, 0<=β€<=*q**i*<=<<=230) describing the *i*-th limit.
Output Specification:
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print *n* integers *a*[1],<=*a*[2],<=...,<=*a*[*n*] (0<=β€<=*a*[*i*]<=<<=230)Β decribing the interesting array. If there are multiple answers, print any of them.
If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
Demo Input:
['3 1\n1 3 3\n', '3 2\n1 3 3\n1 3 2\n']
Demo Output:
['YES\n3 3 3\n', 'NO\n']
Note:
none
| 588
|
Title: Coat of Anticubism
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive β convex polygon.
Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The *i*-th rod is a segment of length *l**i*.
The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .
Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.
Help sculptor!
Input Specification:
The first line contains an integer *n* (3<=β€<=*n*<=β€<=105) β a number of rod-blanks.
The second line contains *n* integers *l**i* (1<=β€<=*l**i*<=β€<=109) β lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with *n* vertices and nonzero area using the rods Cicasso already has.
Output Specification:
Print the only integer *z* β the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (*n*<=+<=1) vertices and nonzero area from all of the rods.
Demo Input:
['3\n1 2 1\n', '5\n20 4 3 2 1\n']
Demo Output:
['1\n', '11\n']
Note:
In the first example triangle with sides {1β+β1β=β2,β2,β1} can be formed from a set of lengths {1,β1,β1,β2}.
In the second example you can make a triangle with lengths {20,β11,β4β+β3β+β2β+β1β=β10}.
| 589
|
Title: Strip
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alexandra has a paper strip with *n* numbers on it. Let's call them *a**i* from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
- Each piece should contain at least *l* numbers.- The difference between the maximal and the minimal number on the piece should be at most *s*.
Please help Alexandra to find the minimal number of pieces meeting the condition above.
Input Specification:
The first line contains three space-separated integers *n*,<=*s*,<=*l* (1<=β€<=*n*<=β€<=105,<=0<=β€<=*s*<=β€<=109,<=1<=β€<=*l*<=β€<=105).
The second line contains *n* integers *a**i* separated by spaces (<=-<=109<=β€<=*a**i*<=β€<=109).
Output Specification:
Output the minimal number of strip pieces.
If there are no ways to split the strip, output -1.
Demo Input:
['7 2 2\n1 3 1 2 4 1 2\n', '7 2 2\n1 100 1 100 1 100 1\n']
Demo Output:
['3\n', '-1\n']
Note:
For the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].
For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.
| 590
|
Title: Broken Monitor
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Innocentius has a problem β his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.
Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention".
Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that:
- the frame's width is 1 pixel, - the frame doesn't go beyond the borders of the screen, - all white pixels of the monitor are located on the frame, - of all frames that satisfy the previous three conditions, the required frame must have the smallest size.
Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is *d*<==<=3, then it consists of 8 pixels, if its size is *d*<==<=2, then it contains 4 pixels and if *d*<==<=1, then the frame is reduced to a single pixel.
Input Specification:
The first line contains the resolution of the monitor as a pair of integers *n*, *m* (1<=β€<=*n*,<=*m*<=β€<=2000). The next *n* lines contain exactly *m* characters each β the state of the monitor pixels at the moment of the game. Character "." (period, ASCII code 46) corresponds to the black pixel, and character "w" (lowercase English letter w) corresponds to the white pixel. It is guaranteed that at least one pixel of the monitor is white.
Output Specification:
Print the monitor screen. Represent the sought frame by characters "+" (the "plus" character). The pixels that has become white during the game mustn't be changed. Print them as "w". If there are multiple possible ways to position the frame of the minimum size, print any of them.
If the required frame doesn't exist, then print a single line containing number -1.
Demo Input:
['4 8\n..w..w..\n........\n........\n..w..w..\n', '5 6\n......\n.w....\n......\n..w...\n......\n', '2 4\n....\n.w..\n', '2 6\nw..w.w\n...w..\n']
Demo Output:
['..w++w..\n..+..+..\n..+..+..\n..w++w..\n', '......\n+w+...\n+.+...\n++w...\n......\n', '....\n.w..\n', '-1\n']
Note:
In the first sample the required size of the optimal frame equals 4. In the second sample the size of the optimal frame equals 3. In the third sample, the size of the optimal frame is 1. In the fourth sample, the required frame doesn't exist.
| 591
|
Title: Deciphering
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Maria Ivanovna found a Sasha's piece of paper with a message dedicated to Olya. Maria Ivanovna wants to know what is there in a message, but unfortunately the message is ciphered. Maria Ivanovna knows that her students usually cipher their messages by replacing each letter of an original message by some another letter. Replacement works in such way that same letters are always replaced with some fixed letter, and different letters are always replaced by different letters.
Maria Ivanovna supposed that the message contains answers to the final exam (since its length is equal to the number of final exam questions). On the other hand she knows that Sasha's answer are not necessary correct. There are *K* possible answers for each questions. Of course, Maria Ivanovna knows correct answers.
Maria Ivanovna decided to decipher message in such way that the number of Sasha's correct answers is maximum possible. She is very busy now, so your task is to help her.
Input Specification:
First line contains length of both strings *N* (1<=β€<=*N*<=β€<=2<=000<=000) and an integer *K*Β β number of possible answers for each of the questions (1<=β€<=*K*<=β€<=52). Answers to the questions are denoted as Latin letters abcde...xyzABCDE...XYZ in the order. For example for *K*<==<=6, possible answers are abcdef and for *K*<==<=30 possible answers are abcde...xyzABCD.
Second line contains a ciphered message string consisting of Latin letters.
Third line contains a correct answers string consisting of Latin letters.
Output Specification:
In the first line output maximum possible number of correct Sasha's answers.
In the second line output cipher rule as the string of length *K* where for each letter from the students' cipher (starting from 'a' as mentioned above) there is specified which answer does it correspond to.
If there are several ways to produce maximum answer, output any of them.
Demo Input:
['10 2\naaabbbaaab\nbbbbabbbbb\n', '10 2\naaaaaaabbb\nbbbbaaabbb\n', '9 4\ndacbdacbd\nacbdacbda\n']
Demo Output:
['7\nba\n', '6\nab\n', '9\ncdba\n']
Note:
none
| 592
|
Title: Flag Day
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In Berland, there is the national holiday coming β the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:
- overall, there must be *m* dances;- exactly three people must take part in each dance;- each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland).
The agency has *n* dancers, and their number can be less than 3*m*. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance.
You considered all the criteria and made the plan for the *m* dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the *n* dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
Input Specification:
The first line contains two space-separated integers *n* (3<=β€<=*n*<=β€<=105) and *m* (1<=β€<=*m*<=β€<=105) β the number of dancers and the number of dances, correspondingly. Then *m* lines follow, describing the dances in the order of dancing them. The *i*-th line contains three distinct integers β the numbers of the dancers that take part in the *i*-th dance. The dancers are numbered from 1 to *n*. Each dancer takes part in at least one dance.
Output Specification:
Print *n* space-separated integers: the *i*-th number must represent the color of the *i*-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
Demo Input:
['7 3\n1 2 3\n1 4 5\n4 6 7\n', '9 3\n3 6 9\n2 5 8\n1 4 7\n', '5 2\n4 1 5\n3 1 2\n']
Demo Output:
['1 2 3 3 2 2 1 \n', '1 1 1 2 2 2 3 3 3 \n', '2 3 1 1 3 \n']
Note:
none
| 593
|
Title: Fedor and coupons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.
The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has *n* discount coupons, the *i*-th of them can be used with products with ids ranging from *l**i* to *r**i*, inclusive. Today Fedor wants to take exactly *k* coupons with him.
Fedor wants to choose the *k* coupons in such a way that the number of such products *x* that all coupons can be used with this product *x* is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*k*<=β€<=*n*<=β€<=3Β·105)Β β the number of coupons Fedor has, and the number of coupons he wants to choose.
Each of the next *n* lines contains two integers *l**i* and *r**i* (<=-<=109<=β€<=*l**i*<=β€<=*r**i*<=β€<=109)Β β the description of the *i*-th coupon. The coupons can be equal.
Output Specification:
In the first line print single integerΒ β the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted.
In the second line print *k* distinct integers *p*1,<=*p*2,<=...,<=*p**k* (1<=β€<=*p**i*<=β€<=*n*)Β β the ids of the coupons which Fedor should choose.
If there are multiple answers, print any of them.
Demo Input:
['4 2\n1 100\n40 70\n120 130\n125 180\n', '3 2\n1 12\n15 20\n25 30\n', '5 2\n1 10\n5 15\n14 50\n30 70\n99 100\n']
Demo Output:
['31\n1 2 \n', '0\n1 2 \n', '21\n3 4 \n']
Note:
In the first example if we take the first two coupons then all the products with ids in range [40,β70] can be bought with both coupons. There are 31 products in total.
In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.
| 594
|
Title: Cyclical Quest
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Some days ago, WJMZBMR learned how to answer the query "how many times does a string *x* occur in a string *s*" quickly by preprocessing the string *s*. But now he wants to make it harder.
So he wants to ask "how many consecutive substrings of *s* are cyclical isomorphic to a given string *x*". You are given string *s* and *n* strings *x**i*, for each string *x**i* find, how many consecutive substrings of *s* are cyclical isomorphic to *x**i*.
Two strings are called cyclical isomorphic if one can rotate one string to get the other one. 'Rotate' here means 'to take some consecutive chars (maybe none) from the beginning of a string and put them back at the end of the string in the same order'. For example, string "abcde" can be rotated to string "deabc". We can take characters "abc" from the beginning and put them at the end of "de".
Input Specification:
The first line contains a non-empty string *s*. The length of string *s* is not greater than 106 characters.
The second line contains an integer *n* (1<=β€<=*n*<=β€<=105) β the number of queries. Then *n* lines follow: the *i*-th line contains the string *x**i* β the string for the *i*-th query. The total length of *x**i* is less than or equal to 106 characters.
In this problem, strings only consist of lowercase English letters.
Output Specification:
For each query *x**i* print a single integer that shows how many consecutive substrings of *s* are cyclical isomorphic to *x**i*. Print the answers to the queries in the order they are given in the input.
Demo Input:
['baabaabaaa\n5\na\nba\nbaa\naabaa\naaba\n', 'aabbaa\n3\naa\naabb\nabba\n']
Demo Output:
['7\n5\n7\n3\n5\n', '2\n3\n3\n']
Note:
none
| 595
|
Title: Lucky Tickets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such tickets and moved on to a more general question. Now he explores *k*-lucky tickets.
Pollard sais that a ticket is *k*-lucky if we can add arithmetic operation signs between its digits to the left or right of them (i.e., "+", "-", "<=Γ<=") and brackets so as to obtain the correct arithmetic expression whose value would equal *k*. For example, ticket "224201016" is 1000-lucky as (<=-<=2<=-<=(2<=+<=4))<=Γ<=(2<=+<=0)<=+<=1016<==<=1000.
Pollard was so carried away by the lucky tickets that he signed up for a seminar on lucky tickets and, as far as Gerald knows, Pollard will attend it daily at 7 pm in some famous institute and will commute to it in the same tram for *m* days. In this tram tickets have eight digits. And Gerald wants to make a surprise for Pollard: each day Pollard will receive a tram *k*-lucky ticket. The conductor has already agreed to give Pollard certain tickets during all these *m* days and he only wants Gerald to tell him what kind of tickets to give out. In this regard, help Gerald pick exactly *m* distinct *k*-lucky tickets.
Input Specification:
The single line contains two integers *k* and *m* (0<=β€<=*k*<=β€<=104, 1<=β€<=*m*<=β€<=3Β·105).
Output Specification:
Print *m* lines. Each line must contain exactly 8 digits β the *k*-winning ticket. The tickets may begin with 0, all tickets must be distinct. If there are more than *m* distinct *k*-lucky tickets, print any *m* of them. It is guaranteed that at least *m* distinct *k*-lucky tickets exist. The tickets can be printed in any order.
Demo Input:
['0 3\n', '7 4\n']
Demo Output:
['00000000\n00000001\n00000002\n', '00000007\n00000016\n00000017\n00000018\n']
Note:
none
| 596
|
Title: Oleg and shares
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Oleg the bank client checks share prices every day. There are *n* share prices he is interested in. Today he observed that each second exactly one of these prices decreases by *k* rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all *n* prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*n*<=β€<=105,<=1<=β€<=*k*<=β€<=109)Β β the number of share prices, and the amount of rubles some price decreases each second.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109)Β β the initial prices.
Output Specification:
Print the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.
Demo Input:
['3 3\n12 9 15\n', '2 2\n10 9\n', '4 1\n1 1000000000 1000000000 1000000000\n']
Demo Output:
['3', '-1', '2999999997']
Note:
Consider the first example.
Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.
There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.
In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.
In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999β*β3β=β2999999997 seconds. We can note that this is the minimum possible time.
| 597
|
Title: The Useless Toy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadaysΒ β caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.
Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one):
After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.
Slastyona managed to have spinner rotating for exactly *n* seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.
Input Specification:
There are two characters in the first stringΒ β the starting and the ending position of a spinner. The position is encoded with one of the following characters: v (ASCII code 118, lowercase v), < (ASCII code 60), ^ (ASCII code 94) or > (ASCII code 62) (see the picture above for reference). Characters are separated by a single space.
In the second strings, a single number *n* is given (0<=β€<=*n*<=β€<=109)Β β the duration of the rotation.
It is guaranteed that the ending position of a spinner is a result of a *n* second spin in any of the directions, assuming the given starting position.
Output Specification:
Output cw, if the direction is clockwise, ccwΒ β if counter-clockwise, and undefined otherwise.
Demo Input:
['^ >\n1\n', '< ^\n3\n', '^ v\n6\n']
Demo Output:
['cw\n', 'ccw\n', 'undefined\n']
Note:
none
| 598
|
Title: none
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (*x*,<=*y*) to (*x*<=-<=1,<=*y*) or (*x*,<=*y*<=-<=1). Vasiliy can move his pawn from (*x*,<=*y*) to one of cells: (*x*<=-<=1,<=*y*),<=(*x*<=-<=1,<=*y*<=-<=1) and (*x*,<=*y*<=-<=1). Both players are also allowed to skip move.
There are some additional restrictions β a player is forbidden to move his pawn to a cell with negative *x*-coordinate or *y*-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0,<=0).
You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
Input Specification:
The first line contains four integers: *x**p*,<=*y**p*,<=*x**v*,<=*y**v* (0<=β€<=*x**p*,<=*y**p*,<=*x**v*,<=*y**v*<=β€<=105) β Polycarp's and Vasiliy's starting coordinates.
It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0,<=0).
Output Specification:
Output the name of the winner: "Polycarp" or "Vasiliy".
Demo Input:
['2 1 2 2\n', '4 7 7 4\n']
Demo Output:
['Polycarp\n', 'Vasiliy\n']
Note:
In the first sample test Polycarp starts in (2,β1) and will move to (1,β1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1,β0) and finally to (0,β0) in the third turn.
| 599
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.