contestId
int64
0
1.01k
name
stringlengths
2
58
tags
listlengths
0
11
title
stringclasses
523 values
time-limit
stringclasses
8 values
memory-limit
stringclasses
8 values
problem-description
stringlengths
0
7.15k
input-specification
stringlengths
0
2.05k
output-specification
stringlengths
0
1.5k
demo-input
listlengths
0
7
demo-output
listlengths
0
7
note
stringlengths
0
5.24k
test_cases
listlengths
0
402
timeConsumedMillis
int64
0
8k
memoryConsumedBytes
int64
0
537M
score
float64
-1
3.99
__index_level_0__
int64
0
621k
105
Entertaining Geodetics
[ "brute force", "dsu", "implementation" ]
D. Entertaining Geodetics
1
256
The maps in the game are divided into square cells called Geo Panels. Some of these panels are painted. We shall assume that the Geo Panels without color are painted the transparent color. Besides, the map has so-called Geo Symbols. They look like pyramids of different colors (including Geo Symbols of the transparent color). Each Geo Symbol is located on one Geo Panel, and each Geo Panel may contain no more than one Geo Symbol. Geo Symbols can be eliminated. To understand better what happens when a Geo Symbol is eliminated, let us introduce some queue to which we will put the recently eliminated Geo Symbols. Let's put at the head of the queue a Geo Symbol that was eliminated just now. Next, we will repeat the following operation: Extract the Geo Symbol from the queue. Look at the color of the panel containing the given Geo Symbol. If it differs from transparent and differs from the color of the Geo Symbol, then all Geo Panels of this color are repainted in the color of the given Geo Symbol (transparent Geo Symbols repaint the Geo Panels transparent). Repainting is executed in an infinite spiral strictly in the following order starting from the panel, which contained the Geo Symbol: In other words, we select all the panels that need to be repainted and find their numbers in the infinite spiral whose center is placed in the position of the given Geo Symbol. After that, we repaint them in the order of the number's increasing. If a panel contains another Geo Symbol and this panel is being repainted, then the Geo Symbol is removed from the field and placed at the tail of the queue. After repainting the Geo Symbol is completely eliminated and the next Geo Symbol is taken from the head of the queue (if there is any) and the process repeats. The process ends if the queue is empty. See the sample analysis for better understanding. You know the colors of all the Geo Panels and the location of all the Geo Symbols. Determine the number of repaintings, which will occur if you destroy one of the Geo Symbols.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=300) — the height and the width of the map (in cells). Then follow *n* line; each of them contains *m* numbers — the Geo Panels' colors. Then follow *n* more lines; each of them contains *m* numbers — the Geo Symbols' description. -1 means that the given position contains no Geo Symbol. Otherwise, the number represents the color of the Geo Symbol in the given position. All colors are integers from 0 to 109. 0 represents the transparent color. The last line contains two integers *x* and *y* (1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m*) — the row and the column where the Geo Symbol is placed that needs to be eliminated. The rows are numbered from top to bottom, the columns are numbered from left to right. Coordinates are 1-based. It is guaranteed that the position with coordinates (*x*,<=*y*) contains a Geo Symbol.
Print the single number — the total number of repaintings after the Geo Symbol is eliminated. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cout stream (you may also use the %I64d specificator).
[ "5 5\n9 0 1 1 0\n0 0 3 2 0\n1 1 1 3 0\n1 1 1 3 0\n0 1 2 0 3\n-1 1 -1 3 -1\n-1 -1 -1 0 -1\n-1 -1 -1 -1 -1\n-1 2 3 -1 -1\n-1 -1 -1 -1 2\n4 2\n" ]
[ "35" ]
All actions of the sample you can see on the following picture: http://assets.codeforces.com/images/geo_slow.gif
[]
46
0
0
38,012
0
none
[ "none" ]
null
null
I won't feel lonely, nor will I be sorrowful... not before everything is buried. A string of *n* beads is left as the message of leaving. The beads are numbered from 1 to *n* from left to right, each having a shape numbered by integers between 1 and *n* inclusive. Some beads may have the same shapes. The memory of a shape *x* in a certain subsegment of beads, is defined to be the difference between the last position and the first position that shape *x* appears in the segment. The memory of a subsegment is the sum of memories over all shapes that occur in it. From time to time, shapes of beads change as well as the memories. Sometimes, the past secreted in subsegments are being recalled, and you are to find the memory for each of them.
The first line of input contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — the number of beads in the string, and the total number of changes and queries, respectively. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the initial shapes of beads 1,<=2,<=...,<=*n*, respectively. The following *m* lines each describes either a change in the beads or a query of subsegment. A line has one of the following formats: - 1 p x (1<=≤<=*p*<=≤<=*n*, 1<=≤<=*x*<=≤<=*n*), meaning that the shape of the *p*-th bead is changed into *x*; - 2 l r (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), denoting a query of memory of the subsegment from *l* to *r*, inclusive.
For each query, print one line with an integer — the memory of the recalled subsegment.
[ "7 6\n1 2 3 1 3 2 1\n2 3 7\n2 1 3\n1 7 2\n1 3 2\n2 1 6\n2 5 7\n", "7 5\n1 3 2 1 4 2 3\n1 1 4\n2 2 3\n1 1 7\n2 4 5\n1 1 7\n" ]
[ "5\n0\n7\n1\n", "0\n0\n" ]
The initial string of beads has shapes (1, 2, 3, 1, 3, 2, 1). Consider the changes and queries in their order: 1. 2 3 7: the memory of the subsegment [3, 7] is (7 - 4) + (6 - 6) + (5 - 3) = 5; 1. 2 1 3: the memory of the subsegment [1, 3] is (1 - 1) + (2 - 2) + (3 - 3) = 0; 1. 1 7 2: the shape of the 7-th bead changes into 2. Beads now have shapes (1, 2, 3, 1, 3, 2, 2) respectively; 1. 1 3 2: the shape of the 3-rd bead changes into 2. Beads now have shapes (1, 2, 2, 1, 3, 2, 2) respectively; 1. 2 1 6: the memory of the subsegment [1, 6] is (4 - 1) + (6 - 2) + (5 - 5) = 7; 1. 2 5 7: the memory of the subsegment [5, 7] is (7 - 6) + (5 - 5) = 1.
[]
6,000
512,000
0
38,141
0
none
[ "none" ]
null
null
Arkady the air traffic controller is now working with *n* planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point 0 on it. The *i*-th plane, small enough to be represented by a point, currently has a coordinate of *x**i* and is moving with speed *v**i*. It's guaranteed that *x**i*·*v**i*<=&lt;<=0, i.e., all planes are moving towards the station. Occasionally, the planes are affected by winds. With a wind of speed *v**wind* (not necessarily positive or integral), the speed of the *i*-th plane becomes *v**i*<=+<=*v**wind*. According to weather report, the current wind has a steady speed falling inside the range [<=-<=*w*,<=*w*] (inclusive), but the exact value cannot be measured accurately since this value is rather small — smaller than the absolute value of speed of any plane. Each plane should contact Arkady at the exact moment it passes above his station. And you are to help Arkady count the number of pairs of planes (*i*,<=*j*) (*i*<=&lt;<=*j*) there are such that there is a possible value of wind speed, under which planes *i* and *j* contact Arkady at the same moment. This value needn't be the same across different pairs. The wind speed is the same for all planes. You may assume that the wind has a steady speed and lasts arbitrarily long.
The first line contains two integers *n* and *w* (1<=≤<=*n*<=≤<=100<=000, 0<=≤<=*w*<=&lt;<=105) — the number of planes and the maximum wind speed. The *i*-th of the next *n* lines contains two integers *x**i* and *v**i* (1<=≤<=|*x**i*|<=≤<=105, *w*<=+<=1<=≤<=|*v**i*|<=≤<=105, *x**i*·*v**i*<=&lt;<=0) — the initial position and speed of the *i*-th plane. Planes are pairwise distinct, that is, no pair of (*i*,<=*j*) (*i*<=&lt;<=*j*) exists such that both *x**i*<==<=*x**j* and *v**i*<==<=*v**j*.
Output a single integer — the number of unordered pairs of planes that can contact Arkady at the same moment.
[ "5 1\n-3 2\n-3 3\n-1 2\n1 -3\n3 -5\n", "6 1\n-3 2\n-2 2\n-1 2\n1 -2\n2 -2\n3 -2\n" ]
[ "3\n", "9\n" ]
In the first example, the following 3 pairs of planes satisfy the requirements: - (2, 5) passes the station at time 3 / 4 with *v*<sub class="lower-index">*wind*</sub> = 1; - (3, 4) passes the station at time 2 / 5 with *v*<sub class="lower-index">*wind*</sub> = 1 / 2; - (3, 5) passes the station at time 4 / 7 with *v*<sub class="lower-index">*wind*</sub> =  - 1 / 4. In the second example, each of the 3 planes with negative coordinates can form a valid pair with each of the other 3, totaling 9 pairs.
[]
77
7,065,600
0
38,160
566
Restructuring Company
[ "data structures", "dsu" ]
null
null
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company. There are *n* people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of *n* departments, one person in each). However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use *team*(*person*) to represent a team where person *person* works. A crisis manager can make decisions of two types: 1. Merge departments *team*(*x*) and *team*(*y*) into one large department containing all the employees of *team*(*x*) and *team*(*y*), where *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*) — are numbers of two of some company employees. If *team*(*x*) matches *team*(*y*), then nothing happens. 1. Merge departments *team*(*x*),<=*team*(*x*<=+<=1),<=...,<=*team*(*y*), where *x* and *y* (1<=≤<=*x*<=≤<=*y*<=≤<=*n*) — the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*) work at the same department. Help the crisis manager and answer all of his queries.
The first line of the input contains two integers *n* and *q* (1<=≤<=*n*<=≤<=200<=000, 1<=≤<=*q*<=≤<=500<=000) — the number of the employees of the company and the number of queries the crisis manager has. Next *q* lines contain the queries of the crisis manager. Each query looks like *type* *x* *y*, where . If *type*<==<=1 or *type*<==<=2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If *type*<==<=3, then your task is to determine whether employees *x* and *y* work at the same department. Note that *x* can be equal to *y* in the query of any type.
For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.
[ "8 6\n3 2 5\n1 2 5\n3 2 5\n2 4 7\n2 1 2\n3 1 7\n" ]
[ "NO\nYES\nYES\n" ]
none
[ { "input": "8 6\n3 2 5\n1 2 5\n3 2 5\n2 4 7\n2 1 2\n3 1 7", "output": "NO\nYES\nYES" }, { "input": "1 1\n3 1 1", "output": "YES" }, { "input": "1 3\n1 1 1\n2 1 1\n3 1 1", "output": "YES" } ]
1,638
21,094,400
-1
38,162
24
Sequence of points
[ "geometry", "implementation", "math" ]
C. Sequence of points
2
256
You are given the following points with integer coordinates on the plane: *M*0,<=*A*0,<=*A*1,<=...,<=*A**n*<=-<=1, where *n* is odd number. Now we define the following infinite sequence of points *M**i*: *M**i* is symmetric to *M**i*<=-<=1 according (for every natural number *i*). Here point *B* is symmetric to *A* according *M*, if *M* is the center of the line segment *AB*. Given index *j* find the point *M**j*.
On the first line you will be given an integer *n* (1<=≤<=*n*<=≤<=105), which will be odd, and *j* (1<=≤<=*j*<=≤<=1018), where *j* is the index of the desired point. The next line contains two space separated integers, the coordinates of *M*0. After that *n* lines follow, where the *i*-th line contain the space separated integer coordinates of the point *A**i*<=-<=1. The absolute values of all input coordinates will not be greater then 1000.
On a single line output the coordinates of *M**j*, space separated.
[ "3 4\n0 0\n1 1\n2 3\n-5 3\n", "3 1\n5 5\n1000 1000\n-1000 1000\n3 100\n" ]
[ "14 0\n", "1995 1995\n" ]
none
[ { "input": "3 4\n0 0\n1 1\n2 3\n-5 3", "output": "14 0" }, { "input": "3 1\n5 5\n1000 1000\n-1000 1000\n3 100", "output": "1995 1995" }, { "input": "1 1\n-1000 -1000\n1000 1000", "output": "3000 3000" }, { "input": "1 1000000000000000000\n-1000 1000\n1000 -1000", "output"...
592
4,710,400
3.843226
38,177
363
Fixing Typos
[ "greedy", "implementation" ]
null
null
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos. In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos). Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
The single line of the input contains word *s*, its length is from 1 to 200000 characters. The given word *s* consists of lowercase English letters.
Print such word *t* that it doesn't contain any typos described in the problem statement and is obtained from *s* by deleting the least number of letters. If there are multiple solutions, print any of them.
[ "helloo\n", "woooooow\n" ]
[ "hello\n", "woow\n" ]
The second valid answer to the test from the statement is "heloo".
[ { "input": "helloo", "output": "hello" }, { "input": "woooooow", "output": "woow" }, { "input": "aabbaa", "output": "aabaa" }, { "input": "yesssssss", "output": "yess" }, { "input": "aabbaabbaabbaabbaabbaabbcccccc", "output": "aabaabaabaabaabaabcc" }, { ...
93
16,896,000
3
38,233
568
New Language
[ "2-sat", "greedy" ]
null
null
Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed. After some time, the wise men returned from the trip even wiser. They locked up for six months in the dining room, after which they said to the king: "there are a lot of different languages, but almost all of them have letters that are divided into vowels and consonants; in a word, vowels and consonants must be combined correctly." There are very many rules, all of them have exceptions, but our language will be deprived of such defects! We propose to introduce a set of formal rules of combining vowels and consonants, and include in the language all the words that satisfy them. The rules of composing words are: - The letters are divided into vowels and consonants in some certain way;- All words have a length of exactly *n*;- There are *m* rules of the form (*pos*1,<=*t*1,<=*pos*2,<=*t*2). Each rule is: if the position *pos*1 has a letter of type *t*1, then the position *pos*2 has a letter of type *t*2. You are given some string *s* of length *n*, it is not necessarily a correct word of the new language. Among all the words of the language that lexicographically not smaller than the string *s*, find the minimal one in lexicographic order.
The first line contains a single line consisting of letters 'V' (Vowel) and 'C' (Consonant), determining which letters are vowels and which letters are consonants. The length of this string *l* is the size of the alphabet of the new language (1<=≤<=*l*<=≤<=26). The first *l* letters of the English alphabet are used as the letters of the alphabet of the new language. If the *i*-th character of the string equals to 'V', then the corresponding letter is a vowel, otherwise it is a consonant. The second line contains two integers *n*, *m* (1<=≤<=*n*<=≤<=200, 0<=≤<=*m*<=≤<=4*n*(*n*<=-<=1)) — the number of letters in a single word and the number of rules, correspondingly. Next *m* lines describe *m* rules of the language in the following format: *pos*1,<=*t*1,<=*pos*2,<=*t*2 (1<=≤<=*pos*1,<=*pos*2<=≤<=*n*, *pos*1<=≠<=*pos*2, 'V', 'C' }). The last line contains string *s* of length *n*, consisting of the first *l* small letters of the English alphabet. It is guaranteed that no two rules are the same.
Print a smallest word of a language that is lexicographically not smaller than *s*. If such words does not exist (for example, if the language has no words at all), print "-1" (without the quotes).
[ "VC\n2 1\n1 V 2 C\naa\n", "VC\n2 1\n1 C 2 V\nbb\n", "VCC\n4 3\n1 C 2 V\n2 C 3 V\n3 V 4 V\nabac\n" ]
[ "ab\n", "-1\n", "acaa\n" ]
In the first test word "aa" is not a word of the language, but word "ab" is. In the second test out of all four possibilities only word "bb" is not a word of a language, but all other words are lexicographically less, so there is no answer. In the third test, due to the last rule, "abac" doesn't belong to the language ("a" is a vowel, "c" is a consonant). The only word with prefix "ab" that meets the given rules is "abaa". But it is less than "abac", so the answer will be "acaa"
[]
0
0
-1
38,351
213
Relay Race
[ "dp" ]
null
null
Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of *n* meters. The given square is split into *n*<=×<=*n* cells (represented as unit squares), each cell has some number. At the beginning of the race Furik stands in a cell with coordinates (1,<=1), and Rubik stands in a cell with coordinates (*n*,<=*n*). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (*i*,<=*j*), then he can move to cell (*i*<=+<=1,<=*j*) or (*i*,<=*j*<=+<=1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (*n*,<=*n*) to cell with coordinates (1,<=1). If Rubik stands in cell (*i*,<=*j*), then he can move to cell (*i*<=-<=1,<=*j*) or (*i*,<=*j*<=-<=1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum. Print the maximum number of points Furik and Rubik can earn on the relay race.
The first line contains a single integer (1<=≤<=*n*<=≤<=300). The next *n* lines contain *n* integers each: the *j*-th number on the *i*-th line *a**i*,<=*j* (<=-<=1000<=≤<=*a**i*,<=*j*<=≤<=1000) is the number written in the cell with coordinates (*i*,<=*j*).
On a single line print a single number — the answer to the problem.
[ "1\n5\n", "2\n11 14\n16 12\n", "3\n25 16 25\n12 18 19\n11 13 8\n" ]
[ "5\n", "53\n", "136\n" ]
Comments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample:
[ { "input": "1\n5", "output": "5" }, { "input": "2\n11 14\n16 12", "output": "53" }, { "input": "3\n25 16 25\n12 18 19\n11 13 8", "output": "136" }, { "input": "4\n35 2 38 10\n15 19 31 32\n21 19 22 15\n37 33 2 13", "output": "274" }, { "input": "5\n4 32 1 18 41\n47...
122
6,656,000
0
38,362
11
Forward, march!
[ "binary search", "dp", "greedy" ]
E. Forward, march!
1
64
Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases. When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually). Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme.
The first line of input contains a sequence consisting only of characters 'L', 'R' and 'X', where 'L' corresponds to a step with the left foot, 'R' — with the right foot, and 'X' — to a break. The length of the sequence will not exceed 106.
Output the maximum percentage of time that Jack can spend marching correctly, rounded down to exactly six digits after the decimal point.
[ "X\n", "LXRR\n" ]
[ "0.000000\n", "50.000000\n" ]
In the second example, if we add two breaks to receive LXXRXR, Jack will march: LXXRXRLXXRXRL... instead of LRLRLRLRLRLRL... and will make the correct step in half the cases. If we didn't add any breaks, the sequence would be incorrect — Jack can't step on his right foot twice in a row.
[ { "input": "X", "output": "0.000000" }, { "input": "LXRR", "output": "50.000000" }, { "input": "LXRR", "output": "50.000000" }, { "input": "LLXRXLXRLR", "output": "50.000000" }, { "input": "RXRRXXXRXXRR", "output": "37.500000" }, { "input": "LLLRLXRXLL...
748
49,152,000
0
38,484
280
Maximum Xor Secondary
[ "data structures", "implementation", "two pointers" ]
null
null
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers *x*1,<=*x*2,<=...,<=*x**k* (*k*<=&gt;<=1) is such maximum element *x**j*, that the following inequality holds: . The lucky number of the sequence of distinct positive integers *x*1,<=*x*2,<=...,<=*x**k* (*k*<=&gt;<=1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence. You've got a sequence of distinct positive integers *s*1,<=*s*2,<=...,<=*s**n* (*n*<=&gt;<=1). Let's denote sequence *s**l*,<=*s**l*<=+<=1,<=...,<=*s**r* as *s*[*l*..*r*] (1<=≤<=*l*<=&lt;<=*r*<=≤<=*n*). Your task is to find the maximum number among all lucky numbers of sequences *s*[*l*..*r*]. Note that as all numbers in sequence *s* are distinct, all the given definitions make sence.
The first line contains integer *n* (1<=&lt;<=*n*<=≤<=105). The second line contains *n* distinct integers *s*1,<=*s*2,<=...,<=*s**n* (1<=≤<=*s**i*<=≤<=109).
Print a single integer — the maximum lucky number among all lucky numbers of sequences *s*[*l*..*r*].
[ "5\n5 2 1 4 3\n", "5\n9 8 3 5 7\n" ]
[ "7\n", "15\n" ]
For the first sample you can choose *s*[4..5] = {4, 3} and its lucky number is (4 *xor* 3) = 7. You can also choose *s*[1..2]. For the second sample you must choose *s*[2..5] = {8, 3, 5, 7}.
[ { "input": "5\n5 2 1 4 3", "output": "7" }, { "input": "5\n9 8 3 5 7", "output": "15" }, { "input": "10\n76969694 71698884 32888447 31877010 65564584 87864180 7850891 1505323 17879621 15722446", "output": "128869996" }, { "input": "10\n4547989 39261040 94929326 38131456 26174...
93
6,656,000
0
38,585
85
Petya and Tree
[ "binary search", "dfs and similar", "probabilities", "sortings", "trees" ]
C. Petya and Tree
3
256
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up. Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node. Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result. It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
The first line contains an odd integer *n* (3<=≤<=*n*<=&lt;<=105), which represents the number of tree nodes. Next *n* lines contain node descriptions. The (*i*<=+<=1)-th line contains two space-separated integers. The first number is the number of parent of the *i*-st node and the second number is the key lying in the *i*-th node. The next line contains an integer *k* (1<=≤<=*k*<=≤<=105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next *k* lines contain the actual keys, one key per line. All node keys and all search keys are positive integers, not exceeding 109. All *n*<=+<=*k* keys are distinct. All nodes are numbered from 1 to *n*. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.
Print *k* real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10<=-<=9.
[ "7\n-1 8\n1 4\n1 12\n2 2\n2 6\n3 10\n3 14\n1\n1\n", "3\n-1 5\n1 3\n1 7\n6\n1\n2\n4\n6\n8\n9\n" ]
[ "8.0000000000\n", "7.0000000000\n7.0000000000\n7.0000000000\n3.0000000000\n3.0000000000\n3.0000000000\n" ]
In the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8.
[]
60
0
0
38,676
1,005
Median on Segments (General Case Edition)
[ "sortings" ]
null
null
You are given an integer sequence $a_1, a_2, \dots, a_n$. Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$. The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used. For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence. Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$.
The first line contains integers $n$ and $m$ ($1 \le n,m \le 2\cdot10^5$) — the length of the given sequence and the required value of the median. The second line contains an integer sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2\cdot10^5$).
Print the required number.
[ "5 4\n1 4 5 60 4\n", "3 1\n1 1 1\n", "15 2\n1 2 3 1 2 3 1 2 3 1 2 3 1 2 3\n" ]
[ "8\n", "6\n", "97\n" ]
In the first example, the suitable pairs of indices are: $(1, 3)$, $(1, 4)$, $(1, 5)$, $(2, 2)$, $(2, 3)$, $(2, 5)$, $(4, 5)$ and $(5, 5)$.
[ { "input": "5 4\n1 4 5 60 4", "output": "8" }, { "input": "3 1\n1 1 1", "output": "6" }, { "input": "15 2\n1 2 3 1 2 3 1 2 3 1 2 3 1 2 3", "output": "97" }, { "input": "1 1\n1", "output": "1" }, { "input": "2 1\n1 2", "output": "2" }, { "input": "2 1\n...
30
0
0
38,677
359
Pair of Numbers
[ "binary search", "brute force", "data structures", "math", "two pointers" ]
null
null
Simon has an array *a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* positive integers. Today Simon asked you to find a pair of integers *l*,<=*r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), such that the following conditions hold: 1. there is integer *j* (*l*<=≤<=*j*<=≤<=*r*), such that all integers *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r* are divisible by *a**j*; 1. value *r*<=-<=*l* takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (*l*,<=*r*). If there are multiple required pairs find all of them.
The first line contains integer *n* (1<=≤<=*n*<=≤<=3·105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106).
Print two integers in the first line — the number of required pairs and the maximum value of *r*<=-<=*l*. On the following line print all *l* values from optimal pairs in increasing order.
[ "5\n4 6 9 3 6\n", "5\n1 3 5 7 9\n", "5\n2 3 5 7 11\n" ]
[ "1 3\n2 \n", "1 4\n1 \n", "5 0\n1 2 3 4 5 \n" ]
In the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3. In the second sample all numbers are divisible by number 1. In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).
[ { "input": "5\n4 6 9 3 6", "output": "1 3\n2 " }, { "input": "5\n1 3 5 7 9", "output": "1 4\n1 " }, { "input": "5\n2 3 5 7 11", "output": "5 0\n1 2 3 4 5 " }, { "input": "1\n1343", "output": "1 0\n1 " }, { "input": "1\n1000000", "output": "1 0\n1 " }, { ...
295
7,577,600
0
38,792
862
Mahmoud and Ehab and the binary string
[ "binary search", "divide and conquer", "interactive" ]
null
null
Mahmoud and Ehab are in the fourth stage now. Dr. Evil has a hidden binary string of length *n*. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to 15 questions. They tell Dr. Evil some binary string of length *n*, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below. Help Mahmoud and Ehab find these two positions. You will get Wrong Answer verdict if - Your queries doesn't satisfy interaction protocol described below. - You ask strictly more than 15 questions and your program terminated after exceeding queries limit. Please note, that you can do up to 15 ask queries and one answer query. - Your final answer is not correct. If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .
The first line of input will contain a single integer *n* (2<=≤<=*n*<=≤<=1000) — the length of the hidden binary string.
To print the final answer, print "! pos0 pos1" (without quotes), where *pos*0 and *pos*1 are positions of some '0' and some '1' in the string (the string is 1-indexed). Don't forget to flush the output after printing the answer!
[ "3\n2\n1\n3\n2\n1\n0" ]
[ "? 000\n? 001\n? 010\n? 011\n? 100\n? 101\n! 2 1" ]
Hamming distance definition: [https://en.wikipedia.org/wiki/Hamming_distance](https://en.wikipedia.org/wiki/Hamming_distance) In the first test case the hidden binary string is 101, The first query is 000, so the Hamming distance is 2. In the second query the hidden string is still 101 and query is 001, so the Hamming distance is 1. After some queries you find that symbol at position 2 is '0' and symbol at position 1 is '1', so you print "! 2 1".
[ { "input": "101", "output": "3" }, { "input": "0011001100", "output": "4" }, { "input": "01", "output": "2" }, { "input": "0010100101101100001101110001110011000010011011001110010011101010011010100101101001111010111001000100", "output": "8" }, { "input": "010101010...
46
204,800
0
38,808
938
Max History
[ "combinatorics", "math" ]
null
null
You are given an array *a* of length *n*. We define *f**a* the following way: - Initially *f**a*<==<=0, *M*<==<=1; - for every 2<=≤<=*i*<=≤<=*n* if *a**M*<=&lt;<=*a**i* then we set *f**a*<==<=*f**a*<=+<=*a**M* and then set *M*<==<=*i*. Calculate the sum of *f**a* over all *n*! permutations of the array *a* modulo 109<=+<=7. Note: two elements are considered different if their indices differ, so for every array *a* there are exactly *n*! permutations.
The first line contains integer *n* (1<=≤<=*n*<=≤<=<=1 000 000) — the size of array *a*. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=<=*a**i*<=≤<=<=109).
Print the only integer, the sum of *f**a* over all *n*! permutations of the array *a* modulo 109<=+<=7.
[ "2\n1 3\n", "3\n1 1 2\n" ]
[ "1", "4" ]
For the second example all the permutations are: - *p* = [1, 2, 3] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [1, 3, 2] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [2, 1, 3] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [2, 3, 1] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [3, 1, 2] : *f*<sub class="lower-index">*a*</sub> is equal to 0; - *p* = [3, 2, 1] : *f*<sub class="lower-index">*a*</sub> is equal to 0. Where *p* is the array of the indices of initial array *a*. The sum of *f*<sub class="lower-index">*a*</sub> is equal to 4.
[ { "input": "2\n1 3", "output": "1" }, { "input": "3\n1 1 2", "output": "4" }, { "input": "6\n1 4 5 2 3 3", "output": "2928" }, { "input": "8\n8 7 5 4 6 6 6 6", "output": "351360" }, { "input": "8\n1 2 3 9 100 100 100 100", "output": "109296" }, { "inpu...
61
5,632,000
0
38,921
77
Heroes
[ "brute force", "implementation" ]
A. Heroes
2
256
The year of 2012 is coming... According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil. The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: *a* for Mephisto, *b* for Diablo and *c* for Baal. Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a of experience, rounded down, where *x* will be the amount of experience for the killed megaboss and *y* — the number of people in the team. Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum. It is known that some heroes like others. But if hero *p* likes hero *q*, this does not mean that the hero *q* likes hero *p*. No hero likes himself. The total amount of liking in teams is the amount of ordered pairs (*p*,<=*q*), such that heroes *p* and *q* are in the same group, and hero *p* likes hero *q* (but it is not important if hero *q* likes hero *p*). In case of heroes *p* and *q* likes each other and they are in the same group, this pair should be counted twice, as (*p*,<=*q*) and (*q*,<=*p*). A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team. It is guaranteed that every hero is able to destroy any megaboss alone.
The first line contains a single non-negative integer *n* (0<=≤<=*n*<=≤<=42) — amount of liking between the heroes. Next *n* lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p <=≠<= q). Every liking is described in the input exactly once, no hero likes himself. In the last line are given three integers *a*, *b* and *c* (1<=≤<=*a*,<=*b*,<=*c*<=≤<=2·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal. In all the pretests, except for examples from the statement, the following condition is satisfied: *a*<==<=*b*<==<=*c*.
Print two integers — the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team). When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking.
[ "3\nTroll likes Dracul\nDracul likes Anka\nSnowy likes Hexadecimal\n210 200 180\n", "2\nAnka likes Chapay\nChapay likes Anka\n10000 50 50\n" ]
[ "30 3\n", "1950 2\n" ]
A note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo и Chapay.
[ { "input": "3\nTroll likes Dracul\nDracul likes Anka\nSnowy likes Hexadecimal\n210 200 180", "output": "30 3" }, { "input": "2\nAnka likes Chapay\nChapay likes Anka\n10000 50 50", "output": "1950 2" }, { "input": "11\nSnowy likes Dracul\nAnka likes Dracul\nChapay likes Snowy\nHexadecimal...
404
3,891,200
3.891752
38,925
489
Hiking
[ "binary search", "dp" ]
null
null
A traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the *i*-th rest point the distance from the start equals *x**i*, and its picturesqueness equals *b**i*. The traveler will move down the river in one direction, we can assume that he will start from point 0 on the coordinate axis and rest points are points with coordinates *x**i*. Every day the traveler wants to cover the distance *l*. In practice, it turns out that this is not always possible, because he needs to end each day at one of the resting points. In addition, the traveler is choosing between two desires: cover distance *l* every day and visit the most picturesque places. Let's assume that if the traveler covers distance *r**j* in a day, then he feels frustration , and his total frustration over the hike is calculated as the total frustration on all days. Help him plan the route so as to minimize the relative total frustration: the total frustration divided by the total picturesqueness of all the rest points he used. The traveler's path must end in the farthest rest point.
The first line of the input contains integers *n*,<=*l* (1<=≤<=*n*<=≤<=1000,<=1<=≤<=*l*<=≤<=105) — the number of rest points and the optimal length of one day path. Then *n* lines follow, each line describes one rest point as a pair of integers *x**i*,<=*b**i* (1<=≤<=*x**i*,<=*b**i*<=≤<=106). No two rest points have the same *x**i*, the lines are given in the order of strictly increasing *x**i*.
Print the traveler's path as a sequence of the numbers of the resting points he used in the order he used them. Number the points from 1 to *n* in the order of increasing *x**i*. The last printed number must be equal to *n*.
[ "5 9\n10 10\n20 10\n30 1\n31 5\n40 10\n" ]
[ "1 2 4 5 " ]
In the sample test the minimum value of relative total frustration approximately equals 0.097549. This value can be calculated as <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bad16faba2aa8ac4e81ca909b5e927a7f644c23f.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "5 9\n10 10\n20 10\n30 1\n31 5\n40 10", "output": "1 2 4 5 " }, { "input": "1 20\n9 1", "output": "1 " }, { "input": "2 7\n1 9\n5 6", "output": "2 " }, { "input": "3 2\n2 6\n3 9\n6 8", "output": "1 2 3 " }, { "input": "4 3\n1 6\n5 10\n9 9\n10 6", "o...
919
15,257,600
3
38,980
883
Renovation
[ "constructive algorithms", "greedy", "sortings" ]
null
null
The mayor of the Berland city S sees the beauty differently than other city-dwellers. In particular, he does not understand at all, how antique houses can be nice-looking. So the mayor wants to demolish all ancient buildings in the city. The city S is going to host the football championship very soon. In order to make the city beautiful, every month the Berland government provides mayor a money tranche. The money has to be spent on ancient buildings renovation. There are *n* months before the championship and the *i*-th month tranche equals to *a**i* burles. The city S has *m* antique buildings and the renovation cost of the *j*-th building is *b**j* burles. The mayor has his own plans for spending the money. As he doesn't like antique buildings he wants to demolish as much of them as possible. For the *j*-th building he calculated its demolishing cost *p**j*. The mayor decided to act according to the following plan. Each month he chooses several (possibly zero) of *m* buildings to demolish in such a way that renovation cost of each of them separately is not greater than the money tranche *a**i* of this month (*b**j*<=≤<=*a**i*) — it will allow to deceive city-dwellers that exactly this building will be renovated. Then the mayor has to demolish all selected buildings during the current month as otherwise the dwellers will realize the deception and the plan will fail. Definitely the total demolishing cost can not exceed amount of money the mayor currently has. The mayor is not obliged to spend all the money on demolishing. If some money is left, the mayor puts it to the bank account and can use it in any subsequent month. Moreover, at any month he may choose not to demolish any buildings at all (in this case all the tranche will remain untouched and will be saved in the bank). Your task is to calculate the maximal number of buildings the mayor can demolish.
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — the number of months before the championship and the number of ancient buildings in the city S. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), where *a**i* is the tranche of the *i*-th month. The third line contains *m* integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**j*<=≤<=109), where *b**j* is renovation cost of the *j*-th building. The fourth line contains *m* integers *p*1,<=*p*2,<=...,<=*p**m* (1<=≤<=*p**j*<=≤<=109), where *p**j* is the demolishing cost of the *j*-th building.
Output single integer — the maximal number of buildings the mayor can demolish.
[ "2 3\n2 4\n6 2 3\n1 3 2\n", "3 5\n5 3 1\n5 2 9 1 10\n4 2 1 3 10\n", "5 6\n6 3 2 4 3\n3 6 4 5 4 2\n1 4 3 2 5 3\n" ]
[ "2\n", "3\n", "6\n" ]
In the third example the mayor acts as follows. In the first month he obtains 6 burles tranche and demolishes buildings #2 (renovation cost 6, demolishing cost 4) and #4 (renovation cost 5, demolishing cost 2). He spends all the money on it. After getting the second month tranche of 3 burles, the mayor selects only building #1 (renovation cost 3, demolishing cost 1) for demolishing. As a result, he saves 2 burles for the next months. In the third month he gets 2 burle tranche, but decides not to demolish any buildings at all. As a result, he has 2 + 2 = 4 burles in the bank. This reserve will be spent on the fourth month together with the 4-th tranche for demolishing of houses #3 and #5 (renovation cost is 4 for each, demolishing costs are 3 and 5 correspondingly). After this month his budget is empty. Finally, after getting the last tranche of 3 burles, the mayor demolishes building #6 (renovation cost 2, demolishing cost 3). As it can be seen, he demolished all 6 buildings.
[ { "input": "2 3\n2 4\n6 2 3\n1 3 2", "output": "2" }, { "input": "3 5\n5 3 1\n5 2 9 1 10\n4 2 1 3 10", "output": "3" }, { "input": "5 6\n6 3 2 4 3\n3 6 4 5 4 2\n1 4 3 2 5 3", "output": "6" }, { "input": "1 5\n9\n1 2 3 4 5\n5 4 3 2 1", "output": "3" }, { "input": "...
46
0
0
39,019
26
Tickets
[ "combinatorics", "math", "probabilities" ]
D. Tickets
2
256
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly *n*<=+<=*m* people will come to buy a ticket. *n* of them will have only a single 10 euro banknote, and *m* of them will have only a single 20 euro banknote. Currently Charlie has *k* 10 euro banknotes, which he can use for change if needed. All *n*<=+<=*m* people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
The input consist of a single line with three space separated integers, *n*, *m* and *k* (0<=≤<=*n*,<=*m*<=≤<=105, 0<=≤<=*k*<=≤<=10).
Output on a single line the desired probability with at least 4 digits after the decimal point.
[ "5 3 1\n", "0 5 5\n", "0 1 0\n" ]
[ "0.857143\n", "1\n", "0\n" ]
none
[ { "input": "5 3 1", "output": "0.857143" }, { "input": "0 5 5", "output": "1" }, { "input": "0 1 0", "output": "0" }, { "input": "95105 76851 10", "output": "0.904215" }, { "input": "60503 53620 1", "output": "0.214637" }, { "input": "25902 30390 2", ...
310
2,048,000
3.918685
39,026
348
Turtles
[ "dp", "matrices" ]
null
null
You've got a table of size *n*<=×<=*m*. We'll consider the table rows numbered from top to bottom 1 through *n*, and the columns numbered from left to right 1 through *m*. Then we'll denote the cell in row *x* and column *y* as (*x*,<=*y*). Initially cell (1,<=1) contains two similar turtles. Both turtles want to get to cell (*n*,<=*m*). Some cells of the table have obstacles but it is guaranteed that there aren't any obstacles in the upper left and lower right corner. A turtle (one or the other) can go from cell (*x*,<=*y*) to one of two cells (*x*<=+<=1,<=*y*) and (*x*,<=*y*<=+<=1), as long as the required cell doesn't contain an obstacle. The turtles have had an argument so they don't want to have any chance of meeting each other along the way. Help them find the number of ways in which they can go from cell (1,<=1) to cell (*n*,<=*m*). More formally, find the number of pairs of non-intersecting ways from cell (1,<=1) to cell (*n*,<=*m*) modulo 1000000007 (109<=+<=7). Two ways are called non-intersecting if they have exactly two common points — the starting point and the final point.
The first line contains two integers *n*,<=*m* (2<=≤<=*n*,<=*m*<=≤<=3000). Each of the following *n* lines contains *m* characters describing the table. The empty cells are marked by characters ".", the cells with obstacles are marked by "#". It is guaranteed that the upper left and the lower right cells are empty.
In a single line print a single integer — the number of pairs of non-intersecting paths from cell (1,<=1) to cell (*n*,<=*m*) modulo 1000000007 (109<=+<=7).
[ "4 5\n.....\n.###.\n.###.\n.....\n", "2 3\n...\n...\n" ]
[ "1\n", "1\n" ]
none
[ { "input": "10 10\n.#.#.#.#..\n#...##.###\n...#...##.\n..##......\n#.###..#.#\n.###..#.#.\n...#...##.\n.....#.##.\n.#.#....##\n#....###..", "output": "0" }, { "input": "10 8\n.#######\n########\n########\n########\n########\n########\n########\n########\n########\n#######.", "output": "0" } ]
92
0
0
39,034
71
Round Table Knights
[ "dp", "math", "number theory" ]
C. Round Table Knights
0
256
There are *n* knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood. Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes. A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated. On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.
The first line contains number *n*, which is the number of knights at the round table (3<=≤<=*n*<=≤<=105). The second line contains space-separated moods of all the *n* knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.
Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".
[ "3\n1 1 1\n", "6\n1 0 1 1 1 0\n", "6\n1 0 0 1 0 1\n" ]
[ "YES", "YES", "NO" ]
none
[ { "input": "3\n1 1 1", "output": "YES" }, { "input": "6\n1 0 1 1 1 0", "output": "YES" }, { "input": "6\n1 0 0 1 0 1", "output": "NO" }, { "input": "10\n1 0 1 1 1 0 1 0 1 0", "output": "YES" }, { "input": "15\n0 0 0 1 0 1 1 0 1 0 0 1 0 1 0", "output": "YES" ...
77
7,270,400
3
39,099
920
Tanks
[ "dp", "greedy", "implementation" ]
null
null
Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly *V* ml of water. Petya has got *N* tanks, *i*-th of them initially containing *a**i* ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is). Also Petya has got a scoop that can contain up to *K* ml of water (initially the scoop is empty). This scoop can be used to get some water from some tank, and after that pour it all into some tank (it is impossible to get water from multiple tanks without pouring it, or leave some water in the scoop when pouring it). When Petya tries to get some water from a tank, he gets *min*(*v*,<=*K*) water, where *v* is the current volume of water in the tank. Is it possible to obtain a tank with exactly *V* ml of water using these operations? If it is possible, print a sequence of operations that allows to do it. If there are multiple ways to obtain needed amount of water in some tank, print any of them.
The first line contains 3 integers: *N* (2<=≤<=*N*<=≤<=5000), *K* (1<=≤<=*K*<=≤<=5000), and *V* (0<=≤<=*V*<=≤<=109) — the number of tanks, the maximum volume of water the scoop can contain, and the required amount of water in some tank, respectively. The second line contains *N* integers *a**i* (0<=≤<=*a**i*<=≤<=105), where *a**i* is initial volume of water in *i*-th tank.
If it is impossible to obtain a tank with exactly *V* ml of water, print NO. Otherwise print YES in the first line, and beginning from the second line, print the sequence of operations in the following format: Each line has to contain 3 numbers denoting a compressed operation: "*cnt* *x* *y*" (1<=≤<=*cnt*<=≤<=109,<=1<=≤<=*x*,<=*y*<=≤<=*N*), where *x* is the index of the tank where we get water, *y* is the index of the tank where we pour water, and *cnt* is the number of times we transfer water from tank *x* to tank *y*. The number of these lines must not exceed *N*<=+<=5.
[ "2 3 5\n2 3\n", "2 3 4\n2 3\n", "5 2 0\n1 3 5 7 9\n" ]
[ "YES\n1 2 1\n", "NO\n", "YES\n2 2 1\n3 3 1\n4 4 1\n5 5 1\n" ]
none
[ { "input": "2 3 5\n2 3", "output": "YES\n1 2 1" }, { "input": "2 3 4\n2 3", "output": "NO" }, { "input": "5 2 0\n1 3 5 7 9", "output": "YES\n2 2 1\n3 3 1\n4 4 1\n5 5 1" }, { "input": "5 10 3\n3 4 5 6 7", "output": "YES\n1 3 2\n1 4 2\n1 5 2" }, { "input": "6 4 8\n5...
31
0
0
39,171
144
Competition
[ "data structures", "greedy" ]
null
null
The secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an *n*-degree staircase as a square matrix *n*<=×<=*n* containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase). The squares of the *n*-degree staircase contain *m* sportsmen. A sportsman needs one second to move to a side-neighboring square of the staircase. Before the beginning of the competition each sportsman must choose one of the shortest ways to the secondary diagonal. After the starting whistle the competition begins and all sportsmen start moving along the chosen paths. When a sportsman reaches a cell of the secondary diagonal, he stops and moves no more. The competition ends when all sportsmen reach the secondary diagonal. The competition is considered successful if during it no two sportsmen were present in the same square simultaneously. Any square belonging to the secondary diagonal also cannot contain more than one sportsman. If a sportsman at the given moment of time leaves a square and another sportsman comes to it, then they are not considered to occupy the same square simultaneously. Note that other extreme cases (for example, two sportsmen moving towards each other) are impossible as the chosen ways are the shortest ones. You are given positions of *m* sportsmen on the staircase. Your task is to choose among them the maximum number of sportsmen for who the competition can be successful, that is, so that there existed such choice of shortest ways for the sportsmen at which no two sportsmen find themselves in the same square simultaneously. All other sportsmen that are not chosen will be removed from the staircase before the competition starts.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105). Then *m* lines contain coordinates of sportsmen on the staircase as pairs of integers *r**i*,<=*c**i* (1<=≤<=*r**i*,<=*c**i*<=≤<=*n*, *n*<=-<=*c**i*<=&lt;<=*r**i*), where *r**i* is the number of the staircase row, *c**i* is the number of the staircase column (to understand the principle of numbering rows and columns see the explanatory pictures). No two sportsmen stand on the same square of the staircase.
In the first line print the number of the chosen sportsmen. In the second line print the numbers of chosen sportsmen in any order, separating the numbers with spaces. If there are several answers, you are permitted to print any of them. The sportsmen are numbered starting from one in the order in which they are given in the input data.
[ "3 3\n2 3\n3 2\n3 3\n" ]
[ "3\n1 2 3 \n" ]
A note to the first sample.
[ { "input": "3 3\n2 3\n3 2\n3 3", "output": "3\n1 2 3 " }, { "input": "1 1\n1 1", "output": "1\n1 " }, { "input": "2 3\n1 2\n2 1\n2 2", "output": "2\n1 2 " }, { "input": "2 1\n1 2", "output": "1\n1 " }, { "input": "2 2\n1 2\n2 1", "output": "2\n1 2 " }, { ...
1,060
34,201,600
3
39,279
253
Printer
[ "binary search", "data structures", "implementation", "sortings" ]
null
null
Let's consider a network printer that functions like that. It starts working at time 0. In each second it can print one page of a text. At some moments of time the printer receives printing tasks. We know that a printer received *n* tasks. Let's number the tasks by consecutive integers from 1 to *n*. Then the task number *i* is characterised by three integers: *t**i* is the time when the task came, *s**i* is the task's volume (in pages) and *p**i* is the task's priority. The priorities of all tasks are distinct. When the printer receives a task, the task goes to the queue and remains there until all pages from this task are printed. The printer chooses a page to print each time when it either stops printing some page or when it is free and receives a new task. Among all tasks that are in the queue at this moment, the printer chooses the task with the highest priority and next second prints an unprinted page from this task. You can assume that a task goes to the queue immediately, that's why if a task has just arrived by time *t*, the printer can already choose it for printing. You are given full information about all tasks except for one: you don't know this task's priority. However, we know the time when the last page from this task was finished printing. Given this information, find the unknown priority value and determine the moments of time when the printer finished printing each task.
The first line contains integer *n* (1<=≤<=*n*<=≤<=50000). Next *n* lines describe the tasks. The *i*-th of these lines contains three integers *t**i*, *s**i* and *p**i*, separated by single spaces (0<=≤<=*t**i*<=≤<=109,<=1<=≤<=*s**i*,<=*p**i*<=≤<=109). Exactly one task (let's assume that his number is *x*) has number -1 written instead of the priority. All priorities are different. The last line contains integer *T* — the time when the printer finished printing the last page of task *x* (1<=≤<=*T*<=≤<=1015). Numbers *t**i* are not necessarily distinct. The tasks in the input are written in the arbitrary order.
In the first line print integer *p**x* — the priority of the task number *x* (1<=≤<=*p**x*<=≤<=109, remember that all priorities should be distinct). Then print *n* integers, the *i*-th of them represents the moment of time when the last page of the task number *i* finished printing. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.
[ "3\n4 3 -1\n0 2 2\n1 3 3\n7\n", "3\n3 1 2\n2 3 3\n3 1 -1\n4\n" ]
[ "4\n7 8 4\n", "4\n7 6 4\n" ]
Let's consider the first test case. Let's assume that the unknown priority equals 4, then the printer's actions for each second are as follows: - the beginning of the 1-st second (time 0). The queue has task 2. The printer prints the first page of this task; - the beginning of the 2-nd second (time 1). The queue has tasks 2 and 3. The printer prints the first page of task 3; - the beginning of the 3-rd second (time 2). The queue has tasks 2 and 3. The printer prints the second page of task 3; - the beginning of the 4-th second (time 3). The queue has tasks 2 and 3. The printer prints the third (last) page of task 3. Thus, by the end of the 4-th second this task will have been printed; - the beginning of the 5-th second (time 4). The queue has tasks 2 and 1. The printer prints the first page of task 1; - the beginning of the 6-th second (time 5). The queue has tasks 2 and 1. The printer prints the second page of task 1; - the beginning of the 7-th second (time 6). The queue has tasks 2 and 1. The printer prints the third (last) page of task 1. Thus, by the end of the 7-th second this task will have been printed; - the beginning of the 8-th second (time 7). The queue has task 2. The printer prints the second (last) page of task 2. Thus, by the end of the 8-th second this task will have been printed. In the end, task number 1 will have been printed by the end of the 7-th second, as was required. And tasks 2 and 3 are printed by the end of the of the 8-th and the 4-th second correspondingly.
[]
92
0
0
39,427
582
Number of Binominal Coefficients
[ "dp", "math", "number theory" ]
null
null
For a given prime integer *p* and integers α,<=*A* calculate the number of pairs of integers (*n*,<=*k*), such that 0<=≤<=*k*<=≤<=*n*<=≤<=*A* and is divisible by *p*α. As the answer can be rather large, print the remainder of the answer moduly 109<=+<=7. Let us remind you that is the number of ways *k* objects can be chosen from the set of *n* objects.
The first line contains two integers, *p* and α (1<=≤<=*p*,<=α<=≤<=109, *p* is prime). The second line contains the decimal record of integer *A* (0<=≤<=*A*<=&lt;<=101000) without leading zeroes.
In the single line print the answer to the problem.
[ "2 2\n7\n", "3 1\n9\n", "3 3\n9\n", "2 4\n5000\n" ]
[ "3\n", "17\n", "0\n", "8576851\n" ]
In the first sample three binominal coefficients divisible by 4 are <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a4c2b94fb12d1298dafcd1d14d7e1f6a47500264.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/80436d3bb1008bf8943b41f46211501e7fea05e9.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bb01b873c593007ca5b10a8897a71c4b0d7dabae.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[]
46
0
0
39,428
732
Sanatorium
[ "binary search", "constructive algorithms", "greedy", "implementation", "math" ]
null
null
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all. Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived. According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.
The only line contains three integers *b*, *d* and *s* (0<=≤<=*b*,<=*d*,<=*s*<=≤<=1018,<=<=*b*<=+<=*d*<=+<=*s*<=≥<=1) — the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium.
Print single integer — the minimum possible number of meals which Vasiliy could have missed during his vacation.
[ "3 2 1\n", "1 0 0\n", "1 1 1\n", "1000000000000000000 0 1000000000000000000\n" ]
[ "1\n", "0\n", "0\n", "999999999999999999\n" ]
In the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day. In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal. In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal.
[ { "input": "3 2 1", "output": "1" }, { "input": "1 0 0", "output": "0" }, { "input": "1 1 1", "output": "0" }, { "input": "1000000000000000000 0 1000000000000000000", "output": "999999999999999999" }, { "input": "1000 0 0", "output": "1998" }, { "input...
46
0
3
39,509
908
New Year and Arbitrary Arrangement
[ "dp", "math", "probabilities" ]
null
null
You are given three integers *k*, *p**a* and *p**b*. You will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability *p**a*<=/<=(*p**a*<=+<=*p**b*), add 'a' to the end of the sequence. Otherwise (with probability *p**b*<=/<=(*p**a*<=+<=*p**b*)), add 'b' to the end of the sequence. You stop once there are at least *k* subsequences that form 'ab'. Determine the expected number of times 'ab' is a subsequence in the resulting sequence. It can be shown that this can be represented by *P*<=/<=*Q*, where *P* and *Q* are coprime integers, and . Print the value of .
The first line will contain three integers integer *k*,<=*p**a*,<=*p**b* (1<=≤<=*k*<=≤<=1<=000, 1<=≤<=*p**a*,<=*p**b*<=≤<=1<=000<=000).
Print a single integer, the answer to the problem.
[ "1 1 1\n", "3 1 4\n" ]
[ "2\n", "370000006\n" ]
The first sample, we will keep appending to our sequence until we get the subsequence 'ab' at least once. For instance, we get the sequence 'ab' with probability 1/4, 'bbab' with probability 1/16, and 'aab' with probability 1/8. Note, it's impossible for us to end with a sequence like 'aabab', since we would have stopped our algorithm once we had the prefix 'aab'. The expected amount of times that 'ab' will occur across all valid sequences is 2. For the second sample, the answer is equal to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b95c4c7a595b83bcacbbaf06f7667850752a2092.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "1 1 1", "output": "2" }, { "input": "3 1 4", "output": "370000006" }, { "input": "1000 123456 654321", "output": "977760856" }, { "input": "305 337309 378395", "output": "174667130" }, { "input": "108 531040 908573", "output": "145579983" }, { ...
186
16,076,800
-1
39,546
292
SMSC
[ "implementation" ]
null
null
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of *n* tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the *i*-th task was described by two integers *t**i* and *c**i* — the receiving time (the second) and the number of the text messages, correspondingly. Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment *x*, the SMSC work at that moment as follows: 1. If at the time moment *x* the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment *x*. 1. If at the time moment *x* SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment *x*. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all *n* tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=103) — the number of tasks of the SMSC. Next *n* lines contain the tasks' descriptions: the *i*-th line contains two space-separated integers *t**i* and *c**i* (1<=≤<=*t**i*,<=*c**i*<=≤<=106) — the time (the second) when the *i*-th task was received and the number of messages to send, correspondingly. It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, *t**i*<=&lt;<=*t**i*<=+<=1 for all integer *i* (1<=≤<=*i*<=&lt;<=*n*).
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
[ "2\n1 1\n2 1\n", "1\n1000000 10\n", "3\n3 3\n4 3\n5 3\n" ]
[ "3 1\n", "1000010 10\n", "12 7\n" ]
In the first test sample: - second 1: the first message has appeared in the queue, the queue's size is 1; - second 2: the first message is sent, the second message has been received, the queue's size is 1; - second 3: the second message is sent, the queue's size is 0, Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
[ { "input": "2\n1 1\n2 1", "output": "3 1" }, { "input": "1\n1000000 10", "output": "1000010 10" }, { "input": "3\n3 3\n4 3\n5 3", "output": "12 7" }, { "input": "1\n1 1", "output": "2 1" }, { "input": "2\n1 11\n100 10", "output": "110 11" }, { "input":...
60
0
0
39,607
47
Safe
[ "brute force" ]
D. Safe
5
256
Vasya tries to break in a safe. He knows that a code consists of *n* numbers, and every number is a 0 or a 1. Vasya has made *m* attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.
The first input line contains two integers *n* and *m* (6<=≤<=*n*<=≤<=35,<=1<=≤<=*m*<=≤<=10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow *m* lines, each containing space-separated *s**i* and *c**i* which correspondingly indicate Vasya’s attempt (a line containing *n* numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).
Print the single number which indicates how many possible code variants that do not contradict the *m* system responses are left.
[ "6 2\n000000 2\n010100 4\n", "6 3\n000000 2\n010100 4\n111100 0\n", "6 3\n000000 2\n010100 4\n111100 2\n" ]
[ "6\n", "0\n", "1\n" ]
none
[ { "input": "6 2\n000000 2\n010100 4", "output": "6" }, { "input": "6 3\n000000 2\n010100 4\n111100 0", "output": "0" }, { "input": "6 3\n000000 2\n010100 4\n111100 2", "output": "1" }, { "input": "6 1\n101011 2", "output": "15" }, { "input": "7 2\n1011111 2\n10011...
60
0
0
39,796
388
Fox and Perfect Sets
[ "math" ]
null
null
Fox Ciel studies number theory. She thinks a non-empty set *S* contains non-negative integers is perfect if and only if for any (*a* can be equal to *b*), . Where operation *xor* means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or). Please calculate the number of perfect sets consisting of integers not greater than *k*. The answer can be very large, so print it modulo 1000000007 (109<=+<=7).
The first line contains an integer *k* (0<=≤<=*k*<=≤<=109).
Print a single integer — the number of required sets modulo 1000000007 (109<=+<=7).
[ "1\n", "2\n", "3\n", "4\n" ]
[ "2\n", "3\n", "5\n", "6\n" ]
In example 1, there are 2 such sets: {0} and {0, 1}. Note that {1} is not a perfect set since 1 xor 1 = 0 and {1} doesn't contain zero. In example 4, there are 6 such sets: {0}, {0, 1}, {0, 2}, {0, 3}, {0, 4} and {0, 1, 2, 3}.
[ { "input": "1", "output": "2" }, { "input": "2", "output": "3" }, { "input": "3", "output": "5" }, { "input": "4", "output": "6" }, { "input": "8", "output": "17" }, { "input": "5", "output": "8" }, { "input": "6", "output": "11" }, ...
62
20,172,800
0
39,821
327
Magic Five
[ "combinatorics", "math" ]
null
null
There is a long plate *s* containing *n* digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros. Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109<=+<=7). Two ways are different, if the set of deleted positions in *s* differs. Look at the input part of the statement, *s* is given in a special form.
In the first line you're given a string *a* (1<=≤<=|*a*|<=≤<=105), containing digits only. In the second line you're given an integer *k* (1<=≤<=*k*<=≤<=109). The plate *s* is formed by concatenating *k* copies of *a* together. That is *n*<==<=|*a*|·*k*.
Print a single integer — the required number of ways modulo 1000000007 (109<=+<=7).
[ "1256\n1\n", "13990\n2\n", "555\n2\n" ]
[ "4\n", "528\n", "63\n" ]
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125. In the second case, remember to concatenate the copies of *a*. The actual plate is 1399013990. In the third case, except deleting all digits, any choice will do. Therefore there are 2<sup class="upper-index">6</sup> - 1 = 63 possible ways to delete digits.
[ { "input": "1256\n1", "output": "4" }, { "input": "13990\n2", "output": "528" }, { "input": "555\n2", "output": "63" }, { "input": "14\n178", "output": "0" }, { "input": "277557766562106078327886194146355351781887756238383139670139581436190170050799912854698535037...
92
1,945,600
0
39,887
0
none
[ "none" ]
null
null
Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end. The conveyor is a looped belt with a total length of 2*l* meters, of which *l* meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (the part which emerges from under the floor to the surface and returns from the surface under the floor) is assumed to be negligibly short. The belt is moving uniformly at speed *v*1 meters per second. Anton will be moving on it in the same direction at the constant speed of *v*2 meters per second, so his speed relatively to the floor will be *v*1<=+<=*v*2 meters per second. Anton will neither stop nor change the speed or the direction of movement. Here and there there are chocolates stuck to the belt (*n* chocolates). They move together with the belt, and do not come off it. Anton is keen on the chocolates, but he is more keen to move forward. So he will pick up all the chocolates he will pass by, but nothing more. If a chocolate is at the beginning of the belt at the moment when Anton starts running, he will take it, and if a chocolate is at the end of the belt at the moment when Anton comes off the belt, he will leave it. You are given the positions of the chocolates relative to the initial start position of the belt 0<=≤<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n*<=&lt;<=2*l*. The positions on the belt from 0 to *l* correspond to the top, and from *l* to 2*l* — to the the bottom half of the belt (see example). All coordinates are given in meters. Anton begins to run along the belt at a random moment of time. This means that all possible positions of the belt at the moment he starts running are equiprobable. For each *i* from 0 to *n* calculate the probability that Anton will pick up exactly *i* chocolates.
The first line contains space-separated integers *n*, *l*, *v*1 and *v*2 (1<=≤<=*n*<=≤<=105, 1<=≤<=*l*,<=*v*1,<=*v*2<=≤<=109) — the number of the chocolates, the length of the conveyor's visible part, the conveyor's speed and Anton's speed. The second line contains a sequence of space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**n*<=&lt;<=2*l*) — the coordinates of the chocolates.
Print *n*<=+<=1 numbers (one per line): the probabilities that Anton picks up exactly *i* chocolates, for each *i* from 0 (the first line) to *n* (the last line). The answer will be considered correct if each number will have absolute or relative error of at most than 10<=-<=9.
[ "1 1 1 1\n0\n", "2 3 1 2\n2 5\n" ]
[ "0.75000000000000000000\n0.25000000000000000000\n", "0.33333333333333331000\n0.66666666666666663000\n0.00000000000000000000\n" ]
In the first sample test Anton can pick up a chocolate if by the moment he starts running its coordinate is less than 0.5; but if by the moment the boy starts running the chocolate's coordinate is greater than or equal to 0.5, then Anton won't be able to pick it up. As all positions of the belt are equiprobable, the probability of picking up the chocolate equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/55d1d7955c1e59f407eb6baa7601582a54eeac4f.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and the probability of not picking it up equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/0e79ad74cc0314b318cc094369c845c55b37c9ef.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[]
46
0
0
39,888
952
Puzzling Language
[ "constructive algorithms" ]
null
null
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck). The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table: You are given a string. Output a program in the described language which prints this string. You can download the language interpreter used for judging here: [https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp](https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp) (use C++11 to compile the code). Note several implementation details: - The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.- The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.- The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.- Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.- Console input (, command) is allowed in Brainfuck code but has no effect when executed.
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output a program in the described language which, when executed, will print the given message.
[ "$$$" ]
[ ".......X.......\n......XXX......\n.....XXXXX.....\n....XXXXXXX....\n...XXXXXXXXX...\n..XXXXXXXXXXX..\n.XXXXXXXXXXXXX.\n...............\nX.............X\nX..............\nX..............\nX..............\n" ]
The example corresponds to the following Brainfuck program: The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
[ { "input": "$$$", "output": "..\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\...
30
0
0
39,918
451
Count Good Substrings
[ "math" ]
null
null
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba". Given a string, you have to find two values: 1. the number of good substrings of even length; 1. the number of good substrings of odd length.
The first line of the input contains a single string of length *n* (1<=≤<=*n*<=≤<=105). Each character of the string will be either 'a' or 'b'.
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
[ "bb\n", "baab\n", "babb\n", "babaa\n" ]
[ "1 2\n", "2 4\n", "2 5\n", "2 7\n" ]
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length. In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length. In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length. Definitions A substring *s*[*l*, *r*] (1 ≤ *l* ≤ *r* ≤ *n*) of string *s* = *s*<sub class="lower-index">1</sub>*s*<sub class="lower-index">2</sub>... *s*<sub class="lower-index">*n*</sub> is string *s*<sub class="lower-index">*l*</sub>*s*<sub class="lower-index">*l* + 1</sub>... *s*<sub class="lower-index">*r*</sub>. A string *s* = *s*<sub class="lower-index">1</sub>*s*<sub class="lower-index">2</sub>... *s*<sub class="lower-index">*n*</sub> is a palindrome if it is equal to string *s*<sub class="lower-index">*n*</sub>*s*<sub class="lower-index">*n* - 1</sub>... *s*<sub class="lower-index">1</sub>.
[ { "input": "bb", "output": "1 2" }, { "input": "baab", "output": "2 4" }, { "input": "babb", "output": "2 5" }, { "input": "babaa", "output": "2 7" }, { "input": "baabbbb", "output": "7 11" }, { "input": "babbbbbaaabaabbabbabbababbaaba", "output": ...
2,000
10,956,800
0
39,927
566
Max and Min
[ "geometry" ]
null
null
Two kittens, Max and Min, play with a pair of non-negative integers *x* and *y*. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, *x* and *y* became negative at the same time, and kitten Max tries to prevent him from doing so. Each kitten has a set of pairs of integers available to it. Kitten Max has *n* pairs of non-negative integers (*a**i*,<=*b**i*) (1<=≤<=*i*<=≤<=*n*), and kitten Min has *m* pairs of non-negative integers (*c**j*,<=*d**j*) (1<=≤<=*j*<=≤<=*m*). As kitten Max makes a move, it can take any available pair (*a**i*,<=*b**i*) and add *a**i* to *x* and *b**i* to *y*, and kitten Min can take any available pair (*c**j*,<=*d**j*) and subtract *c**j* from *x* and *d**j* from *y*. Each kitten can use each pair multiple times during distinct moves. Max moves first. Kitten Min is winning if at some moment both numbers *a*, *b* are negative simultaneously. Otherwise, the winner of the game is kitten Max. Determine which kitten wins if both of them play optimally.
The first line contains two integers, *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — the number of pairs of numbers available to Max and Min, correspondingly. The second line contains two integers *x*, *y* (1<=≤<=*x*,<=*y*<=≤<=109) — the initial values of numbers with which the kittens are playing. Next *n* lines contain the pairs of numbers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=109) — the pairs available to Max. The last *m* lines contain pairs of numbers *c**j*,<=*d**j* (1<=≤<=*c**j*,<=*d**j*<=≤<=109) — the pairs available to Min.
Print «Max» (without the quotes), if kitten Max wins, or "Min" (without the quotes), if kitten Min wins.
[ "2 2\n42 43\n2 3\n3 2\n3 10\n10 3\n", "1 1\n1 1\n3 4\n1 1\n" ]
[ "Min\n", "Max\n" ]
In the first test from the statement Min can respond to move (2, 3) by move (3, 10), and to move (3, 2) by move (10, 3). Thus, for each pair of Max and Min's moves the values of both numbers *x* and *y* will strictly decrease, ergo, Min will win sooner or later. In the second sample test after each pair of Max and Min's moves both numbers *x* and *y* only increase, thus none of them will become negative.
[]
46
0
0
40,057
581
Kojiro and Furrari
[ "dp", "greedy" ]
null
null
Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her. Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point *f* of a coordinate line, and Johanna is at point *e*. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers *t**i* and *x**i* — the number of the gas type and its position. One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly *s* liters of fuel (regardless of the type of fuel). At the moment of departure from point *f* Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than *s* liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right. To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from *f* to *e*, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95. Write a program that can for the *m* possible positions of the start *f**i* minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.
The first line of the input contains four positive integers *e*,<=*s*,<=*n*,<=*m* (1<=≤<=*e*,<=*s*<=≤<=109,<=1<=≤<=*n*,<=*m*<=≤<=2·105) — the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points. Next *n* lines contain two integers each *t**i*,<=*x**i* (1<=≤<=*t**i*<=≤<=3,<=<=-<=109<=≤<=*x**i*<=≤<=109), representing the type of the *i*-th gas station (1 represents Regular-92, 2 — Premium-95 and 3 — Super-98) and the position on a coordinate line of the *i*-th gas station. Gas stations don't necessarily follow in order from left to right. The last line contains *m* integers *f**i* (<=-<=109<=≤<=*f**i*<=&lt;<=*e*). Start positions don't necessarily follow in order from left to right. No point of the coordinate line contains more than one gas station. It is possible that some of points *f**i* or point *e* coincide with a gas station.
Print exactly *m* lines. The *i*-th of them should contain two integers — the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point *f**i*. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value. If there is no way to get to Johanna from point *f**i*, the *i*-th line should look like that "-1 -1" (two numbers minus one without the quotes).
[ "8 4 1 1\n2 4\n0\n", "9 3 2 3\n2 3\n1 6\n-1 0 1\n", "20 9 2 4\n1 5\n2 10\n-1 0 1 2\n" ]
[ "0 4\n", "-1 -1\n3 3\n3 2\n", "-1 -1\n-1 -1\n-1 -1\n-1 -1\n" ]
none
[]
62
9,523,200
-1
40,111
804
The same permutation
[ "constructive algorithms" ]
null
null
Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (*i*,<=*j*), where *i*<=&lt;<=*j*, exactly once. MoJaK doesn't like to upset Sajjad. Given the permutation, determine whether it is possible to swap all pairs of positions so that the permutation stays the same. If it is possible find how to do that.
The first line contains single integer *n* (1<=≤<=*n*<=≤<=1000) — the size of the permutation. As the permutation is not important, you can consider *a**i*<==<=*i*, where the permutation is *a*1,<=*a*2,<=...,<=*a**n*.
If it is not possible to swap all pairs of positions so that the permutation stays the same, print "NO", Otherwise print "YES", then print lines: the *i*-th of these lines should contain two integers *a* and *b* (*a*<=&lt;<=*b*) — the positions where the *i*-th swap is performed.
[ "3\n", "1\n" ]
[ "NO\n", "YES\n" ]
none
[ { "input": "3", "output": "NO" }, { "input": "1", "output": "YES" }, { "input": "5", "output": "YES\n3 5\n3 4\n4 5\n1 3\n2 4\n2 3\n1 4\n1 5\n1 2\n2 5" }, { "input": "6", "output": "NO" }, { "input": "7", "output": "NO" }, { "input": "8", "output": ...
30
0
0
40,113
140
New Year Cards
[ "brute force", "greedy", "implementation" ]
null
null
As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has *n* friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to *n* in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the *i*-th friend sent to Alexander a card number *i*. Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: 1. He will never send to a firend a card that this friend has sent to him. 1. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times. Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to *n*. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card. Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible. Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.
The first line contains an integer *n* (2<=≤<=*n*<=≤<=300) — the number of Alexander's friends, equal to the number of cards. Next *n* lines contain his friends' preference lists. Each list consists of *n* different integers from 1 to *n*. The last line contains Alexander's preference list in the same format.
Print *n* space-separated numbers: the *i*-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the *i*-th friend. If there are several solutions, print any of them.
[ "4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4\n" ]
[ "2 1 1 4\n" ]
In the sample, the algorithm of actions Alexander and his friends perform is as follows: 1. Alexander receives card 1 from the first friend. 1. Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3. 1. Alexander receives card 2 from the second friend, now he has two cards — 1 and 2. 1. Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend. 1. Alexander receives card 3 from the third friend. 1. Alexander receives card 4 from the fourth friend. 1. Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct).
[ { "input": "4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4", "output": "2 1 1 3" }, { "input": "2\n1 2\n2 1\n2 1", "output": "2 1" }, { "input": "3\n1 2 3\n2 3 1\n1 3 2\n3 2 1", "output": "2 3 1" }, { "input": "5\n1 4 2 3 5\n5 1 3 4 2\n3 2 4 1 5\n1 4 5 3 2\n5 2 3 4 1\n5 4 2 1...
186
4,710,400
3
40,139
976
Degree Set
[ "constructive algorithms", "graphs", "implementation" ]
null
null
You are given a sequence of *n* positive integers *d*1,<=*d*2,<=...,<=*d**n* (*d*1<=&lt;<=*d*2<=&lt;<=...<=&lt;<=*d**n*). Your task is to construct an undirected graph such that: - there are exactly *d**n*<=+<=1 vertices; - there are no self-loops; - there are no multiple edges; - there are no more than 106 edges; - its degree set is equal to *d*. Vertices should be numbered 1 through (*d**n*<=+<=1). Degree sequence is an array *a* with length equal to the number of vertices in a graph such that *a**i* is the number of vertices adjacent to *i*-th vertex. Degree set is a sorted in increasing order sequence of all distinct values from the degree sequence. It is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than 106 edges. Print the resulting graph.
The first line contains one integer *n* (1<=≤<=*n*<=≤<=300) — the size of the degree set. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≤<=*d**i*<=≤<=1000, *d*1<=&lt;<=*d*2<=&lt;<=...<=&lt;<=*d**n*) — the degree set.
In the first line print one integer *m* (1<=≤<=*m*<=≤<=106) — the number of edges in the resulting graph. It is guaranteed that there exists such a graph that all the conditions hold and it contains no more than 106 edges. Each of the next *m* lines should contain two integers *v**i* and *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*d**n*<=+<=1) — the description of the *i*-th edge.
[ "3\n2 3 4\n", "3\n1 2 3\n" ]
[ "8\n3 1\n4 2\n4 5\n2 5\n5 1\n3 2\n2 1\n5 3\n", "4\n1 2\n1 3\n1 4\n2 3\n" ]
none
[ { "input": "3\n2 3 4", "output": "8\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4" }, { "input": "3\n1 2 3", "output": "4\n1 2\n1 3\n1 4\n2 3" }, { "input": "4\n1 3 4 6", "output": "11\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n2 3\n2 4\n2 5\n3 4\n3 5" }, { "input": "1\n1", "output": "1\n1...
124
0
0
40,140
596
Wilbur and Strings
[ "dfs and similar", "dp", "graphs", "strings" ]
null
null
Wilbur the pig now wants to play with strings. He has found an *n* by *m* table consisting only of the digits from 0 to 9 where the rows are numbered 1 to *n* and the columns are numbered 1 to *m*. Wilbur starts at some square and makes certain moves. If he is at square (*x*, *y*) and the digit *d* (0<=≤<=*d*<=≤<=9) is written at position (*x*, *y*), then he must move to the square (*x*<=+<=*a**d*, *y*<=+<=*b**d*), if that square lies within the table, and he stays in the square (*x*, *y*) otherwise. Before Wilbur makes a move, he can choose whether or not to write the digit written in this square on the white board. All digits written on the whiteboard form some string. Every time a new digit is written, it goes to the end of the current string. Wilbur has *q* strings that he is worried about. For each string *s**i*, Wilbur wants to know whether there exists a starting position (*x*, *y*) so that by making finitely many moves, Wilbur can end up with the string *s**i* written on the white board.
The first line of the input consists of three integers *n*, *m*, and *q* (1<=≤<=*n*,<=*m*,<=*q*<=≤<=200) — the dimensions of the table and the number of strings to process, respectively. Each of the next *n* lines contains *m* digits from 0 and 9 giving the table itself. Then follow 10 lines. The *i*-th of them contains the values *a**i*<=-<=1 and *b**i*<=-<=1 (<=-<=200<=≤<=*a**i*,<=*b**i*<=≤<=200), i.e. the vector that Wilbur uses to make a move from the square with a digit *i*<=-<=1 in it. There are *q* lines that follow. The *i*-th of them will contain a string *s**i* consisting only of digits from 0 to 9. It is guaranteed that the total length of these *q* strings won't exceed 1<=000<=000.
For each of the *q* strings, print "YES" if Wilbur can choose *x* and *y* in order to finish with this string after some finite number of moves. If it's impossible, than print "NO" for the corresponding string.
[ "1 1 2\n0\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n0000000000000\n2413423432432\n", "4 2 5\n01\n23\n45\n67\n0 1\n0 -1\n0 1\n0 -1\n0 1\n0 -1\n0 1\n0 -1\n0 1\n0 -1\n0000000000\n010101011101\n32232232322\n44343222342444324\n6767\n" ]
[ "YES\nNO\n", "YES\nYES\nYES\nNO\nYES\n" ]
In the first sample, there is a 1 by 1 table consisting of the only digit 0. The only move that can be made is staying on the square. The first string can be written on the white board by writing 0 repeatedly. The second string cannot be written as there is no 2 on the table.
[ { "input": "1 1 2\n0\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n1 1\n0000000000000\n2413423432432", "output": "YES\nNO" }, { "input": "4 2 5\n01\n23\n45\n67\n0 1\n0 -1\n0 1\n0 -1\n0 1\n0 -1\n0 1\n0 -1\n0 1\n0 -1\n0000000000\n010101011101\n32232232322\n44343222342444324\n6767", "output": "YES\...
31
204,800
-1
40,224
675
Tree Construction
[ "data structures", "trees" ]
null
null
During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help. You are given a sequence $a$, consisting of $n$ distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. 1. First element $a_1$ becomes the root of the tree. 1. Elements $a_2, a_3, \ldots, a_n$ are added one by one. To add element $a_i$ one needs to traverse the tree starting from the root and using the following rules: The pointer to the current node is set to the root. 1. If $a_i$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. 1. If at some point there is no required child, the new node is created, it is assigned value $a_i$ and becomes the corresponding child of the current node.
The first line of the input contains a single integer $n$ ($2 \leq n \leq 100\,000$) — the length of the sequence $a$. The second line contains $n$ distinct integers $a_i$ ($1 \leq a_i \leq 10^9$) — the sequence $a$ itself.
Output $n - 1$ integers. For all $i &gt; 1$ print the value written in the node that is the parent of the node with value $a_i$ in it.
[ "3\n1 2 3\n", "5\n4 2 3 1 6\n" ]
[ "1 2\n", "4 2 2 4\n" ]
none
[ { "input": "3\n1 2 3", "output": "1 2" }, { "input": "5\n4 2 3 1 6", "output": "4 2 2 4" }, { "input": "2\n1 2", "output": "1" }, { "input": "10\n991309218 517452607 870021923 978357992 136426010 10601767 302627526 883615372 163475700 600546765", "output": "991309218 5174...
46
4,608,000
0
40,303
551
GukiZ and Binary Operations
[ "combinatorics", "implementation", "math", "matrices", "number theory" ]
null
null
We all know that GukiZ often plays with arrays. Now he is thinking about this problem: how many arrays *a*, of length *n*, with non-negative elements strictly less then 2*l* meet the following condition: ? Here operation means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equivalent to &amp;), operation means bitwise OR (in Pascal it is equivalent to , in C/C++/Java/Python it is equivalent to |). Because the answer can be quite large, calculate it modulo *m*. This time GukiZ hasn't come up with solution, and needs you to help him!
First and the only line of input contains four integers *n*, *k*, *l*, *m* (2<=≤<=*n*<=≤<=1018, 0<=≤<=*k*<=≤<=1018, 0<=≤<=*l*<=≤<=64, 1<=≤<=*m*<=≤<=109<=+<=7).
In the single line print the number of arrays satisfying the condition above modulo *m*.
[ "2 1 2 10\n", "2 1 1 3\n", "3 3 2 10\n" ]
[ "3\n", "1\n", "9\n" ]
In the first sample, satisfying arrays are {1, 1}, {3, 1}, {1, 3}. In the second sample, only satisfying array is {1, 1}. In the third sample, satisfying arrays are {0, 3, 3}, {1, 3, 2}, {1, 3, 3}, {2, 3, 1}, {2, 3, 3}, {3, 3, 0}, {3, 3, 1}, {3, 3, 2}, {3, 3, 3}.
[ { "input": "2 1 2 10", "output": "3" }, { "input": "2 1 1 3", "output": "1" }, { "input": "3 3 2 10", "output": "9" }, { "input": "5135 42542 15 4354", "output": "0" }, { "input": "21 21 21 21", "output": "1" }, { "input": "2 0 0 5", "output": "1" ...
61
7,065,600
0
40,378
578
LCS Again
[ "dp", "greedy" ]
null
null
You are given a string *S* of length *n* with each character being one of the first *m* lowercase English letters. Calculate how many different strings *T* of length *n* composed from the first *m* lowercase English letters exist such that the length of LCS (longest common subsequence) between *S* and *T* is *n*<=-<=1. Recall that LCS of two strings *S* and *T* is the longest string *C* such that *C* both in *S* and *T* as a subsequence.
The first line contains two numbers *n* and *m* denoting the length of string *S* and number of first English lowercase characters forming the character set for strings (1<=≤<=*n*<=≤<=100<=000, 2<=≤<=*m*<=≤<=26). The second line contains string *S*.
Print the only line containing the answer.
[ "3 3\naaa\n", "3 3\naab\n", "1 2\na\n", "10 9\nabacadefgh\n" ]
[ "6\n", "11\n", "1\n", "789\n" ]
For the first sample, the 6 possible strings *T* are: aab, aac, aba, aca, baa, caa. For the second sample, the 11 possible strings *T* are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab. For the third sample, the only possible string *T* is b.
[ { "input": "3 3\naaa", "output": "6" }, { "input": "3 3\naab", "output": "11" }, { "input": "1 2\na", "output": "1" }, { "input": "10 9\nabacadefgh", "output": "789" }, { "input": "15 3\nabababababababa", "output": "345" }, { "input": "100 26\njysrixyp...
30
0
0
40,519
496
Distributing Parts
[ "greedy", "sortings" ]
null
null
You are an assistant director in a new musical play. The play consists of *n* musical parts, each part must be performed by exactly one actor. After the casting the director chose *m* actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations. First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, *c**i* and *d**i* (*c**i*<=≤<=*d**i*) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — *a**j* and *b**j* (*a**j*<=≤<=*b**j*) — the pitch of the lowest and the highest notes that are present in the part. The *i*-th actor can perform the *j*-th part if and only if *c**i*<=≤<=*a**j*<=≤<=*b**j*<=≤<=*d**i*, i.e. each note of the part is in the actor's voice range. According to the contract, the *i*-th actor can perform at most *k**i* parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes). The rehearsal starts in two hours and you need to do the assignment quickly!
The first line contains a single integer *n* — the number of parts in the play (1<=≤<=*n*<=≤<=105). Next *n* lines contain two space-separated integers each, *a**j* and *b**j* — the range of notes for the *j*-th part (1<=≤<=*a**j*<=≤<=*b**j*<=≤<=109). The next line contains a single integer *m* — the number of actors (1<=≤<=*m*<=≤<=105). Next *m* lines contain three space-separated integers each, *c**i*, *d**i* and *k**i* — the range of the *i*-th actor and the number of parts that he can perform (1<=≤<=*c**i*<=≤<=*d**i*<=≤<=109, 1<=≤<=*k**i*<=≤<=109).
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print *n* space-separated integers. The *i*-th integer should be the number of the actor who should perform the *i*-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
[ "3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1\n", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1\n" ]
[ "YES\n1 1 2\n", "NO\n" ]
none
[]
46
0
0
40,579
542
Place Your Ad Here
[ "data structures", "sortings" ]
null
null
Ivan Anatolyevich's agency is starting to become famous in the town. They have already ordered and made *n* TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the *i*-th video can only be shown within the time range of [*l**i*,<=*r**i*] (it is not necessary to use the whole segment but the broadcast time should be within this segment). Now it's time to choose a TV channel to broadcast the commercial. Overall, there are *m* TV channels broadcasting in the city, the *j*-th one has *c**j* viewers, and is ready to sell time [*a**j*,<=*b**j*] to broadcast the commercial. Ivan Anatolyevich is facing a hard choice: he has to choose exactly one video *i* and exactly one TV channel *j* to broadcast this video and also a time range to broadcast [*x*,<=*y*]. At that the time range should be chosen so that it is both within range [*l**i*,<=*r**i*] and within range [*a**j*,<=*b**j*]. Let's define the efficiency of the broadcast as value (*y*<=-<=*x*)·*c**j* — the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency!
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105) — the number of commercial videos and channels, respectively. Each of the following *n* lines contains two integers *l**i*, *r**i* (0<=≤<=*l**i*<=≤<=*r**i*<=≤<=109) — the segment of time when it is possible to show the corresponding video. Each of the following *m* lines contains three integers *a**j*, *b**j*, *c**j* (0<=≤<=*a**j*<=≤<=*b**j*<=≤<=109, 1<=≤<=*c**j*<=≤<=109), characterizing the TV channel.
In the first line print an integer — the maximum possible efficiency of the broadcast. If there is no correct way to get a strictly positive efficiency, print a zero. If the maximum efficiency is strictly positive, in the second line also print the number of the video *i* (1<=≤<=*i*<=≤<=*n*) and the number of the TV channel *j* (1<=≤<=*j*<=≤<=*m*) in the most effective broadcast. If there are multiple optimal answers, you can print any of them.
[ "2 3\n7 9\n1 4\n2 8 2\n0 4 1\n8 9 3\n", "1 1\n0 0\n1 1 10\n" ]
[ "4\n2 1\n", "0\n" ]
In the first sample test the most optimal solution is to show the second commercial using the first TV channel at time [2, 4]. The efficiency of such solution is equal to (4 - 2)·2 = 4. In the second sample test Ivan Anatolievich's wish does not meet the options of the TV channel, the segments do not intersect, so the answer is zero.
[]
2,000
5,836,800
0
40,592
962
Simple Cycles Edges
[ "dfs and similar", "graphs", "trees" ]
null
null
You are given an undirected graph, consisting of $n$ vertices and $m$ edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself). A cycle in a graph is called a simple, if it contains each own vertex exactly once. So simple cycle doesn't allow to visit a vertex more than once in a cycle. Determine the edges, which belong to exactly on one simple cycle.
The first line contain two integers $n$ and $m$ $(1 \le n \le 100\,000$, $0 \le m \le \min(n \cdot (n - 1) / 2, 100\,000))$ — the number of vertices and the number of edges. Each of the following $m$ lines contain two integers $u$ and $v$ ($1 \le u, v \le n$, $u \neq v$) — the description of the edges.
In the first line print the number of edges, which belong to exactly one simple cycle. In the second line print the indices of edges, which belong to exactly one simple cycle, in increasing order. The edges are numbered from one in the same order as they are given in the input.
[ "3 3\n1 2\n2 3\n3 1\n", "6 7\n2 3\n3 4\n4 2\n1 2\n1 5\n5 6\n6 1\n", "5 6\n1 2\n2 3\n2 4\n4 3\n2 5\n5 3\n" ]
[ "3\n1 2 3 \n", "6\n1 2 3 5 6 7 \n", "0\n\n" ]
none
[ { "input": "3 3\n1 2\n2 3\n3 1", "output": "3\n1 2 3 " }, { "input": "6 7\n2 3\n3 4\n4 2\n1 2\n1 5\n5 6\n6 1", "output": "6\n1 2 3 5 6 7 " }, { "input": "5 6\n1 2\n2 3\n2 4\n4 3\n2 5\n5 3", "output": "0" }, { "input": "4 5\n1 2\n2 3\n3 4\n4 1\n1 3", "output": "0" }, {...
857
40,243,200
3
40,752
172
Calendar Reform
[ "*special", "number theory" ]
null
null
Reforms have started in Berland again! At this time, the Parliament is discussing the reform of the calendar. To make the lives of citizens of Berland more varied, it was decided to change the calendar. As more and more people are complaining that "the years fly by...", it was decided that starting from the next year the number of days per year will begin to grow. So the coming year will have exactly *a* days, the next after coming year will have *a*<=+<=1 days, the next one will have *a*<=+<=2 days and so on. This schedule is planned for the coming *n* years (in the *n*-th year the length of the year will be equal *a*<=+<=*n*<=-<=1 day). No one has yet decided what will become of months. An MP Palevny made the following proposal. - The calendar for each month is comfortable to be printed on a square sheet of paper. We are proposed to make the number of days in each month be the square of some integer. The number of days per month should be the same for each month of any year, but may be different for different years. - The number of days in each year must be divisible by the number of days per month in this year. This rule ensures that the number of months in each year is an integer. - The number of days per month for each year must be chosen so as to save the maximum amount of paper to print the calendars. In other words, the number of days per month should be as much as possible. These rules provide an unambiguous method for choosing the number of days in each month for any given year length. For example, according to Palevny's proposition, a year that consists of 108 days will have three months, 36 days each. The year that consists of 99 days will have 11 months, 9 days each, and a year of 365 days will have 365 months, one day each. The proposal provoked heated discussion in the community, the famous mathematician Perelmanov quickly calculated that if the proposal is supported, then in a period of *n* years, beginning with the year that has *a* days, the country will spend *p* sheets of paper to print a set of calendars for these years. Perelmanov's calculations take into account the fact that the set will contain one calendar for each year and each month will be printed on a separate sheet. Repeat Perelmanov's achievement and print the required number *p*. You are given positive integers *a* and *n*. Perelmanov warns you that your program should not work longer than four seconds at the maximum test.
The only input line contains a pair of integers *a*, *n* (1<=≤<=*a*,<=*n*<=≤<=107; *a*<=+<=*n*<=-<=1<=≤<=107).
Print the required number *p*. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use cin, cout streams or the %I64d specifier.
[ "25 3\n", "50 5\n" ]
[ "30\n", "125\n" ]
A note to the first sample test. A year of 25 days will consist of one month containing 25 days. A year of 26 days will consist of 26 months, one day each. A year of 27 days will have three months, 9 days each.
[ { "input": "25 3", "output": "30" }, { "input": "50 5", "output": "125" }, { "input": "1 1", "output": "1" }, { "input": "1 2", "output": "3" }, { "input": "1 10", "output": "38" }, { "input": "1 5000000", "output": "8224640917276" }, { "in...
156
0
3
40,792
215
Hot Days
[ "greedy" ]
null
null
The official capital and the cultural capital of Berland are connected by a single road running through *n* regions. Each region has a unique climate, so the *i*-th (1<=≤<=*i*<=≤<=*n*) region has a stable temperature of *t**i* degrees in summer. This summer a group of *m* schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the *i*-th region and has *k* schoolchildren, then the temperature inside the bus is *t**i*<=+<=*k* degrees. Of course, nobody likes it when the bus is hot. So, when the bus drives through the *i*-th region, if it has more than *T**i* degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as *x**i* rubles and it is charged in each region where the temperature in the bus exceeds the limit. To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the *i*-th region will cost the organizers *cost**i* rubles. Please note that sorting children into buses takes no money. Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
The first input line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=106) — the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next *n* lines contain four integers each: the *i*-th line contains *t**i*, *T**i*, *x**i* and *cost**i* (1<=≤<=*t**i*,<=*T**i*,<=*x**i*,<=*cost**i*<=≤<=106). The numbers in the lines are separated by single spaces.
Print the only integer — the minimum number of roubles the organizers will have to spend to transport all schoolchildren. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
[ "2 10\n30 35 1 100\n20 35 10 10\n", "3 100\n10 30 1000 1\n5 10 1000 3\n10 40 1000 100000\n" ]
[ "120\n", "200065\n" ]
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.
[ { "input": "2 10\n30 35 1 100\n20 35 10 10", "output": "120" }, { "input": "3 100\n10 30 1000 1\n5 10 1000 3\n10 40 1000 100000", "output": "200065" }, { "input": "10 1\n8 6 3 4\n9 10 7 7\n1 3 9 5\n10 9 4 2\n1 10 2 10\n1 1 8 5\n5 5 9 2\n5 8 4 3\n4 4 9 7\n5 7 5 10", "output": "88" }...
2,000
9,728,000
0
40,818
459
Pashmak and Parmida's problem
[ "data structures", "divide and conquer", "sortings" ]
null
null
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak. There is a sequence *a* that consists of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Let's denote *f*(*l*,<=*r*,<=*x*) the number of indices *k* such that: *l*<=≤<=*k*<=≤<=*r* and *a**k*<==<=*x*. His task is to calculate the number of pairs of indicies *i*,<=*j* (1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*) such that *f*(1,<=*i*,<=*a**i*)<=&gt;<=*f*(*j*,<=*n*,<=*a**j*). Help Pashmak with the test.
The first line of the input contains an integer *n* (1<=≤<=*n*<=≤<=106). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
Print a single integer — the answer to the problem.
[ "7\n1 2 1 1 2 2 1\n", "3\n1 1 1\n", "5\n1 2 3 4 5\n" ]
[ "8\n", "1\n", "0\n" ]
none
[ { "input": "7\n1 2 1 1 2 2 1", "output": "8" }, { "input": "3\n1 1 1", "output": "1" }, { "input": "5\n1 2 3 4 5", "output": "0" }, { "input": "24\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "output": "114" }, { "input": "1\n1", "output": "0" }, { ...
31
0
0
40,850
321
Ciel and Flipboard
[ "dp", "greedy", "math" ]
null
null
Fox Ciel has a board with *n* rows and *n* columns, there is one integer in each cell. It's known that *n* is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size *x* rows and *x* columns, then all numbers in it will be multiplied by -1. Return the maximal sum of numbers in the board that she can get by these operations.
The first line contains an integer *n*, (1<=≤<=*n*<=≤<=33, and *n* is an odd integer) — the size of the board. Each of the next *n* lines contains *n* integers — the numbers in the board. Each number doesn't exceed 1000 by its absolute value.
Output a single integer: the maximal sum of numbers in the board that can be accomplished.
[ "3\n-1 -1 1\n-1 1 -1\n1 -1 -1\n", "5\n-2 0 0 0 -2\n0 -2 0 -2 0\n0 0 -2 0 0\n0 -2 0 -2 0\n-2 0 0 0 -2\n" ]
[ "9\n", "18\n" ]
In the first test, we can apply this operation twice: first on the top left 2 × 2 sub-board, then on the bottom right 2 × 2 sub-board. Then all numbers will become positive. <img class="tex-graphics" src="https://espresso.codeforces.com/c3426b4faf54a7f3b8dfc0e18e955f907760fe71.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[]
280
1,433,600
0
41,083
632
Magic Matrix
[ "brute force", "divide and conquer", "graphs", "matrices", "trees" ]
null
null
You're given a matrix *A* of size *n*<=×<=*n*. Let's call the matrix with nonnegative elements magic if it is symmetric (so *a**ij*<==<=*a**ji*), *a**ii*<==<=0 and *a**ij*<=≤<=*max*(*a**ik*,<=*a**jk*) for all triples *i*,<=*j*,<=*k*. Note that *i*,<=*j*,<=*k* do not need to be distinct. Determine if the matrix is magic. As the input/output can reach very huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
The first line contains integer *n* (1<=≤<=*n*<=≤<=2500) — the size of the matrix *A*. Each of the next *n* lines contains *n* integers *a**ij* (0<=≤<=*a**ij*<=&lt;<=109) — the elements of the matrix *A*. Note that the given matrix not necessarily is symmetric and can be arbitrary.
Print ''MAGIC" (without quotes) if the given matrix *A* is magic. Otherwise print ''NOT MAGIC".
[ "3\n0 1 2\n1 0 2\n2 2 0\n", "2\n0 1\n2 3\n", "4\n0 1 2 3\n1 0 3 4\n2 3 0 5\n3 4 5 0\n" ]
[ "MAGIC\n", "NOT MAGIC\n", "NOT MAGIC\n" ]
none
[ { "input": "3\n0 1 2\n1 0 2\n2 2 0", "output": "MAGIC" }, { "input": "2\n0 1\n2 3", "output": "NOT MAGIC" }, { "input": "4\n0 1 2 3\n1 0 3 4\n2 3 0 5\n3 4 5 0", "output": "NOT MAGIC" }, { "input": "5\n0 2 5 9 5\n2 0 5 9 5\n5 5 0 9 4\n9 9 9 0 9\n5 5 4 9 0", "output": "MAGI...
61
0
0
41,126
818
Level Generation
[ "binary search", "math", "ternary search" ]
null
null
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly *n**i* vertices in the graph representing level *i*, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices *u* and *v* is called a bridge if this edge belongs to every path between *u* and *v* (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given *q* numbers *n*1,<=*n*2,<=...,<=*n**q*, for each *i* tell the maximum number of edges in a graph with *n**i* vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.
The first line of input file contains a positive integer *q* (1<=≤<=*q*<=≤<=100<=000) — the number of graphs Ivan needs to construct. Then *q* lines follow, *i*-th line contains one positive integer *n**i* (1<=≤<=*n**i*<=≤<=2·109) — the number of vertices in *i*-th graph. Note that in hacks you have to use *q*<==<=1.
Output *q* numbers, *i*-th of them must be equal to the maximum number of edges in *i*-th graph.
[ "3\n3\n4\n6\n" ]
[ "2\n3\n6\n" ]
In the first example it is possible to construct these graphs: 1. 1 - 2, 1 - 3; 1. 1 - 2, 1 - 3, 2 - 4; 1. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.
[ { "input": "3\n3\n4\n6", "output": "2\n3\n6" }, { "input": "10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10", "output": "0\n1\n2\n3\n4\n6\n7\n8\n10\n12" }, { "input": "1\n212055293", "output": "424069398" }, { "input": "1\n508427854", "output": "1016791932" }, { "input": "1\n39...
998
6,963,200
3
41,134
989
A Shade of Moonlight
[ "binary search", "geometry", "math", "sortings", "two pointers" ]
null
null
"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino. "See? The clouds are coming." Kanno gazes into the distance. "That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $0$. There are $n$ clouds floating in the sky. Each cloud has the same length $l$. The $i$-th initially covers the range of $(x_i, x_i + l)$ (endpoints excluded). Initially, it moves at a velocity of $v_i$, which equals either $1$ or $-1$. Furthermore, no pair of clouds intersect initially, that is, for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$. With a wind velocity of $w$, the velocity of the $i$-th cloud becomes $v_i + w$. That is, its coordinate increases by $v_i + w$ during each unit of time. Note that the wind can be strong and clouds can change their direction. You are to help Mino count the number of pairs $(i, j)$ ($i &lt; j$), such that with a proper choice of wind velocity $w$ not exceeding $w_\mathrm{max}$ in absolute value (possibly negative and/or fractional), the $i$-th and $j$-th clouds both cover the moon at the same future moment. This $w$ doesn't need to be the same across different pairs.
The first line contains three space-separated integers $n$, $l$, and $w_\mathrm{max}$ ($1 \leq n \leq 10^5$, $1 \leq l, w_\mathrm{max} \leq 10^8$) — the number of clouds, the length of each cloud and the maximum wind speed, respectively. The $i$-th of the following $n$ lines contains two space-separated integers $x_i$ and $v_i$ ($-10^8 \leq x_i \leq 10^8$, $v_i \in \{-1, 1\}$) — the initial position and the velocity of the $i$-th cloud, respectively. The input guarantees that for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$.
Output one integer — the number of unordered pairs of clouds such that it's possible that clouds from each pair cover the moon at the same future moment with a proper choice of wind velocity $w$.
[ "5 1 2\n-2 1\n2 1\n3 -1\n5 -1\n7 -1\n", "4 10 1\n-20 1\n-10 -1\n0 1\n10 -1\n" ]
[ "4\n", "1\n" ]
In the first example, the initial positions and velocities of clouds are illustrated below. The pairs are: - $(1, 3)$, covering the moon at time $2.5$ with $w = -0.4$; - $(1, 4)$, covering the moon at time $3.5$ with $w = -0.6$; - $(1, 5)$, covering the moon at time $4.5$ with $w = -0.7$; - $(2, 5)$, covering the moon at time $2.5$ with $w = -2$. Below is the positions of clouds at time $2.5$ with $w = -0.4$. At this moment, the $1$-st and $3$-rd clouds both cover the moon. In the second example, the only pair is $(1, 4)$, covering the moon at time $15$ with $w = 0$. Note that all the times and wind velocities given above are just examples among infinitely many choices.
[ { "input": "5 1 2\n-2 1\n2 1\n3 -1\n5 -1\n7 -1", "output": "4" }, { "input": "4 10 1\n-20 1\n-10 -1\n0 1\n10 -1", "output": "1" }, { "input": "1 100000000 98765432\n73740702 1", "output": "0" }, { "input": "10 2 3\n-1 -1\n-4 1\n-6 -1\n1 1\n10 -1\n-8 -1\n6 1\n8 1\n4 -1\n-10 -1...
841
6,860,800
3
41,189
160
Unlucky Ticket
[ "greedy", "sortings" ]
null
null
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half. But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half. For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2<=&gt;<=1 and 4<=&gt;<=2), ticket 0135 also meets the criterion (the sought correspondence is 0<=&lt;<=3 and 1<=&lt;<=5), and ticket 3754 does not meet the criterion. You have a ticket in your hands, it contains 2*n* digits. Your task is to check whether it meets the unluckiness criterion.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). The second line contains a string that consists of 2*n* digits and defines your ticket.
In the first line print "YES" if the ticket meets the unluckiness criterion. Otherwise, print "NO" (without the quotes).
[ "2\n2421\n", "2\n0135\n", "2\n3754\n" ]
[ "YES\n", "YES\n", "NO\n" ]
none
[ { "input": "2\n2421", "output": "YES" }, { "input": "2\n0135", "output": "YES" }, { "input": "2\n3754", "output": "NO" }, { "input": "1\n33", "output": "NO" }, { "input": "2\n3444", "output": "NO" }, { "input": "3\n221323", "output": "YES" }, {...
92
0
0
41,389
626
Jerry's Protest
[ "brute force", "combinatorics", "dp", "probabilities" ]
null
null
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing *n* balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds. Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?
The first line of input contains a single integer *n* (2<=≤<=*n*<=≤<=2000) — the number of balls in the jar. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=5000) — the number written on the *i*th ball. It is guaranteed that no two balls have the same number.
Print a single real value — the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6. Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if .
[ "2\n1 2\n", "3\n1 2 10\n" ]
[ "0.0000000000\n", "0.0740740741\n" ]
In the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total. In the second case, each game could've had three outcomes — 10 - 2, 10 - 1, or 2 - 1. Jerry has a higher total if and only if Andrew won 2 - 1 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3c0ec296285f607c66d594132fb91e5e5f2bb007.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "2\n1 2", "output": "0.0000000000" }, { "input": "3\n1 2 10", "output": "0.0740740741" }, { "input": "3\n1 2 3", "output": "0.0000000000" }, { "input": "4\n2 4 1 3", "output": "0.0416666667" }, { "input": "11\n1 2 4 8 16 32 64 128 256 512 1024", "ou...
1,403
7,270,400
3
41,478
111
Petya and Coloring
[ "combinatorics", "dp" ]
D. Petya and Coloring
5
256
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size *n*<=×<=*m* (*n* rows, *m* columns) in *k* colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.
The first line contains space-separated integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=1000,<=1<=≤<=*k*<=≤<=106) — the board's vertical and horizontal sizes and the number of colors respectively.
Print the answer to the problem. As the answer can be quite a large number, you should print it modulo 109<=+<=7 (1000000007).
[ "2 2 1\n", "2 2 2\n", "3 2 2\n" ]
[ "1\n", "8\n", "40\n" ]
none
[ { "input": "2 2 1", "output": "1" }, { "input": "2 2 2", "output": "8" }, { "input": "3 2 2", "output": "40" }, { "input": "7 8 15", "output": "422409918" }, { "input": "5 3 1", "output": "1" }, { "input": "5 100 1", "output": "1" }, { "inp...
4,242
15,155,200
3.547571
41,553
757
Felicity is Coming!
[ "data structures", "hashing", "sortings", "strings" ]
null
null
It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has *n* gyms. The *i*-th gym has *g**i* Pokemon in it. There are *m* distinct Pokemon types in the Himalayan region numbered from 1 to *m*. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation *f* of {1,<=2,<=...,<=*m*}, such that *f*(*x*)<==<=*y* means that a Pokemon of type *x* evolves into a Pokemon of type *y*. The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol. Two evolution plans *f*1 and *f*2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an *i* such that *f*1(*i*)<=≠<=*f*2(*i*). Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109<=+<=7.
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=105, 1<=≤<=*m*<=≤<=106) — the number of gyms and the number of Pokemon types. The next *n* lines contain the description of Pokemons in the gyms. The *i*-th of these lines begins with the integer *g**i* (1<=≤<=*g**i*<=≤<=105) — the number of Pokemon in the *i*-th gym. After that *g**i* integers follow, denoting types of the Pokemons in the *i*-th gym. Each of these integers is between 1 and *m*. The total number of Pokemons (the sum of all *g**i*) does not exceed 5·105.
Output the number of valid evolution plans modulo 109<=+<=7.
[ "2 3\n2 1 2\n2 2 3\n", "1 3\n3 1 2 3\n", "2 4\n2 1 2\n3 2 3 4\n", "2 2\n3 2 2 1\n2 1 2\n", "3 7\n2 1 2\n2 3 4\n3 5 6 7\n" ]
[ "1\n", "6\n", "2\n", "1\n", "24\n" ]
In the first case, the only possible evolution plan is: In the second case, any permutation of (1,  2,  3) is valid. In the third case, there are two possible plans: In the fourth case, the only possible evolution plan is:
[ { "input": "2 3\n2 1 2\n2 2 3", "output": "1" }, { "input": "1 3\n3 1 2 3", "output": "6" }, { "input": "2 4\n2 1 2\n3 2 3 4", "output": "2" }, { "input": "2 2\n3 2 2 1\n2 1 2", "output": "1" }, { "input": "3 7\n2 1 2\n2 3 4\n3 5 6 7", "output": "24" }, { ...
77
4,608,000
0
41,557
327
Block Tower
[ "constructive algorithms", "dfs and similar", "graphs" ]
null
null
After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with *n* rows and *m* columns (it contains *n*<=×<=*m* cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any building. The rest of cells are empty. In some empty cell Iahub can build exactly one tower of two following types: 1. Blue towers. Each has population limit equal to 100. 1. Red towers. Each has population limit equal to 200. However, it can be built in some cell only if in that moment at least one of the neighbouring cells has a Blue Tower. Two cells are neighbours is they share a side. Iahub is also allowed to destroy a building from any cell. He can do this operation as much as he wants. After destroying a building, the other buildings are not influenced, and the destroyed cell becomes empty (so Iahub can build a tower in this cell if needed, see the second example for such a case). Iahub can convince as many population as he wants to come into his city. So he needs to configure his city to allow maximum population possible. Therefore he should find a sequence of operations that builds the city in an optimal way, so that total population limit is as large as possible. He says he's the best at this game, but he doesn't have the optimal solution. Write a program that calculates the optimal one, to show him that he's not as good as he thinks.
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=500). Each of the next *n* lines contains *m* characters, describing the grid. The *j*-th character in the *i*-th line is '.' if you're allowed to build at the cell with coordinates (*i*,<=*j*) a tower (empty cell) or '#' if there is a big hole there.
Print an integer *k* in the first line (0<=≤<=*k*<=≤<=106) — the number of operations Iahub should perform to obtain optimal result. Each of the following *k* lines must contain a single operation in the following format: 1. «B x y» (1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*) — building a blue tower at the cell (*x*,<=*y*); 1. «R x y» (1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*) — building a red tower at the cell (*x*,<=*y*); 1. «D x y» (1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*) — destroying a tower at the cell (*x*,<=*y*). If there are multiple solutions you can output any of them. Note, that you shouldn't minimize the number of operations.
[ "2 3\n..#\n.#.\n", "1 3\n...\n" ]
[ "4\nB 1 1\nR 1 2\nR 2 1\nB 2 3\n", "5\nB 1 1\nB 1 2\nR 1 3\nD 1 2\nR 1 2\n" ]
none
[]
124
0
0
41,591
54
Cutting Jigsaw Puzzle
[ "hashing", "implementation" ]
B. Cutting Jigsaw Puzzle
2
256
The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one. Soon the Hedgehog came up with a brilliant idea: instead of buying ready-made puzzles, one can take his own large piece of paper with some picture and cut it into many small rectangular pieces, then mix them and solve the resulting puzzle, trying to piece together the picture. The resulting task is even more challenging than the classic puzzle: now all the fragments have the same rectangular shape, and one can assemble the puzzle only relying on the picture drawn on the pieces. All puzzle pieces turn out to be of the same size *X*<=×<=*Y*, because the picture is cut first by horizontal cuts with the pitch of *X*, then with vertical cuts with the pitch of *Y*. If we denote the initial size of the picture as *A*<=×<=*B*, then *A* must be divisible by *X* and *B* must be divisible by *Y* (*X* and *Y* are integer numbers). However, not every such cutting of the picture will result in a good puzzle. The Hedgehog finds a puzzle good if no two pieces in it are the same (It is allowed to rotate the pieces when comparing them, but it is forbidden to turn them over). Your task is to count for a given picture the number of good puzzles that you can make from it, and also to find the puzzle with the minimal piece size.
The first line contains two numbers *A* and *B* which are the sizes of the picture. They are positive integers not exceeding 20. Then follow *A* lines containing *B* symbols each, describing the actual picture. The lines only contain uppercase English letters.
In the first line print the number of possible good puzzles (in other words, the number of pairs (*X*,<=*Y*) such that the puzzle with the corresponding element sizes will be good). This number should always be positive, because the whole picture is a good puzzle itself. In the second line print two numbers — the sizes *X* and *Y* of the smallest possible element among all good puzzles. The comparison is made firstly by the area *XY* of one element and secondly — by the length *X*.
[ "2 4\nABDC\nABDC\n", "2 6\nABCCBA\nABCCBA\n" ]
[ "3\n2 1\n", "1\n2 6\n" ]
The picture in the first sample test has the following good puzzles: (2, 1), (2, 2), (2, 4).
[ { "input": "2 4\nABDC\nABDC", "output": "3\n2 1" }, { "input": "2 6\nABCCBA\nABCCBA", "output": "1\n2 6" }, { "input": "2 2\nAB\nCD", "output": "4\n1 1" }, { "input": "4 6\nABABAC\nBABABC\nABABAC\nCCCCCA", "output": "4\n2 3" }, { "input": "1 12\nABAAADCAAABX", ...
62
0
-1
41,609
141
Queue
[ "constructive algorithms", "greedy", "sortings" ]
null
null
In the Main Berland Bank *n* people stand in a queue at the cashier, everyone knows his/her height *h**i*, and the heights of the other people in the queue. Each of them keeps in mind number *a**i* — how many people who are taller than him/her and stand in queue in front of him. After a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order. When the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number *a**i*. Your task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers *h**i* — the heights of people in the queue, so that the numbers *a**i* are correct.
The first input line contains integer *n* — the number of people in the queue (1<=≤<=*n*<=≤<=3000). Then *n* lines contain descriptions of the people as "*name**i* *a**i*" (one description on one line), where *name**i* is a non-empty string consisting of lowercase Latin letters whose length does not exceed 10 characters (the *i*-th person's name), *a**i* is an integer (0<=≤<=*a**i*<=≤<=*n*<=-<=1), that represents the number of people who are higher and stand in the queue in front of person *i*. It is guaranteed that all names are different.
If there's no acceptable order of the people in the queue, print the single line containing "-1" without the quotes. Otherwise, print in *n* lines the people as "*name**i* *h**i*", where *h**i* is the integer from 1 to 109 (inclusive), the possible height of a man whose name is *name**i*. Print the people in the order in which they stand in the queue, starting from the head of the queue and moving to its tail. Numbers *h**i* are not necessarily unique.
[ "4\na 0\nb 2\nc 0\nd 0\n", "4\nvasya 0\npetya 1\nmanya 3\ndunay 3\n" ]
[ "a 150\nc 170\nd 180\nb 160\n", "-1\n" ]
none
[ { "input": "4\na 0\nb 2\nc 0\nd 0", "output": "a 150\nc 170\nd 180\nb 160" }, { "input": "4\nvasya 0\npetya 1\nmanya 3\ndunay 3", "output": "-1" }, { "input": "1\nze 0", "output": "ze 150" }, { "input": "3\nl 0\nmybiqxmnqq 0\nsoxkyvgd 0", "output": "l 150\nmybiqxmnqq 160\...
30
0
0
41,611
0
none
[ "none" ]
null
null
Polycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them). Polycarpus wants to save these pictures on his laptop, but the problem is, laptops do not allow to write hieroglyphs circles. So Polycarp had to break each circle and write down all of its hieroglyphs in a clockwise order in one line. A line obtained from the first circle will be called *a*, and the line obtained from the second one will be called *b*. There are quite many ways to break hieroglyphic circles, so Polycarpus chooses the method, that makes the length of the largest substring of string *a*, which occurs as a subsequence in string *b*, maximum. Help Polycarpus — find the maximum possible length of the desired substring (subsequence) if the first and the second circles are broken optimally. The length of string *s* is the number of characters in it. If we denote the length of string *s* as |*s*|, we can write the string as *s*<==<=*s*1*s*2... *s*|*s*|. A substring of *s* is a non-empty string *x*<==<=*s*[*a*... *b*]<==<=*s**a**s**a*<=+<=1... *s**b* (1<=≤<=*a*<=≤<=*b*<=≤<=|*s*|). For example, "code" and "force" are substrings of "codeforces", while "coders" is not. A subsequence of *s* is a non-empty string *y*<==<=*s*[*p*1*p*2... *p*|*y*|]<==<=*s**p*1*s**p*2... *s**p*|*y*| (1<=≤<=*p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p*|*y*|<=≤<=|*s*|). For example, "coders" is a subsequence of "codeforces".
The first line contains two integers *l**a* and *l**b* (1<=≤<=*l**a*,<=*l**b*<=≤<=1000000) — the number of hieroglyphs in the first and second circles, respectively. Below, due to difficulties with encoding of Berland hieroglyphs, they are given as integers from 1 to 106. The second line contains *l**a* integers — the hieroglyphs in the first picture, in the clockwise order, starting with one of them. The third line contains *l**b* integers — the hieroglyphs in the second picture, in the clockwise order, starting with one of them. It is guaranteed that the first circle doesn't contain a hieroglyph, which occurs twice. The second circle also has this property.
Print a single number — the maximum length of the common substring and subsequence. If at any way of breaking the circles it does not exist, print 0.
[ "5 4\n1 2 3 4 5\n1 3 5 6\n", "4 6\n1 3 5 2\n1 2 3 4 5 6\n", "3 3\n1 2 3\n3 2 1\n" ]
[ "2\n", "3\n", "2\n" ]
In the first test Polycarpus picks a string that consists of hieroglyphs 5 and 1, and in the second sample — from hieroglyphs 1, 3 and 5.
[ { "input": "5 4\n1 2 3 4 5\n1 3 5 6", "output": "2" }, { "input": "4 6\n1 3 5 2\n1 2 3 4 5 6", "output": "3" }, { "input": "3 3\n1 2 3\n3 2 1", "output": "2" }, { "input": "6 3\n1 2 3 4 5 6\n3 5 1", "output": "1" }, { "input": "1 1\n1\n2", "output": "0" }, ...
62
0
0
41,650
120
Minimum Sum
[ "divide and conquer", "geometry", "sortings" ]
null
null
You are given a set of *n* vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector *v**i*<==<=(*x**i*,<=*y**i*) can be transformed into one of the following four vectors: - *v**i*1<==<=(*x**i*,<=*y**i*), - *v**i*2<==<=(<=-<=*x**i*,<=*y**i*), - *v**i*3<==<=(*x**i*,<=<=-<=*y**i*), - *v**i*4<==<=(<=-<=*x**i*,<=<=-<=*y**i*). You should find two vectors from the set and determine which of their coordinates should be multiplied by -1 so that the absolute value of the sum of the resulting vectors was minimally possible. More formally, you should choose two vectors *v**i*, *v**j* (1<=≤<=*i*,<=*j*<=≤<=*n*,<=*i*<=≠<=*j*) and two numbers *k*1, *k*2 (1<=≤<=*k*1,<=*k*2<=≤<=4), so that the value of the expression |*v**i**k*1<=+<=*v**j**k*2| were minimum.
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=105). Then *n* lines contain vectors as pairs of integers "*x**i* *y**i*" (<=-<=10000<=≤<=*x**i*,<=*y**i*<=≤<=10000), one pair per line.
Print on the first line four space-separated numbers "*i* *k*1 *j* *k*2" — the answer to the problem. If there are several variants the absolute value of whose sums is minimum, you can print any of them.
[ "5\n-7 -3\n9 0\n-8 6\n7 -8\n4 -5\n", "5\n3 2\n-4 7\n-6 0\n-8 4\n5 1\n" ]
[ "3 2 4 2\n", "3 4 5 4\n" ]
A sum of two vectors *v* = (*x*<sub class="lower-index">*v*</sub>, *y*<sub class="lower-index">*v*</sub>) and *u* = (*x*<sub class="lower-index">*u*</sub>, *y*<sub class="lower-index">*u*</sub>) is vector *s* = *v* + *u* = (*x*<sub class="lower-index">*v*</sub> + *x*<sub class="lower-index">*u*</sub>, *y*<sub class="lower-index">*v*</sub> + *y*<sub class="lower-index">*u*</sub>). An absolute value of vector *v* = (*x*, *y*) is number <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d6c16bed0f57e40cf156237736f342487ab25fb8.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample there are several valid answers, such as: (3 1 4 2), (3 1 4 4), (3 4 4 1), (3 4 4 3), (4 1 3 2), (4 1 3 4), (4 2 3 1).
[ { "input": "5\n-7 -3\n9 0\n-8 6\n7 -8\n4 -5", "output": "3 2 4 2" }, { "input": "5\n3 2\n-4 7\n-6 0\n-8 4\n5 1", "output": "3 4 5 4" }, { "input": "2\n-4 -2\n-2 1", "output": "1 4 2 3" }, { "input": "3\n-4 -3\n-4 -5\n-1 0", "output": "2 4 1 1" }, { "input": "10\n5...
216
2,355,200
-1
41,797
62
Tyndex.Brome
[ "binary search", "implementation" ]
B. Tyndex.Brome
2
256
Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the *F* error is calculated by the following rules: - for every letter *c**i* from the potential address *c* the closest position *j* of the letter *c**i* in the address (*s*) entered by the user is found. The absolute difference |*i*<=-<=*j*| of these positions is added to *F*. So for every *i* (1<=≤<=*i*<=≤<=|*c*|) the position *j* is chosen such, that *c**i*<==<=*s**j*, and |*i*<=-<=*j*| is minimal possible. - if no such letter *c**i* exists in the address entered by the user, then the length of the potential address |*c*| is added to *F*. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the *F* function for an address given by the user and some set of potential addresses. Good luck!
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=105). They are the number of potential addresses and the length of the address entered by the user. The next line contains *k* lowercase Latin letters. They are the address entered by the user (*s*). Each next *i*-th (1<=≤<=*i*<=≤<=*n*) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105.
On each *n* line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
[ "2 10\ncodeforces\ncodeforces\ncodehorses\n", "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese\n" ]
[ "0\n12\n", "18\n14\n36\n47\n14\n29\n30\n0\n84\n" ]
none
[ { "input": "2 10\ncodeforces\ncodeforces\ncodehorses", "output": "0\n12" }, { "input": "9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese", "output": "18\n14\n36\n47\n14\n29\n30\n0\n84" }, { "input": "3 3\nbyg\ndwg\nl\nx", "outp...
1,714
4,710,400
3.562726
41,876
226
Anniversary
[ "data structures", "implementation", "math", "matrices", "number theory" ]
null
null
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations. Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set *A*, consisting of numbers *l*, *l*<=+<=1, *l*<=+<=2, ..., *r*; let's consider all its *k*-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one. Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where *F*1<==<=1, *F*2<==<=1, *F**n*<==<=*F**n*<=-<=1<=+<=*F**n*<=-<=2 for *n*<=≥<=3. Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by *m*.
The first line contains four space-separated integers *m*, *l*, *r* and *k* (1<=≤<=*m*<=≤<=109; 1<=≤<=*l*<=&lt;<=*r*<=≤<=1012; 2<=≤<=*k*<=≤<=*r*<=-<=*l*<=+<=1). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Print a single integer — the residue from dividing the sought greatest common divisor by *m*.
[ "10 1 8 2\n", "10 1 8 3\n" ]
[ "3\n", "1\n" ]
none
[ { "input": "10 1 8 2", "output": "3" }, { "input": "10 1 8 3", "output": "1" }, { "input": "10 1 20 2", "output": "5" }, { "input": "4 1 10 2", "output": "1" }, { "input": "1000000000 999000000000 1000000000000 1000000001", "output": "1" }, { "input": ...
248
1,843,200
3
41,972
709
Checkpoints
[ "greedy", "implementation", "sortings" ]
null
null
Vasya takes part in the orienteering competition. There are *n* checkpoints located along the line at coordinates *x*1,<=*x*2,<=...,<=*x**n*. Vasya starts at the point with coordinate *a*. His goal is to visit at least *n*<=-<=1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order. Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
The first line of the input contains two integers *n* and *a* (1<=≤<=*n*<=≤<=100<=000, <=-<=1<=000<=000<=≤<=*a*<=≤<=1<=000<=000) — the number of checkpoints and Vasya's starting position respectively. The second line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=1<=000<=000<=≤<=*x**i*<=≤<=1<=000<=000) — coordinates of the checkpoints.
Print one integer — the minimum distance Vasya has to travel in order to visit at least *n*<=-<=1 checkpoint.
[ "3 10\n1 7 12\n", "2 0\n11 -10\n", "5 0\n0 0 1000 0 0\n" ]
[ "7\n", "10\n", "0\n" ]
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7. In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point  - 10.
[ { "input": "3 10\n1 7 12", "output": "7" }, { "input": "2 0\n11 -10", "output": "10" }, { "input": "5 0\n0 0 1000 0 0", "output": "0" }, { "input": "1 0\n0", "output": "0" }, { "input": "2 1\n4 -8", "output": "3" }, { "input": "3 4\n4 2 4", "output...
202
31,334,400
3
42,038
534
Berland Local Positioning System
[ "constructive algorithms", "greedy", "hashing", "implementation" ]
null
null
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are *n* bus stops located along the street, the *i*-th of them is located at the distance *a**i* from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, *a**i*<=&lt;<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number *n*, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop *n*. During the day, the bus runs non-stop on this route. The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number. One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order. For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: , then the request about this segment of the path will have form: 3,<=4,<=5,<=5,<=6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have form: 1,<=2,<=2,<=3,<=3,<=4,<=5,<=5,<=6. You will have to repeat the Berland programmers achievement and implement this function.
The first line contains integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of stops. The second line contains *n* integers (1<=≤<=*a**i*<=≤<=109) — the distance from the *i*-th stop to the central square. The numbers in the second line go in the increasing order. The third line contains integer *m* (1<=≤<=*m*<=≤<=4·105) — the number of stops the bus visited on some segment of the path. The fourth line contains *m* integers (1<=≤<=*b**i*<=≤<=*n*) — the sorted list of numbers of the stops visited by the bus on the segment of the path. The number of a stop occurs as many times as it was visited by a bus. It is guaranteed that the query corresponds to some segment of the path.
In the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print <=-<=1.
[ "6\n2 3 5 7 11 13\n5\n3 4 5 5 6\n", "6\n2 3 5 7 11 13\n9\n1 2 2 3 3 4 5 5 6\n", "3\n10 200 300\n4\n1 2 2 3\n", "3\n1 2 3\n4\n1 2 2 3\n" ]
[ "10\n", "16\n", "-1\n", "3\n" ]
The first test from the statement demonstrates the first example shown in the statement of the problem. The second test from the statement demonstrates the second example shown in the statement of the problem. In the third sample there are two possible paths that have distinct lengths, consequently, the sought length of the segment isn't defined uniquely. In the fourth sample, even though two distinct paths correspond to the query, they have the same lengths, so the sought length of the segment is defined uniquely.
[ { "input": "6\n2 3 5 7 11 13\n5\n3 4 5 5 6", "output": "10" }, { "input": "6\n2 3 5 7 11 13\n9\n1 2 2 3 3 4 5 5 6", "output": "16" }, { "input": "3\n10 200 300\n4\n1 2 2 3", "output": "-1" }, { "input": "3\n1 2 3\n4\n1 2 2 3", "output": "3" }, { "input": "2\n1 100...
31
0
0
42,043
954
Yet Another String Matching Problem
[ "fft", "math" ]
null
null
Suppose you have two strings *s* and *t*, and their length is equal. You may perform the following operation any number of times: choose two different characters *c*1 and *c*2, and replace every occurence of *c*1 in both strings with *c*2. Let's denote the distance between strings *s* and *t* as the minimum number of operations required to make these strings equal. For example, if *s* is abcd and *t* is ddcb, the distance between them is 2 — we may replace every occurence of a with b, so *s* becomes bbcd, and then we may replace every occurence of b with d, so both strings become ddcd. You are given two strings *S* and *T*. For every substring of *S* consisting of |*T*| characters you have to determine the distance between this substring and *T*.
The first line contains the string *S*, and the second — the string *T* (1<=≤<=|*T*|<=≤<=|*S*|<=≤<=125000). Both strings consist of lowercase Latin letters from a to f.
Print |*S*|<=-<=|*T*|<=+<=1 integers. The *i*-th of these integers must be equal to the distance between the substring of *S* beginning at *i*-th index with length |*T*| and the string *T*.
[ "abcdefa\nddcb\n" ]
[ "2 3 3 3 \n" ]
none
[ { "input": "abcdefa\nddcb", "output": "2 3 3 3 " } ]
30
0
0
42,190
0
none
[ "none" ]
null
null
Felix the Robot is preparing for a probability theory exam. Unfortunately, during the semester, he took a course of the belles-lettres instead of studying the subject, so now he does not know the answer to any of the upcoming exam's questions. One thing is for sure: Felix needs help! The exam for robots is an online event. It consists of *n*<==<=5000 questions each of which has only two possible answers: "yes" and "no". A robot can attempt to pass the exam at most *x*<==<=100 times. The questions, their order and right answers don't change from one attempt to another. Once the exam starts, Felix will get just a few seconds for all his attempts, and he can't learn the right answers so fast. The robot will try to pass the exam in the following way. First, Felix fixes the answers for all questions. The result is a string of *n* bits: answers for the first, second, ..., *n*-th questions. In this string, 0 means that the answer is "no", and 1 is for "yes". Then he answers the questions according to this string, spending one attempt. After that, Felix can fix another string of *n* bits and make another attempt, and so on until there are no more attempts. In the online system for exam, the following optimization is implemented: if at some moment of time, the examinee already got *k*<==<=2000 answers wrong, the attempt is immediately terminated with the corresponding message. For Felix, this means that the remaining bits in the string he fixed are ignored. If there were strictly less than *k* wrong answers for all *n* questions, the exam is considered passed. The result of an attempt is a number from *k* to *n* inclusive: the number of questions after which the attempt was terminated. If the exam is passed, this number is considered to be *n*<=+<=1. The exam result is the highest result among all attempts. If there were no attempts, the exam result is zero. Your task is to write a program which will determine the bit strings for all attempts Felix makes. After each attempt, your program will get its result immediately. Help Felix get the highest exam result you can! Interaction Protocol Your solution can make from 0 to *x* attempts inclusive. To make an attempt, print a string to the standard output. The string must consist of exactly *n* binary digits without spaces and end with a newline character. To prevent output buffering, after printing a string, insert a command to flush the buffer: for example, it can be fflush (stdout) in C or C++, System.out.flush () in Java, flush (output) in Pascal or sys.stdout.flush () in Python. After each attempt you make, you can immediately read its result from the standard input. The result is an integer from *k* to *n*<=+<=1 inclusive, followed by a newline character. Scoring System A test is defined by a string of *n* binary digits: the right answers to *n* questions. This string is kept secret from the solution. Each test is evaluated separately. If a solution followed the interaction protocol and terminated correctly on a test, it gets a score of *max* (0,<=*S*<=-<=4000) where *S* is the exam result. Otherwise, the solution gets zero score for the test. Testing Your solution will be checked on sets of tests generated in advance. Each test is created using a pseudo-random number generator. You can consider that the answers are uniformly distributed (the probabilities of digits 0 and 1 are the same) and mutually independent (the probabilities of all 2*n* possible strings are the same). A solution gets the score which is the sum of its score on all the tests. During the main phase of the contest, there are two ways to send a solution for checking. - The first one is to check on examples. There are 10 example tests which are also available for local testing. As soon as the solution is checked, you can see reports for all examples by clicking on the submission result.- The second way is to check on preliminary tests. There are 100 preliminary tests which are generated in advance but kept secret. The score for preliminary tests (but not for example tests) is used in the preliminary scoreboard. This score does not affect the final results, but nevertheless allows to roughly compare a solution with others. After the main phase ends, for each participant, the system chooses the final solution: - consider all solutions sent for preliminary testing; - choose the ones which got a total score strictly greater than zero; - define the final solution as the one of chosen solutions which has the latest submission time. Note that the solutions sent only to be checked on examples are not considered when choosing the final solution. During the final testing, all final solutions will be checked on the same large set of a large number (<=≈<=1000) of final tests. The score for final tests determines the final scoreboard. The winner is the contestant whose solution gets the highest total score. In case two or more participants have equal total score, the contestants with such score tie for the same place. A package for local development is available on GitHub at the following address: [https://github.com/GassaFM/online-exam](https://github.com/GassaFM/online-exam). You can download sources or the latest release: [https://github.com/GassaFM/online-exam/releases](https://github.com/GassaFM/online-exam/releases). Example To have an example which fits into the problem statement, let *n*<==<=10, *k*<==<=2, and *x*<==<=3 (recall that in the real problem, *n*<==<=5000, *k*<==<=2000, and *x*<==<=100, so this example is not a correct test for the problem). Let the right answers be defined by the string 1010001111. Before any attempts are made, the exam result is zero. Consider a solution making three attempts. Let the first attempt be defined by the string 0100100100. The result of this attempt is the number 2: the first wrong answer is the answer to the first question, and the second is to the second question. The exam result at this moment is 2. Let the second attempt be defined by the string 1010101010. The result of this attempt is the number 8: the first wrong answer is the answer to the fifth question, and the second is to the eighth question. The exam result at this moment is 8. Let the second attempt be defined by the string 1001011001. The result of this attempt is the number 4: the first wrong answer is the answer to the third question, and the second is to the fourth question. The exam result at this moment is still 8. As *x*<==<=3 in our example, further attempts are impossible, so if the solution terminates correctly, the exam result is 8. Now consider another solution making two attempts. Let the first attempt be defined by the string 1010001110. Its result is the number 11: the first and only wrong answer is the answer to the tenth question, *k*<==<=2, so the exam is considered passed. Let the first attempt be defined by the string 0000011111. Its result is the number 3: the first wrong answer is the answer to the first question, and the second one is to the third question. If the solution terminates correctly after the above two attempts, the exam result is 11.
none
none
[]
[]
none
[]
295
5,836,800
-1
42,195
39
What Has Dirichlet Got to Do with That?
[ "dp", "games" ]
E. What Has Dirichlet Got to Do with That?
2
64
You all know the Dirichlet principle, the point of which is that if *n* boxes have no less than *n*<=+<=1 items, that leads to the existence of a box in which there are at least two items. Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. There are *a* different boxes and *b* different items, and each turn a player can either add a new box or a new item. The player, after whose turn the number of ways of putting *b* items into *a* boxes becomes no less then a certain given number *n*, loses. All the boxes and items are considered to be different. Boxes may remain empty. Who loses if both players play optimally and Stas's turn is first?
The only input line has three integers *a*,<=*b*,<=*n* (1<=≤<=*a*<=≤<=10000, 1<=≤<=*b*<=≤<=30, 2<=≤<=*n*<=≤<=109) — the initial number of the boxes, the number of the items and the number which constrains the number of ways, respectively. Guaranteed that the initial number of ways is strictly less than *n*.
Output "Stas" if Masha wins. Output "Masha" if Stas wins. In case of a draw, output "Missing".
[ "2 2 10\n", "5 5 16808\n", "3 1 4\n", "1 4 10\n" ]
[ "Masha\n", "Masha\n", "Stas\n", "Missing\n" ]
In the second example the initial number of ways is equal to 3125. - If Stas increases the number of boxes, he will lose, as Masha may increase the number of boxes once more during her turn. After that any Stas's move will lead to defeat. - But if Stas increases the number of items, then any Masha's move will be losing.
[ { "input": "2 2 10", "output": "Masha" }, { "input": "5 5 16808", "output": "Masha" }, { "input": "3 1 4", "output": "Stas" }, { "input": "1 4 10", "output": "Missing" }, { "input": "1 1 2", "output": "Missing" }, { "input": "1 1 3", "output": "Mas...
92
0
0
42,270
0
none
[ "none" ]
null
null
In some country there are exactly *n* cities and *m* bidirectional roads connecting the cities. Cities are numbered with integers from 1 to *n*. If cities *a* and *b* are connected by a road, then in an hour you can go along this road either from city *a* to city *b*, or from city *b* to city *a*. The road network is such that from any city you can get to any other one by moving along the roads. You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city *s*1 to city *t*1 in at most *l*1 hours and get from city *s*2 to city *t*2 in at most *l*2 hours. Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.
The first line contains two integers *n*, *m* (1<=≤<=*n*<=≤<=3000, ) — the number of cities and roads in the country, respectively. Next *m* lines contain the descriptions of the roads as pairs of integers *a**i*, *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, *s*1, *t*1, *l*1 and *s*2, *t*2, *l*2, respectively (1<=≤<=*s**i*,<=*t**i*<=≤<=*n*, 0<=≤<=*l**i*<=≤<=*n*).
Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.
[ "5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n3 5 2\n", "5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n2 4 2\n", "5 4\n1 2\n2 3\n3 4\n4 5\n1 3 2\n3 5 1\n" ]
[ "0\n", "1\n", "-1\n" ]
none
[]
46
0
0
42,312
733
Epidemic in Monstropolis
[ "constructive algorithms", "dp", "greedy", "two pointers" ]
null
null
There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city. Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster *A* eats the monster *B*, the weight of the monster *A* increases by the weight of the eaten monster *B*. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were *n* monsters in the queue, the *i*-th of which had weight *a**i*. For example, if weights are [1,<=2,<=2,<=2,<=1,<=2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are: 1. the first monster can't eat the second monster because *a*1<==<=1 is not greater than *a*2<==<=2; 1. the second monster can't eat the third monster because *a*2<==<=2 is not greater than *a*3<==<=2; 1. the second monster can't eat the fifth monster because they are not neighbors; 1. the second monster can eat the first monster, the queue will be transformed to [3,<=2,<=2,<=1,<=2]. After some time, someone said a good joke and all monsters recovered. At that moment there were *k* (*k*<=≤<=*n*) monsters in the queue, the *j*-th of which had weight *b**j*. Both sequences (*a* and *b*) contain the weights of the monsters in the order from the first to the last. You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.
The first line contains single integer *n* (1<=≤<=*n*<=≤<=500) — the number of monsters in the initial queue. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the initial weights of the monsters. The third line contains single integer *k* (1<=≤<=*k*<=≤<=*n*) — the number of monsters in the queue after the joke. The fourth line contains *k* integers *b*1,<=*b*2,<=...,<=*b**k* (1<=≤<=*b**j*<=≤<=5·108) — the weights of the monsters after the joke. Monsters are listed in the order from the beginning of the queue to the end.
In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line. Otherwise print "YES" (without quotes) in the first line. In the next *n*<=-<=*k* lines print actions in the chronological order. In each line print *x* — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the *x*-th in the queue eats the monster in front of him, or 'R' if the monster which stays the *x*-th in the queue eats the monster behind him. After each eating the queue is enumerated again. When one monster eats another the queue decreases. If there are several answers, print any of them.
[ "6\n1 2 2 2 1 2\n2\n5 5\n", "5\n1 2 3 4 5\n1\n15\n", "5\n1 1 1 3 3\n3\n2 1 6\n" ]
[ "YES\n2 L\n1 R\n4 L\n3 L\n", "YES\n5 L\n4 L\n3 L\n2 L\n", "NO" ]
In the first example, initially there were *n* = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue: - the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2]; - the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2]; - the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3]; - the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue.
[ { "input": "6\n1 2 2 2 1 2\n2\n5 5", "output": "YES\n2 L\n1 R\n4 L\n3 L" }, { "input": "5\n1 2 3 4 5\n1\n15", "output": "YES\n5 L\n4 L\n3 L\n2 L" }, { "input": "5\n1 1 1 3 3\n3\n2 1 6", "output": "NO" }, { "input": "5\n1 1 1 1 2\n3\n1 1 4", "output": "YES\n5 L\n4 L" }, ...
46
0
3
42,445
317
Game with Powers
[ "dp", "games" ]
null
null
Vasya and Petya wrote down all integers from 1 to *n* to play the "powers" game (*n* can be quite large; however, Vasya and Petya are not confused by this fact). Players choose numbers in turn (Vasya chooses first). If some number *x* is chosen at the current turn, it is forbidden to choose *x* or all of its other positive integer powers (that is, *x*2, *x*3, ...) at the next turns. For instance, if the number 9 is chosen at the first turn, one cannot choose 9 or 81 later, while it is still allowed to choose 3 or 27. The one who cannot make a move loses. Who wins if both Vasya and Petya play optimally?
Input contains single integer *n* (1<=≤<=*n*<=≤<=109).
Print the name of the winner — "Vasya" or "Petya" (without quotes).
[ "1\n", "2\n", "8\n" ]
[ "Vasya\n", "Petya\n", "Petya\n" ]
In the first sample Vasya will choose 1 and win immediately. In the second sample no matter which number Vasya chooses during his first turn, Petya can choose the remaining number and win.
[ { "input": "1", "output": "Vasya" }, { "input": "2", "output": "Petya" }, { "input": "8", "output": "Petya" }, { "input": "52", "output": "Petya" }, { "input": "53", "output": "Vasya" }, { "input": "3", "output": "Vasya" }, { "input": "4", ...
310
0
0
42,476
852
Digits
[ "brute force", "implementation", "math" ]
null
null
John gave Jack a very hard problem. He wrote a very big positive integer *A*0 on a piece of paper. The number is less than 10200000 . In each step, Jack is allowed to put '<=+<=' signs in between some of the digits (maybe none) of the current number and calculate the sum of the expression. He can perform the same procedure on that sum and so on. The resulting sums can be labeled respectively by *A*1, *A*2 etc. His task is to get to a single digit number. The problem is that there is not much blank space on the paper. There are only three lines of space, so he can't perform more than three steps. Since he wants to fill up the paper completely, he will perform exactly three steps. Jack must not add leading zeros to intermediate results, but he can put '<=+<=' signs in front of digit 0. For example, if the current number is 1000100, 10<=+<=001<=+<=00 is a valid step, resulting in number 11.
First line contains a positive integer *N* (1<=≤<=*N*<=≤<=200000), representing the number of digits of *A*0. Second line contains a string of length *N* representing positive integer number *A*0. Each character is digit. There will be no leading zeros.
Output exactly three lines, the steps Jack needs to perform to solve the problem. You can output any sequence of steps which results in a single digit number (and is logically consistent). Every step consists of digits and '<=+<=' signs. Steps should not contain several '<=+<=' signs in a row, whitespaces, or '<=+<=' signs as the first or last character. They also need to be arithmetically consistent. Solution might not be unique. Output any of them in that case.
[ "1\n1\n", "4\n5806\n" ]
[ "1\n1\n1\n", "5+8+0+6\n1+9\n1+0\n" ]
In the first sample, Jack can't put ' + ' signs anywhere, so he just writes 1 in each line and solves the problem. Here, solution is unique. In the second sample, Jack first puts ' + ' between every two consecutive digits, thus getting the result 5 + 8 + 0 + 6 = 19. He does the same on the second step, getting 1 + 9 = 10. Once more, he gets 1 + 0 = 1, so after three steps, the result is 1 and his solution is correct.
[]
1,000
1,843,200
0
42,494
0
none
[ "none" ]
null
null
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work. Ryouko's notebook consists of *n* pages, numbered from 1 to *n*. To make life (and this problem) easier, we consider that to turn from page *x* to page *y*, |*x*<=-<=*y*| pages should be turned. During analyzing, Ryouko needs *m* pieces of information, the *i*-th piece of information is on page *a**i*. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is . Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page *x* to page *y*, she would copy all the information on page *x* to *y* (1<=≤<=*x*,<=*y*<=≤<=*n*), and consequently, all elements in sequence *a* that was *x* would become *y*. Note that *x* can be equal to *y*, in which case no changes take place. Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.
The first line of input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105). The next line contains *m* integers separated by spaces: *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=*n*).
Print a single integer — the minimum number of pages Ryouko needs to turn.
[ "4 6\n1 2 3 4 3 2\n", "10 5\n9 4 3 8 8\n" ]
[ "3\n", "6\n" ]
In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence *a* becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3. In the second sample, optimal solution is achieved by merging page 9 to 4.
[ { "input": "4 6\n1 2 3 4 3 2", "output": "3" }, { "input": "10 5\n9 4 3 8 8", "output": "6" }, { "input": "5 10\n2 5 2 2 3 5 3 2 1 3", "output": "7" }, { "input": "10 20\n6 3 9 6 1 9 1 9 8 2 7 6 9 8 4 7 1 2 4 2", "output": "52" }, { "input": "100 100\n28 28 28 28 ...
62
0
0
42,792
375
Red and Black Tree
[ "dp", "implementation", "math" ]
null
null
You have a weighted tree, consisting of *n* vertices. Each vertex is either painted black or is painted red. A red and black tree is called beautiful, if for any its vertex we can find a black vertex at distance at most *x*. The distance between two nodes is the shortest path between them. You have a red and black tree. Your task is to make it beautiful in the minimum number of color swap operations. In one color swap operation, you can choose two vertices of different colors and paint each of them the other color. In other words, if you choose a red vertex *p* and a black vertex *q*, then in one operation you are allowed to paint *p* black and paint *q* red. Print the minimum number of required actions.
The first line contains two integers *n* and *x* (2<=≤<=*n*<=≤<=500; 1<=≤<=*x*<=≤<=109). The next line contains *n* integers, each of them is either a zero or one. If the *i*-th number equals 1, then vertex *i* of the tree is black, otherwise vertex *i* is red. Next *n*<=-<=1 lines contain the tree edges. The *j*-th line contains integers *u**j* *v**j* *w**j* (1<=≤<=*u**j*,<=*v**j*<=≤<=*n*; *u**j*<=≠<=*v**j*; 1<=≤<=*w**j*<=≤<=109) which means that the tree has an edge of weight *w**j* between vertices *v**j* and *u**j*. Assume that the tree vertices are numbered from 1 to *n*.
Print a single integer — the minimum number of required swap operations. If it is impossible to get a beautiful tree at any number of operations, print -1.
[ "3 2\n1 0 0\n1 2 2\n2 3 2\n", "4 2\n0 1 0 0\n1 2 2\n2 3 2\n3 4 2\n" ]
[ "1\n", "-1\n" ]
none
[]
46
0
0
42,820
0
none
[ "none" ]
null
null
Mr. Kitayuta's garden is planted with *n* bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the *i*-th bamboo is *h**i* meters, and it grows *a**i* meters at the end of each day. Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed because their stems are too hard. Mr. Kitayuta have not given up, however. He has crafted Magical Hammer with his intelligence to drive them into the ground. He can use Magical Hammer at most *k* times during each day, due to his limited Magic Power. Each time he beat a bamboo with Magical Hammer, its height decreases by *p* meters. If the height would become negative by this change, it will become 0 meters instead (it does not disappear). In other words, if a bamboo whose height is *h* meters is beaten with Magical Hammer, its new height will be *max*(0,<=*h*<=-<=*p*) meters. It is possible to beat the same bamboo more than once in a day. Mr. Kitayuta will fight the bamboos for *m* days, starting today. His purpose is to minimize the height of the tallest bamboo after *m* days (that is, *m* iterations of "Mr. Kitayuta beats the bamboos and then they grow"). Find the lowest possible height of the tallest bamboo after *m* days.
The first line of the input contains four space-separated integers *n*, *m*, *k* and *p* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*m*<=≤<=5000,<=1<=≤<=*k*<=≤<=10,<=1<=≤<=*p*<=≤<=109). They represent the number of the bamboos in Mr. Kitayuta's garden, the duration of Mr. Kitayuta's fight in days, the maximum number of times that Mr. Kitayuta beat the bamboos during each day, and the power of Magic Hammer, respectively. The following *n* lines describe the properties of the bamboos. The *i*-th of them (1<=≤<=*i*<=≤<=*n*) contains two space-separated integers *h**i* and *a**i* (0<=≤<=*h**i*<=≤<=109,<=1<=≤<=*a**i*<=≤<=109), denoting the initial height and the growth rate of the *i*-th bamboo, respectively.
Print the lowest possible height of the tallest bamboo after *m* days.
[ "3 1 2 5\n10 10\n10 10\n15 2\n", "2 10 10 1000000000\n0 10\n0 10\n", "5 3 3 10\n9 5\n9 2\n4 7\n9 10\n3 8\n" ]
[ "17\n", "10\n", "14\n" ]
none
[]
46
0
0
42,914
804
Ice cream coloring
[ "constructive algorithms", "dfs and similar", "greedy" ]
null
null
Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?" We have a tree *T* with *n* vertices and *m* types of ice cream numerated from 1 to *m*. Each vertex *i* has a set of *s**i* types of ice cream. Vertices which have the *i*-th (1<=≤<=*i*<=≤<=*m*) type of ice cream form a connected subgraph. We build a new graph *G* with *m* vertices. We put an edge between the *v*-th and the *u*-th (1<=≤<=*u*,<=*v*<=≤<=*m*, *u*<=≠<=*v*) vertices in *G* if and only if there exists a vertex in *T* that has both the *v*-th and the *u*-th types of ice cream in its set. The problem is to paint the vertices of *G* with minimum possible number of colors in a way that no adjacent vertices have the same color. Please note that we consider that empty set of vertices form a connected subgraph in this problem. As usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.
The first line contains two integer *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=3·105) — the number of vertices in *T* and the number of ice cream types. *n* lines follow, the *i*-th of these lines contain single integer *s**i* (0<=≤<=*s**i*<=≤<=3·105) and then *s**i* distinct integers, each between 1 and *m* — the types of ice cream in the *i*-th vertex. The sum of *s**i* doesn't exceed 5·105. *n*<=-<=1 lines follow. Each of these lines describes an edge of the tree with two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*) — the indexes of connected by this edge vertices.
Print single integer *c* in the first line — the minimum number of colors to paint the vertices in graph *G*. In the second line print *m* integers, the *i*-th of which should be the color of the *i*-th vertex. The colors should be between 1 and *c*. If there are some answers, print any of them.
[ "3 3\n1 1\n2 2 3\n1 2\n1 2\n2 3\n", "4 5\n0\n1 1\n1 3\n3 2 4 5\n2 1\n3 2\n4 3\n" ]
[ "2\n1 1 2 ", "3\n1 1 1 2 3 " ]
In the first example the first type of ice cream is present in the first vertex only, so we can color it in any color. The second and the third ice cream are both presented in the second vertex, so we should paint them in different colors. In the second example the colors of the second, the fourth and the fifth ice cream should obviously be distinct.
[ { "input": "3 3\n1 1\n2 2 3\n1 2\n1 2\n2 3", "output": "2\n1 1 2 " }, { "input": "4 5\n0\n1 1\n1 3\n3 2 4 5\n2 1\n3 2\n4 3", "output": "3\n1 1 1 2 3 " }, { "input": "7 35\n3 17 20 32\n4 3 14 24 25\n4 4 10 17 26\n7 2 9 13 17 23 28 30\n9 1 2 7 8 13 16 18 33 35\n8 5 6 11 15 17 22 29 34\n5 1...
2,000
52,838,400
0
43,060
988
Rain and Umbrellas
[ "dp" ]
null
null
Polycarp lives on a coordinate line at the point $x = 0$. He goes to his friend that lives at the point $x = a$. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $n$ non-intersecting segments, the $i$-th segment which is in the rain is represented as $[l_i, r_i]$ ($0 \le l_i &lt; r_i \le a$). There are $m$ umbrellas lying on the line, the $i$-th umbrella is located at point $x_i$ ($0 \le x_i \le a$) and has weight $p_i$. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from $x = 0$ to $x = a$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $x$ to $x + 1$ if a segment $[x, x + 1]$ is in the rain (i.e. if there exists some $i$ such that $l_i \le x$ and $x + 1 \le r_i$). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point $x = 0$ to point $x = a$? If yes, find the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.
The first line contains three integers $a$, $n$ and $m$ ($1 \le a, m \le 2000, 1 \le n \le \lceil\frac{a}{2}\rceil$) — the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next $n$ lines contains two integers $l_i$ and $r_i$ ($0 \le l_i &lt; r_i \le a$) — the borders of the $i$-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments $i$ and $j$ either $r_i &lt; l_j$ or $r_j &lt; l_i$. Each of the next $m$ lines contains two integers $x_i$ and $p_i$ ($0 \le x_i \le a$, $1 \le p_i \le 10^5$) — the location and the weight of the $i$-th umbrella.
Print "-1" (without quotes) if Polycarp can't make his way from point $x = 0$ to point $x = a$. Otherwise print one integer — the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.
[ "10 2 4\n3 7\n8 10\n0 10\n3 4\n8 1\n1 2\n", "10 1 1\n0 9\n0 5\n", "10 1 1\n0 9\n1 5\n" ]
[ "14\n", "45\n", "-1\n" ]
In the first example the only possible strategy is to take the fourth umbrella at the point $x = 1$, keep it till the point $x = 7$ (the total fatigue at $x = 7$ will be equal to $12$), throw it away, move on from $x = 7$ to $x = 8$ without an umbrella, take the third umbrella at $x = 8$ and keep it till the end (the total fatigue at $x = 10$ will be equal to $14$). In the second example the only possible strategy is to take the first umbrella, move with it till the point $x = 9$, throw it away and proceed without an umbrella till the end.
[ { "input": "10 2 4\n3 7\n8 10\n0 10\n3 4\n8 1\n1 2", "output": "14" }, { "input": "10 1 1\n0 9\n0 5", "output": "45" }, { "input": "10 1 1\n0 9\n1 5", "output": "-1" }, { "input": "1 1 1\n0 1\n1 100000", "output": "-1" }, { "input": "1 1 1\n0 1\n0 100000", "ou...
217
9,420,800
3
43,155
788
Finding lines
[ "constructive algorithms", "divide and conquer", "interactive" ]
null
null
After some programming contest Roma decided to try himself in tourism. His home country Uzhlyandia is a Cartesian plane. He wants to walk along each of the Main Straight Lines in Uzhlyandia. It is known that each of these lines is a straight line parallel to one of the axes (i.e. it is described with the equation *x*<==<=*a* or *y*<==<=*a*, where *a* is integer called the coordinate of this line). Roma lost his own map, so he should find out the coordinates of all lines at first. Uncle Anton agreed to help him, using the following rules: - Initially Roma doesn't know the number of vertical and horizontal lines and their coordinates; - Roma can announce integer coordinates of some point in Uzhlandia, and Anton then will tell him the minimum among the distances from the chosen point to each of the lines. However, since the coordinates of the lines don't exceed 108 by absolute value, Roma can't choose a point with coordinates exceeding 108 by absolute value. Uncle Anton is in a hurry to the UOI (Uzhlandian Olympiad in Informatics), so he can only answer no more than 3·105 questions. The problem is that Roma doesn't know how to find out the coordinates of the lines. Write a program that plays Roma's role and finds the coordinates.
There is no input initially. Your program should make queries to get information. It is guaranteed that the number of horizontal and vertical lines is at least 1 and less than or equal to 104 for each type.
none
[ "1\n1\n3\n2\n" ]
[ "0 1 2\n0 -2 -2\n0 5 6\n0 -2 2\n1 1 2\n2\n0 -3\n" ]
The example test is The minimum distances are: - from (1, 2) to *x* = 2; - from ( - 2,  - 2) to *y* =  - 3; - from (5, 6) to *x* = 2; - from ( - 2, 2) to *y* = 0.
[]
46
0
0
43,265
392
Tower of Hanoi
[ "dp" ]
null
null
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1. Only one disk can be moved at a time. 1. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 1. No disk may be placed on top of a smaller disk. With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2*n*<=-<=1, where *n* is the number of disks. (c) Wikipedia. SmallY's puzzle is very similar to the famous Tower of Hanoi. In the Tower of Hanoi puzzle you need to solve a puzzle in minimum number of moves, in SmallY's puzzle each move costs some money and you need to solve the same puzzle but for minimal cost. At the beginning of SmallY's puzzle all *n* disks are on the first rod. Moving a disk from rod *i* to rod *j* (1<=≤<=*i*,<=*j*<=≤<=3) costs *t**ij* units of money. The goal of the puzzle is to move all the disks to the third rod. In the problem you are given matrix *t* and an integer *n*. You need to count the minimal cost of solving SmallY's puzzle, consisting of *n* disks.
Each of the first three lines contains three integers — matrix *t*. The *j*-th integer in the *i*-th line is *t**ij* (1<=≤<=*t**ij*<=≤<=10000; *i*<=≠<=*j*). The following line contains a single integer *n* (1<=≤<=*n*<=≤<=40) — the number of disks. It is guaranteed that for all *i* (1<=≤<=*i*<=≤<=3), *t**ii*<==<=0.
Print a single integer — the minimum cost of solving SmallY's puzzle.
[ "0 1 1\n1 0 1\n1 1 0\n3\n", "0 2 2\n1 0 100\n1 2 0\n3\n", "0 2 1\n1 0 100\n1 2 0\n5\n" ]
[ "7\n", "19\n", "87\n" ]
none
[ { "input": "0 1 1\n1 0 1\n1 1 0\n3", "output": "7" }, { "input": "0 2 2\n1 0 100\n1 2 0\n3", "output": "19" }, { "input": "0 2 1\n1 0 100\n1 2 0\n5", "output": "87" }, { "input": "0 5835 1487\n6637 0 9543\n6961 6820 0\n7", "output": "723638" }, { "input": "0 3287 ...
0
0
-1
43,396
702
Analysis of Pathes in Functional Graph
[ "data structures", "graphs" ]
null
null
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to *n*<=-<=1. Graph is given as the array *f*0,<=*f*1,<=...,<=*f**n*<=-<=1, where *f**i* — the number of vertex to which goes the only arc from the vertex *i*. Besides you are given array with weights of the arcs *w*0,<=*w*1,<=...,<=*w**n*<=-<=1, where *w**i* — the arc weight from *i* to *f**i*. Also you are given the integer *k* (the length of the path) and you need to find for each vertex two numbers *s**i* and *m**i*, where: - *s**i* — the sum of the weights of all arcs of the path with length equals to *k* which starts from the vertex *i*; - *m**i* — the minimal weight from all arcs on the path with length *k* which starts from the vertex *i*. The length of the path is the number of arcs on this path.
The first line contains two integers *n*,<=*k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=1010). The second line contains the sequence *f*0,<=*f*1,<=...,<=*f**n*<=-<=1 (0<=≤<=*f**i*<=&lt;<=*n*) and the third — the sequence *w*0,<=*w*1,<=...,<=*w**n*<=-<=1 (0<=≤<=*w**i*<=≤<=108).
Print *n* lines, the pair of integers *s**i*, *m**i* in each line.
[ "7 3\n1 2 3 4 3 2 6\n6 3 1 4 2 2 3\n", "4 4\n0 1 2 3\n0 1 2 3\n", "5 3\n1 2 3 4 0\n4 1 2 14 3\n" ]
[ "10 1\n8 1\n7 1\n10 2\n8 2\n7 1\n9 3\n", "0 0\n4 1\n8 2\n12 3\n", "7 1\n17 1\n19 2\n21 3\n8 1\n" ]
none
[ { "input": "7 3\n1 2 3 4 3 2 6\n6 3 1 4 2 2 3", "output": "10 1\n8 1\n7 1\n10 2\n8 2\n7 1\n9 3" }, { "input": "4 4\n0 1 2 3\n0 1 2 3", "output": "0 0\n4 1\n8 2\n12 3" }, { "input": "5 3\n1 2 3 4 0\n4 1 2 14 3", "output": "7 1\n17 1\n19 2\n21 3\n8 1" }, { "input": "1 1\n0\n100...
46
0
0
43,464
878
Numbers on the blackboard
[ "combinatorics", "dp" ]
null
null
A sequence of *n* integers is written on a blackboard. Soon Sasha will come to the blackboard and start the following actions: let *x* and *y* be two adjacent numbers (*x* before *y*), then he can remove them and write *x*<=+<=2*y* instead of them. He will perform these operations until one number is left. Sasha likes big numbers and will get the biggest possible number. Nikita wants to get to the blackboard before Sasha and erase some of the numbers. He has *q* options, in the option *i* he erases all numbers to the left of the *l**i*-th number and all numbers to the right of *r**i*-th number, i. e. all numbers between the *l**i*-th and the *r**i*-th, inclusive, remain on the blackboard. For each of the options he wants to know how big Sasha's final number is going to be. This number can be very big, so output it modulo 109<=+<=7.
The first line contains two integers *n* and *q* (1<=≤<=*n*,<=*q*<=≤<=105) — the number of integers on the blackboard and the number of Nikita's options. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109) — the sequence on the blackboard. Each of the next *q* lines contains two integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*), describing Nikita's options.
For each option output Sasha's result modulo 109<=+<=7.
[ "3 3\n1 2 3\n1 3\n1 2\n2 3\n", "3 1\n1 2 -3\n1 3\n", "4 2\n1 1 1 -1\n1 4\n3 4\n" ]
[ "17\n5\n8\n", "1000000006\n", "5\n1000000006\n" ]
In the second sample Nikita doesn't erase anything. Sasha first erases the numbers 1 and 2 and writes 5. Then he erases 5 and -3 and gets -1. -1 modulo 10<sup class="upper-index">9</sup> + 7 is 10<sup class="upper-index">9</sup> + 6.
[]
46
0
0
43,470
52
Right Triangles
[ "combinatorics" ]
B. Right Triangles
2
256
You are given a *n*<=×<=*m* field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle).
The first line contains two positive integer numbers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000). The following *n* lines consist of *m* characters each, describing the field. Only '.' and '*' are allowed.
Output a single number — total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
[ "2 2\n**\n*.\n", "3 4\n*..*\n.**.\n*.**\n" ]
[ "1\n", "9\n" ]
none
[ { "input": "2 2\n**\n*.", "output": "1" }, { "input": "3 4\n*..*\n.**.\n*.**", "output": "9" }, { "input": "3 2\n..\n..\n*.", "output": "0" }, { "input": "1 2\n**", "output": "0" }, { "input": "1 3\n*.*", "output": "0" }, { "input": "5 2\n*.\n**\n.*\n....
530
26,112,000
3.818863
43,503
932
Tree
[ "binary search", "dp", "trees" ]
null
null
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.
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 the answer to each query of second type in separate line.
[ "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" ]
[ "0\n1\n1\n2\n", "2\n2\n3\n2\n", "1\n1\n2\n", "1\n2\n3\n" ]
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
[ { "input": "6\n1 1 1\n2 2 0\n2 2 1\n1 3 0\n2 2 0\n2 2 2", "output": "0\n1\n1\n2" }, { "input": "6\n1 1 0\n2 2 0\n2 0 3\n1 0 2\n2 1 3\n2 1 6", "output": "2\n2\n3\n2" }, { "input": "7\n1 1 2\n1 2 3\n2 3 3\n1 0 0\n1 5 1\n2 5 0\n2 4 0", "output": "1\n1\n2" }, { "input": "7\n1 1 3...
46
0
0
43,535
71
Nuclear Fusion
[ "bitmasks", "dp" ]
E. Nuclear Fusion
1
256
There is the following puzzle popular among nuclear physicists. A reactor contains a set of *n* atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of *k* atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle.
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=17). The second line contains space-separated symbols of elements of *n* atoms, which are available from the start. The third line contains space-separated symbols of elements of *k* atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized.
If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line «YES», and on the next *k* lines print the way of synthesizing each of *k* atoms as equations. Each equation has the following form: "*x*1+*x*2+...+*x**t*-&gt;*y**i*", where *x**j* is the symbol of the element of some atom from the original set, and *y**i* is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples.
[ "10 3\nMn Co Li Mg C P F Zn Sc K\nSn Pt Y\n", "2 1\nH H\nHe\n", "2 2\nBk Fm\nCf Es\n" ]
[ "YES\nMn+C+K-&gt;Sn\nCo+Zn+Sc-&gt;Pt\nLi+Mg+P+F-&gt;Y\n", "YES\nH+H-&gt;He\n", "NO\n" ]
The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6f2ce1bed492cbe40ff1bb4600fe53aebc680ace.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/edbd66c81b30040884ff79761e8a0ff37dc1fa9d.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9f68585680e3f916d2ec79a9aac68b2ee880cba7.png" style="max-width: 100.0%;max-height: 100.0%;"/> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints.
[ { "input": "10 3\nMn Co Li Mg C P F Zn Sc K\nSn Pt Y", "output": "YES\nCo+Mg->Y\nLi+P+F+Zn+Sc->Pt\nMn+C+K->Sn" }, { "input": "2 1\nH H\nHe", "output": "YES\nH+H->He" }, { "input": "2 2\nBk Fm\nCf Es", "output": "NO" }, { "input": "8 8\nTl Pb Bi Po Np Pu Am Cm\nAt Rn Fr Ra Ac ...
93
3,584,000
0
43,668
0
none
[ "none" ]
null
null
Вам задано прямоугольное клетчатое поле, состоящее из *n* строк и *m* столбцов. Поле содержит цикл из символов «*», такой что: - цикл можно обойти, посетив каждую его клетку ровно один раз, перемещаясь каждый раз вверх/вниз/вправо/влево на одну клетку; - цикл не содержит самопересечений и самокасаний, то есть две клетки цикла соседствуют по стороне тогда и только тогда, когда они соседние при перемещении вдоль цикла (самокасание по углу тоже запрещено). Ниже изображены несколько примеров допустимых циклов: Все клетки поля, отличные от цикла, содержат символ «.». Цикл на поле ровно один. Посещать клетки, отличные от цикла, Роботу нельзя. В одной из клеток цикла находится Робот. Эта клетка помечена символом «S». Найдите последовательность команд для Робота, чтобы обойти цикл. Каждая из четырёх возможных команд кодируется буквой и обозначает перемещение Робота на одну клетку: - «U» — сдвинуться на клетку вверх, - «R» — сдвинуться на клетку вправо, - «D» — сдвинуться на клетку вниз, - «L» — сдвинуться на клетку влево. Робот должен обойти цикл, побывав в каждой его клетке ровно один раз (кроме стартовой точки — в ней он начинает и заканчивает свой путь). Найдите искомую последовательность команд, допускается любое направление обхода цикла.
В первой строке входных данных записаны два целых числа *n* и *m* (3<=≤<=*n*,<=*m*<=≤<=100) — количество строк и столбцов прямоугольного клетчатого поля соответственно. В следующих *n* строках записаны по *m* символов, каждый из которых — «.», «*» или «S». Гарантируется, что отличные от «.» символы образуют цикл без самопересечений и самокасаний. Также гарантируется, что на поле ровно одна клетка содержит «S» и что она принадлежит циклу. Робот не может посещать клетки, помеченные символом «.».
В первую строку выходных данных выведите искомую последовательность команд для Робота. Направление обхода цикла Роботом может быть любым.
[ "3 3\n***\n*.*\n*S*\n", "6 7\n.***...\n.*.*...\n.*.S**.\n.*...**\n.*....*\n.******\n" ]
[ "LUURRDDL\n", "UULLDDDDDRRRRRUULULL\n" ]
В первом тестовом примере для обхода по часовой стрелке последовательность посещенных роботом клеток выглядит следующим образом: 1. клетка (3, 2); 1. клетка (3, 1); 1. клетка (2, 1); 1. клетка (1, 1); 1. клетка (1, 2); 1. клетка (1, 3); 1. клетка (2, 3); 1. клетка (3, 3); 1. клетка (3, 2).
[ { "input": "3 3\n***\n*.*\n*S*", "output": "LUURRDDL" }, { "input": "6 7\n.***...\n.*.*...\n.*.S**.\n.*...**\n.*....*\n.******", "output": "UULLDDDDDRRRRRUULULL" }, { "input": "100 3\n***\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\n*.*\...
31
4,812,800
0
43,806
383
Volcanoes
[ "binary search", "implementation", "sortings", "two pointers" ]
null
null
Iahub got lost in a very big desert. The desert can be represented as a *n*<=×<=*n* square matrix, where each cell is a zone of the desert. The cell (*i*,<=*j*) represents the cell at row *i* and column *j* (1<=≤<=*i*,<=*j*<=≤<=*n*). Iahub can go from one cell (*i*,<=*j*) only down or right, that is to cells (*i*<=+<=1,<=*j*) or (*i*,<=*j*<=+<=1). Also, there are *m* cells that are occupied by volcanoes, which Iahub cannot enter. Iahub is initially at cell (1,<=1) and he needs to travel to cell (*n*,<=*n*). Knowing that Iahub needs 1 second to travel from one cell to another, find the minimum time in which he can arrive in cell (*n*,<=*n*).
The first line contains two integers *n* (1<=≤<=*n*<=≤<=109) and *m* (1<=≤<=*m*<=≤<=105). Each of the next *m* lines contains a pair of integers, *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*), representing the coordinates of the volcanoes. Consider matrix rows are numbered from 1 to *n* from top to bottom, and matrix columns are numbered from 1 to *n* from left to right. There is no volcano in cell (1,<=1). No two volcanoes occupy the same location.
Print one integer, the minimum time in which Iahub can arrive at cell (*n*,<=*n*). If no solution exists (there is no path to the final cell), print -1.
[ "4 2\n1 3\n1 4\n", "7 8\n1 6\n2 6\n3 5\n3 6\n4 3\n5 1\n5 2\n5 3\n", "2 2\n1 2\n2 1\n" ]
[ "6\n", "12\n", "-1\n" ]
Consider the first sample. A possible road is: (1, 1)  →  (1, 2)  →  (2, 2)  →  (2, 3)  →  (3, 3)  →  (3, 4)  →  (4, 4).
[ { "input": "4 2\n1 3\n1 4", "output": "6" }, { "input": "7 8\n1 6\n2 6\n3 5\n3 6\n4 3\n5 1\n5 2\n5 3", "output": "12" }, { "input": "2 2\n1 2\n2 1", "output": "-1" }, { "input": "1000000000 9\n1 2\n3 1\n3 2\n999999998 999999999\n999999998 1000000000\n999999999 999999999\n9999...
46
0
0
43,885
255
Code Parsing
[ "implementation" ]
null
null
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string *s*, consisting of characters "x" and "y", and uses two following operations at runtime: 1. Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. 1. Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string *s*, and the algorithm works as follows: 1. If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. 1. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string *s*.
The first line contains a non-empty string *s*. It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.
In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string *s*.
[ "x\n", "yxyxy\n", "xxxxxy\n" ]
[ "x\n", "y\n", "xxxx\n" ]
In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change. In the second test the transformation will be like this: 1. string "yxyxy" transforms into string "xyyxy"; 1. string "xyyxy" transforms into string "xyxyy"; 1. string "xyxyy" transforms into string "xxyyy"; 1. string "xxyyy" transforms into string "xyy"; 1. string "xyy" transforms into string "y". As a result, we've got string "y". In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".
[ { "input": "x", "output": "x" }, { "input": "yxyxy", "output": "y" }, { "input": "xxxxxy", "output": "xxxx" }, { "input": "yxyyxyyx", "output": "yy" }, { "input": "yxxyxyx", "output": "x" }, { "input": "xxx", "output": "xxx" }, { "input": "...
436
2,048,000
-1
44,012
0
none
[ "none" ]
null
null
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string *s*, consisting of small English letters, and uniformly at random chooses an integer *k* from a segment [0,<=*len*(*s*)<=-<=1]. He tells Vasya this string *s*, and then shifts it *k* letters to the left, i. e. creates a new string *t*<==<=*s**k*<=+<=1*s**k*<=+<=2... *s**n**s*1*s*2... *s**k*. Vasya does not know the integer *k* nor the string *t*, but he wants to guess the integer *k*. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose. Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of *k* uniquely, it means, that if there are at least two cyclic shifts of *s* that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
The only string contains the string *s* of length *l* (3<=≤<=*l*<=≤<=5000), consisting of small English letters only.
Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10<=-<=6. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct if
[ "technocup\n", "tictictactac\n", "bbaabaabbb\n" ]
[ "1.000000000000000\n", "0.333333333333333\n", "0.100000000000000\n" ]
In the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely. In the second example if the first opened letter of *t* is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
[ { "input": "technocup", "output": "1.000000000000000" }, { "input": "tictictactac", "output": "0.333333333333333" }, { "input": "bbaabaabbb", "output": "0.100000000000000" }, { "input": "cbbbbcaaca", "output": "0.800000000000000" }, { "input": "cadbcdddda", "o...
61
19,968,000
0
44,035
167
Wizards and Numbers
[ "games", "math" ]
null
null
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*<=&gt;<=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*<=&gt;<=*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.
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.
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.
[ "4\n10 21\n31 10\n0 1\n10 30\n" ]
[ "First\nSecond\nSecond\nFirst\n" ]
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.
[ { "input": "4\n10 21\n31 10\n0 1\n10 30", "output": "First\nSecond\nSecond\nFirst" }, { "input": "66\n7 0\n5 7\n1 3\n3 2\n3 5\n0 6\n1 2\n0 7\n4 5\n4 7\n5 1\n2 0\n4 0\n0 5\n3 6\n7 3\n6 0\n5 2\n6 6\n1 7\n5 6\n2 2\n3 4\n2 1\n5 3\n4 6\n6 2\n3 3\n100000000000 1000000000000000000\n0 1\n4 1\n2 6\n5 5\n4 3\...
62
0
0
44,036
189
Counting Rhombi
[ "brute force", "math" ]
null
null
You have two positive integers *w* and *h*. Your task is to count the number of rhombi which have the following properties: - Have positive area. - With vertices at integer points. - All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points (0,<=0), (*w*,<=0), (*w*,<=*h*), (0,<=*h*). In other words, for all vertices (*x**i*,<=*y**i*) of the rhombus the following conditions should fulfill: 0<=≤<=*x**i*<=≤<=*w* and 0<=≤<=*y**i*<=≤<=*h*. - Its diagonals are parallel to the axis. Count the number of such rhombi. Let us remind you that a rhombus is a quadrilateral whose four sides all have the same length.
The first line contains two integers *w* and *h* (1<=≤<=*w*,<=*h*<=≤<=4000) — the rectangle's sizes.
Print a single number — the number of sought rhombi. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
[ "2 2\n", "1 2\n" ]
[ "1\n", "0\n" ]
In the first example there exists only one such rhombus. Its vertices are located at points (1, 0), (2, 1), (1, 2), (0, 1).
[ { "input": "2 2", "output": "1" }, { "input": "1 2", "output": "0" }, { "input": "1 4000", "output": "0" }, { "input": "4000 1", "output": "0" }, { "input": "4000 4000", "output": "16000000000000" }, { "input": "15 10", "output": "1400" }, { ...
92
0
0
44,317
396
On Changing Tree
[ "data structures", "graphs", "trees" ]
null
null
You are given a rooted tree consisting of *n* vertices numbered from 1 to *n*. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come *q* queries, each query has one of the two types: - The format of the query: 1 *v* *x* *k*. In response to the query, you need to add to the number at vertex *v* number *x*; to the numbers at the descendants of vertex *v* at distance 1, add *x*<=-<=*k*; and so on, to the numbers written in the descendants of vertex *v* at distance *i*, you need to add *x*<=-<=(*i*·*k*). The distance between two vertices is the number of edges in the shortest path between these vertices. - The format of the query: 2 *v*. In reply to the query you should print the number written in vertex *v* modulo 1000000007 (109<=+<=7). Process the queries given in the input.
The first line contains integer *n* (1<=≤<=*n*<=≤<=3·105) — the number of vertices in the tree. The second line contains *n*<=-<=1 integers *p*2,<=*p*3,<=... *p**n* (1<=≤<=*p**i*<=&lt;<=*i*), where *p**i* is the number of the vertex that is the parent of vertex *i* in the tree. The third line contains integer *q* (1<=≤<=*q*<=≤<=3·105) — the number of queries. Next *q* lines contain the queries, one per line. The first number in the line is *type*. It represents the type of the query. If *type*<==<=1, then next follow space-separated integers *v*,<=*x*,<=*k* (1<=≤<=*v*<=≤<=*n*; 0<=≤<=*x*<=&lt;<=109<=+<=7; 0<=≤<=*k*<=&lt;<=109<=+<=7). If *type*<==<=2, then next follows integer *v* (1<=≤<=*v*<=≤<=*n*) — the vertex where you need to find the value of the number.
For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109<=+<=7).
[ "3\n1 1\n3\n1 1 2 1\n2 1\n2 2\n" ]
[ "2\n1\n" ]
You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory).
[ { "input": "3\n1 1\n3\n1 1 2 1\n2 1\n2 2", "output": "2\n1" }, { "input": "10\n1 2 3 4 4 3 3 6 7\n10\n1 6 13 98\n1 7 17 66\n1 5 32 39\n1 1 9 5\n1 7 27 11\n1 1 24 79\n1 5 87 86\n2 2\n1 5 9 38\n2 5", "output": "999999956\n999999832" }, { "input": "1\n\n1\n2 1", "output": "0" } ]
109
307,200
0
44,364
677
Vanya and Label
[ "bitmasks", "combinatorics", "implementation", "strings" ]
null
null
While walking down the street Vanya saw a label "Hide&amp;Seek". Because he is a programmer, he used &amp; as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string *s* and wants to know the number of pairs of words of length |*s*| (length of *s*), such that their bitwise AND is equal to *s*. As this number can be large, output it modulo 109<=+<=7. To represent the string as a number in numeral system with base 64 Vanya uses the following rules: - digits from '0' to '9' correspond to integers from 0 to 9; - letters from 'A' to 'Z' correspond to integers from 10 to 35; - letters from 'a' to 'z' correspond to integers from 36 to 61; - letter '-' correspond to integer 62; - letter '_' correspond to integer 63.
The only line of the input contains a single word *s* (1<=≤<=|*s*|<=≤<=100<=000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.
Print a single integer — the number of possible pairs of words, such that their bitwise AND is equal to string *s* modulo 109<=+<=7.
[ "z\n", "V_V\n", "Codeforces\n" ]
[ "3\n", "9\n", "130653412\n" ]
For a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia. In the first sample, there are 3 possible solutions: 1. *z*&amp;_ = 61&amp;63 = 61 = *z* 1. _&amp;*z* = 63&amp;61 = 61 = *z* 1. *z*&amp;*z* = 61&amp;61 = 61 = *z*
[ { "input": "z", "output": "3" }, { "input": "V_V", "output": "9" }, { "input": "Codeforces", "output": "130653412" }, { "input": "zHsIINYjVtU71kmM9E", "output": "130312847" }, { "input": "fRRNAdMvLFTX21T0FG5gyn7NG0SaIvzGG_g_SO", "output": "547121709" }, { ...
46
0
0
44,488
0
none
[ "none" ]
null
null
Imagine that you are in a building that has exactly *n* floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to *n*. Now you're on the floor number *a*. You are very bored, so you want to take the lift. Floor number *b* has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make *k* consecutive trips in the lift. Let us suppose that at the moment you are on the floor number *x* (initially, you were on floor *a*). For another trip between floors you choose some floor with number *y* (*y*<=≠<=*x*) and the lift travels to this floor. As you cannot visit floor *b* with the secret lab, you decided that the distance from the current floor *x* to the chosen *y* must be strictly less than the distance from the current floor *x* to floor *b* with the secret lab. Formally, it means that the following inequation must fulfill: |*x*<=-<=*y*|<=&lt;<=|*x*<=-<=*b*|. After the lift successfully transports you to floor *y*, you write down number *y* in your notepad. Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of *k* trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109<=+<=7).
The first line of the input contains four space-separated integers *n*, *a*, *b*, *k* (2<=≤<=*n*<=≤<=5000, 1<=≤<=*k*<=≤<=5000, 1<=≤<=*a*,<=*b*<=≤<=*n*, *a*<=≠<=*b*).
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109<=+<=7).
[ "5 2 4 1\n", "5 2 4 2\n", "5 3 4 1\n" ]
[ "2\n", "2\n", "0\n" ]
Two sequences *p*<sub class="lower-index">1</sub>, *p*<sub class="lower-index">2</sub>, ..., *p*<sub class="lower-index">*k*</sub> and *q*<sub class="lower-index">1</sub>, *q*<sub class="lower-index">2</sub>, ..., *q*<sub class="lower-index">*k*</sub> are distinct, if there is such integer *j* (1 ≤ *j* ≤ *k*), that *p*<sub class="lower-index">*j*</sub> ≠ *q*<sub class="lower-index">*j*</sub>. Notes to the samples: 1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| &lt; |2 - 4| and |3 - 2| &lt; |2 - 4|. 1. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip. 1. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
[ { "input": "5 2 4 1", "output": "2" }, { "input": "5 2 4 2", "output": "2" }, { "input": "5 3 4 1", "output": "0" }, { "input": "2 2 1 1", "output": "0" }, { "input": "10 1 10 2", "output": "44" }, { "input": "2222 1206 1425 2222", "output": "40257...
31
0
0
44,630
815
Karen and Test
[ "brute force", "combinatorics", "constructive algorithms", "math" ]
null
null
Karen has just arrived at school, and she has a math test today! The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. There are *n* integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition. Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa. The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test. Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row? Since this number can be quite large, output only the non-negative remainder after dividing it by 109<=+<=7.
The first line of input contains a single integer *n* (1<=≤<=*n*<=≤<=200000), the number of numbers written on the first row. The next line contains *n* integers. Specifically, the *i*-th one among these is *a**i* (1<=≤<=*a**i*<=≤<=109), the *i*-th number on the first row.
Output a single integer on a line by itself, the number on the final row after performing the process above. Since this number can be quite large, print only the non-negative remainder after dividing it by 109<=+<=7.
[ "5\n3 6 9 12 15\n", "4\n3 7 5 2\n" ]
[ "36\n", "1000000006\n" ]
In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15. Karen performs the operations as follows: The non-negative remainder after dividing the final number by 10<sup class="upper-index">9</sup> + 7 is still 36, so this is the correct output. In the second test case, the numbers written on the first row are 3, 7, 5 and 2. Karen performs the operations as follows: The non-negative remainder after dividing the final number by 10<sup class="upper-index">9</sup> + 7 is 10<sup class="upper-index">9</sup> + 6, so this is the correct output.
[ { "input": "5\n3 6 9 12 15", "output": "36" }, { "input": "4\n3 7 5 2", "output": "1000000006" }, { "input": "1\n1", "output": "1" }, { "input": "16\n985629174 189232688 48695377 692426437 952164554 243460498 173956955 210310239 237322183 96515847 678847559 682240199 49879255...
93
0
-1
44,707
939
Cutlet
[ "data structures", "dp" ]
null
null
Arkady wants to have a dinner. He has just returned from a shop where he has bought a semifinished cutlet. He only needs to fry it. The cutlet should be fried for 2*n* seconds, in particular, it should be fried for *n* seconds on one side and *n* seconds on the other side. Arkady has already got a frying pan and turn on fire, but understood that maybe he won't be able to flip the cutlet exactly after *n* seconds after the beginning of cooking. Arkady is too busy with sorting sticker packs in his favorite messenger and can flip the cutlet only in some periods of time. Namely, there are *k* periods of time in which he can do it, the *i*-th of them is an interval of time from *l**i* seconds after he starts cooking till *r**i* seconds, inclusive. Arkady decided that it's not required to flip the cutlet exactly in the middle of cooking, instead, he will flip it several times in such a way that the cutlet will be fried exactly *n* seconds on one side and *n* seconds on the other side in total. Help Arkady and find out if it's possible for him to cook the cutlet, if he is able to flip the cutlet only in given periods of time; and if yes, find the minimum number of flips he needs to cook the cutlet.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*k*<=≤<=100) — the number of seconds the cutlet should be cooked on each side and number of periods of time in which Arkady can flip it. The next *k* lines contain descriptions of these intervals. Each line contains two integers *l**i* and *r**i* (0<=≤<=*l**i*<=≤<=*r**i*<=≤<=2·*n*), meaning that Arkady can flip the cutlet in any moment starting from *l**i* seconds after the beginning of cooking and finishing at *r**i* seconds after beginning of cooking. In particular, if *l**i*<==<=*r**i* then Arkady can flip the cutlet only in the moment *l**i*<==<=*r**i*. It's guaranteed that *l**i*<=&gt;<=*r**i*<=-<=1 for all 2<=≤<=*i*<=≤<=*k*.
Output "Hungry" if Arkady won't be able to fry the cutlet for exactly *n* seconds on one side and exactly *n* seconds on the other side. Otherwise, output "Full" in the first line, and the minimum number of times he should flip the cutlet in the second line.
[ "10 2\n3 5\n11 13\n", "10 3\n3 5\n9 10\n11 13\n", "20 1\n3 19\n" ]
[ "Full\n2\n", "Full\n1\n", "Hungry\n" ]
In the first example Arkady should flip the cutlet in time moment 3 seconds after he starts cooking and in time moment 13 seconds after he starts cooking. In the second example, Arkady can flip the cutlet at 10 seconds after he starts cooking.
[ { "input": "10 2\n3 5\n11 13", "output": "Full\n2" }, { "input": "10 3\n3 5\n9 10\n11 13", "output": "Full\n1" }, { "input": "20 1\n3 19", "output": "Hungry" }, { "input": "10 1\n0 20", "output": "Full\n1" }, { "input": "10 1\n0 1", "output": "Hungry" }, {...
0
0
-1
44,712
394
Very Beautiful Number
[ "math" ]
null
null
Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office. The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactly *p* decimal digits, and if we move the last digit of the number to the beginning, it grows exactly *x* times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible. The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
The single line contains integers *p*, *x* (1<=≤<=*p*<=≤<=106,<=1<=≤<=*x*<=≤<=9).
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
[ "6 5\n", "1 2\n", "6 4\n" ]
[ "142857", "Impossible\n", "102564" ]
Sample 1: 142857·5 = 714285. Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
[ { "input": "6 5", "output": "142857" }, { "input": "1 2", "output": "Impossible" }, { "input": "6 4", "output": "102564" }, { "input": "11 1", "output": "11111111111" }, { "input": "42 5", "output": "102040816326530612244897959183673469387755" }, { "in...
1,000
9,420,800
0
44,761
0
none
[ "none" ]
null
null
You have an array of positive integers *a*[1],<=*a*[2],<=...,<=*a*[*n*] and a set of bad prime numbers *b*1,<=*b*2,<=...,<=*b**m*. The prime numbers that do not occur in the set *b* are considered good. The beauty of array *a* is the sum , where function *f*(*s*) is determined as follows: - *f*(1)<==<=0; - Let's assume that *p* is the minimum prime divisor of *s*. If *p* is a good prime, then , otherwise . You are allowed to perform an arbitrary (probably zero) number of operations to improve array *a*. The operation of improvement is the following sequence of actions: - Choose some number *r* (1<=≤<=*r*<=≤<=*n*) and calculate the value *g* = GCD(*a*[1],<=*a*[2],<=...,<=*a*[*r*]). - Apply the assignments: , , ..., . What is the maximum beauty of the array you can get?
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=5000) showing how many numbers are in the array and how many bad prime numbers there are. The second line contains *n* space-separated integers *a*[1],<=*a*[2],<=...,<=*a*[*n*] (1<=≤<=*a*[*i*]<=≤<=109) — array *a*. The third line contains *m* space-separated integers *b*1,<=*b*2,<=...,<=*b**m* (2<=≤<=*b*1<=&lt;<=*b*2<=&lt;<=...<=&lt;<=*b**m*<=≤<=109) — the set of bad prime numbers.
Print a single integer — the answer to the problem.
[ "5 2\n4 20 34 10 10\n2 5\n", "4 5\n2 4 8 16\n3 5 7 11 17\n" ]
[ "-2\n", "10\n" ]
Note that the answer to the problem can be negative. The GCD(*x*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub>, ..., *x*<sub class="lower-index">*k*</sub>) is the maximum positive integer that divides each *x*<sub class="lower-index">*i*</sub>.
[]
62
2,867,200
-1
44,797
766
Mahmoud and a Message
[ "brute force", "dp", "greedy", "strings" ]
null
null
Mahmoud wrote a message *s* of length *n*. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number *i* in the English alphabet to be written on it in a string of length more than *a**i*. For example, if *a*1<==<=2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not. Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be *n* and they shouldn't overlap. For example, if *a*1<==<=2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than *n*. He can split the message into single string if it fulfills the conditions. A substring of string *s* is a string that consists of some consecutive characters from string *s*, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself. While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions: - How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is *n* and they don't overlap? Compute the answer modulo 109<=+<=7. - What is the maximum length of a substring that can appear in some valid splitting? - What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa".
The first line contains an integer *n* (1<=≤<=*n*<=≤<=103) denoting the length of the message. The second line contains the message *s* of length *n* that consists of lowercase English letters. The third line contains 26 integers *a*1,<=*a*2,<=...,<=*a*26 (1<=≤<=*a**x*<=≤<=103) — the maximum lengths of substring each letter can appear in.
Print three lines. In the first line print the number of ways to split the message into substrings and fulfill the conditions mentioned in the problem modulo 109<=<=+<=<=7. In the second line print the length of the longest substring over all the ways. In the third line print the minimum number of substrings over all the ways.
[ "3\naab\n2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n", "10\nabcdeabcde\n5 5 5 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n" ]
[ "3\n2\n2\n", "401\n4\n3\n" ]
In the first example the three ways to split the message are: - a|a|b - aa|b - a|ab The longest substrings are "aa" and "ab" of length 2. The minimum number of substrings is 2 in "a|ab" or "aa|b". Notice that "aab" is not a possible splitting because the letter 'a' appears in a substring of length 3, while *a*<sub class="lower-index">1</sub> = 2.
[ { "input": "3\naab\n2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "output": "3\n2\n2" }, { "input": "10\nabcdeabcde\n5 5 5 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "output": "401\n4\n3" }, { "input": "10\naaaaaaaaaa\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", ...
77
3,276,800
3
44,808
853
Lada Malina
[ "data structures", "geometry" ]
null
null
After long-term research and lots of experiments leading Megapolian automobile manufacturer «AutoVoz» released a brand new car model named «Lada Malina». One of the most impressive features of «Lada Malina» is its highly efficient environment-friendly engines. Consider car as a point in *Oxy* plane. Car is equipped with *k* engines numbered from 1 to *k*. Each engine is defined by its velocity vector whose coordinates are (*vx**i*,<=*vy**i*) measured in distance units per day. An engine may be turned on at any level *w**i*, that is a real number between <=-<=1 and <=+<=1 (inclusive) that result in a term of (*w**i*·*vx**i*,<=*w**i*·*vy**i*) in the final car velocity. Namely, the final car velocity is equal to Formally, if car moves with constant values of *w**i* during the whole day then its *x*-coordinate will change by the first component of an expression above, and its *y*-coordinate will change by the second component of an expression above. For example, if all *w**i* are equal to zero, the car won't move, and if all *w**i* are equal to zero except *w*1<==<=1, then car will move with the velocity of the first engine. There are *n* factories in Megapolia, *i*-th of them is located in (*fx**i*,<=*fy**i*). On the *i*-th factory there are *a**i* cars «Lada Malina» that are ready for operation. As an attempt to increase sales of a new car, «AutoVoz» is going to hold an international exposition of cars. There are *q* options of exposition location and time, in the *i*-th of them exposition will happen in a point with coordinates (*px**i*,<=*py**i*) in *t**i* days. Of course, at the «AutoVoz» is going to bring as much new cars from factories as possible to the place of exposition. Cars are going to be moved by enabling their engines on some certain levels, such that at the beginning of an exposition car gets exactly to the exposition location. However, for some of the options it may be impossible to bring cars from some of the factories to the exposition location by the moment of an exposition. Your task is to determine for each of the options of exposition location and time how many cars will be able to get there by the beginning of an exposition.
The first line of input contains three integers *k*,<=*n*,<=*q* (2<=≤<=*k*<=≤<=10, 1<=≤<=*n*<=≤<=105, 1<=≤<=*q*<=≤<=105), the number of engines of «Lada Malina», number of factories producing «Lada Malina» and number of options of an exposition time and location respectively. The following *k* lines contain the descriptions of «Lada Malina» engines. The *i*-th of them contains two integers *vx**i*, *vy**i* (<=-<=1000<=≤<=*vx**i*,<=*vy**i*<=≤<=1000) defining the velocity vector of the *i*-th engine. Velocity vector can't be zero, i.e. at least one of *vx**i* and *vy**i* is not equal to zero. It is guaranteed that no two velosity vectors are collinear (parallel). Next *n* lines contain the descriptions of factories. The *i*-th of them contains two integers *fx**i*, *fy**i*, *a**i* (<=-<=109<=≤<=*fx**i*,<=*fy**i*<=≤<=109, 1<=≤<=*a**i*<=≤<=109) defining the coordinates of the *i*-th factory location and the number of cars that are located there. The following *q* lines contain the descriptions of the car exposition. The *i*-th of them contains three integers *px**i*, *py**i*, *t**i* (<=-<=109<=≤<=*px**i*,<=*py**i*<=≤<=109, 1<=≤<=*t**i*<=≤<=105) defining the coordinates of the exposition location and the number of days till the exposition start in the *i*-th option.
For each possible option of the exposition output the number of cars that will be able to get to the exposition location by the moment of its beginning.
[ "2 4 1\n1 1\n-1 1\n2 3 1\n2 -2 1\n-2 1 1\n-2 -2 1\n0 0 2\n", "3 4 3\n2 0\n-1 1\n-1 -2\n-3 0 6\n1 -2 1\n-3 -7 3\n3 2 2\n-1 -4 1\n0 4 2\n6 0 1\n" ]
[ "3\n", "4\n9\n0\n" ]
Images describing sample tests are given below. Exposition options are denoted with crosses, factories are denoted with points. Each factory is labeled with a number of cars that it has. First sample test explanation: - Car from the first factory is not able to get to the exposition location in time. - Car from the second factory can get to the exposition in time if we set *w*<sub class="lower-index">1</sub> = 0, *w*<sub class="lower-index">2</sub> = 1. - Car from the third factory can get to the exposition in time if we set <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1a41eaee1a8903558be190d96f56b1bfe60e3ba9.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a8b87da549f125113bd6a37b75809d13a7c05c07.png" style="max-width: 100.0%;max-height: 100.0%;"/>. - Car from the fourth factory can get to the exposition in time if we set *w*<sub class="lower-index">1</sub> = 1, *w*<sub class="lower-index">2</sub> = 0.
[]
46
0
0
44,871