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
487
Fight the Monster
[ "binary search", "brute force", "implementation" ]
null
null
A monster is attacking the Cyberland! Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (*HP*), offensive power (*ATK*) and defensive power (*DEF*). During the battle, every second the monster's HP decrease by *max*(0,<=*ATK**Y*<=-<=*DEF**M*), while Yang's HP decreases by *max*(0,<=*ATK**M*<=-<=*DEF**Y*), where index *Y* denotes Master Yang and index *M* denotes monster. Both decreases happen simultaneously Once monster's *HP*<=≀<=0 and the same time Master Yang's *HP*<=&gt;<=0, Master Yang wins. Master Yang can buy attributes from the magic shop of Cyberland: *h* bitcoins per *HP*, *a* bitcoins per *ATK*, and *d* bitcoins per *DEF*. Now Master Yang wants to know the minimum number of bitcoins he can spend in order to win.
The first line contains three integers *HP**Y*,<=*ATK**Y*,<=*DEF**Y*, separated by a space, denoting the initial *HP*, *ATK* and *DEF* of Master Yang. The second line contains three integers *HP**M*,<=*ATK**M*,<=*DEF**M*, separated by a space, denoting the *HP*, *ATK* and *DEF* of the monster. The third line contains three integers *h*,<=*a*,<=*d*, separated by a space, denoting the price of 1Β *HP*, 1Β *ATK* and 1Β *DEF*. All numbers in input are integer and lie between 1 and 100 inclusively.
The only output line should contain an integer, denoting the minimum bitcoins Master Yang should spend in order to win.
[ "1 2 1\n1 100 1\n1 100 100\n", "100 100 100\n1 1 1\n1 1 1\n" ]
[ "99\n", "0\n" ]
For the first sample, prices for *ATK* and *DEF* are extremely high. Master Yang can buy 99 HP, then he can beat the monster with 1 HP left. For the second sample, Master Yang is strong enough to beat the monster, so he doesn't need to buy anything.
[ { "input": "1 2 1\n1 100 1\n1 100 100", "output": "99" }, { "input": "100 100 100\n1 1 1\n1 1 1", "output": "0" }, { "input": "50 80 92\n41 51 56\n75 93 12", "output": "0" }, { "input": "76 63 14\n89 87 35\n20 15 56", "output": "915" }, { "input": "12 59 66\n43 15...
62
204,800
0
44,888
0
none
[ "none" ]
null
null
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: - There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. - There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. - Masculine adjectives end with -lios, and feminine adjectives end with -liala. - Masculine nouns end with -etr, and feminime nouns end with -etra. - Masculine verbs end with -initis, and feminime verbs end with -inites. - Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. - It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. - There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. - A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: - Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. - All words in the statement should have the same gender. After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
[ "petr\n", "etis atis animatis etis atis amatis\n", "nataliala kataliala vetra feinites\n" ]
[ "YES\n", "NO\n", "YES\n" ]
none
[ { "input": "petr", "output": "YES" }, { "input": "etis atis animatis etis atis amatis", "output": "NO" }, { "input": "nataliala kataliala vetra feinites", "output": "YES" }, { "input": "qweasbvflios", "output": "YES" }, { "input": "lios lios petr initis qwe", ...
124
6,963,200
0
45,004
0
none
[ "none" ]
null
null
Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :) Rick and Morty like to go to the ridge High Cry for crying loudlyΒ β€” there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this ridge: if Rick and Morty begin crying simultaneously from different mountains, their cry would be heard between these mountains up to the height equal the bitwise OR of mountains they've climbed and all the mountains between them. Bitwise OR is a binary operation which is determined the following way. Consider representation of numbers *x* and *y* in binary numeric system (probably with leading zeroes) *x*<==<=*x**k*... *x*1*x*0 and *y*<==<=*y**k*... *y*1*y*0. Then *z*<==<=*x*Β |Β *y* is defined following way: *z*<==<=*z**k*... *z*1*z*0, where *z**i*<==<=1, if *x**i*<==<=1 or *y**i*<==<=1, and *z**i*<==<=0 otherwise. In the other words, digit of bitwise OR of two numbers equals zero if and only if digits at corresponding positions is both numbers equals zero. For example bitwise OR of numbers 10<==<=10102 and 9<==<=10012 equals 11<==<=10112. In programming languages C/C++/Java/Python this operation is defined as Β«|Β», and in Pascal as Β«orΒ». Help Rick and Morty calculate the number of ways they can select two mountains in such a way that if they start crying from these mountains their cry will be heard above these mountains and all mountains between them. More formally you should find number of pairs *l* and *r* (1<=≀<=*l*<=&lt;<=*r*<=≀<=*n*) such that bitwise OR of heights of all mountains between *l* and *r* (inclusive) is larger than the height of any mountain at this interval.
The first line contains integer *n* (1<=≀<=*n*<=≀<=200<=000), the number of mountains in the ridge. Second line contains *n* integers *a**i* (0<=≀<=*a**i*<=≀<=109), the heights of mountains in order they are located in the ridge.
Print the only integer, the number of ways to choose two different mountains.
[ "5\n3 2 1 6 5\n", "4\n3 3 3 3\n" ]
[ "8\n", "0\n" ]
In the first test case all the ways are pairs of mountains with the numbers (numbering from one): In the second test case there are no such pairs because for any pair of mountains the height of cry from them is 3, and this height is equal to the height of any mountain.
[ { "input": "5\n3 2 1 6 5", "output": "8" }, { "input": "4\n3 3 3 3", "output": "0" }, { "input": "1\n0", "output": "0" }, { "input": "1\n1", "output": "0" }, { "input": "1\n1000000000", "output": "0" }, { "input": "1\n6", "output": "0" }, { ...
30
0
0
45,043
898
Squares and not squares
[ "constructive algorithms", "greedy" ]
null
null
Ann and Borya have *n* piles with candies and *n* is even number. There are *a**i* candies in pile with number *i*. Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly *n*<=/<=2 piles contain number of candies that is a square of some integer and exactly *n*<=/<=2 piles contain number of candies that is not a square of any integer.
First line contains one even integer *n* (2<=≀<=*n*<=≀<=200<=000)Β β€” number of piles with candies. Second line contains sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=109)Β β€” amounts of candies in each pile.
Output minimal number of steps required to make exactly *n*<=/<=2 piles contain number of candies that is a square of some integer and exactly *n*<=/<=2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.
[ "4\n12 14 30 4\n", "6\n0 0 0 0 0 0\n", "6\n120 110 23 34 25 45\n", "10\n121 56 78 81 45 100 1 0 54 78\n" ]
[ "2\n", "6\n", "3\n", "0\n" ]
In first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile). In second example you should add two candies to any three piles.
[ { "input": "4\n12 14 30 4", "output": "2" }, { "input": "6\n0 0 0 0 0 0", "output": "6" }, { "input": "6\n120 110 23 34 25 45", "output": "3" }, { "input": "10\n121 56 78 81 45 100 1 0 54 78", "output": "0" }, { "input": "10\n0 675178538 310440616 608075179 0 0 0 ...
2,000
25,088,000
0
45,254
961
k-substrings
[ "binary search", "hashing", "string suffix structures" ]
null
null
You are given a string *s* consisting of *n* lowercase Latin letters. Let's denote *k*-substring of *s* as a string *subs**k*<==<=*s**k**s**k*<=+<=1..*s**n*<=+<=1<=-<=*k*. Obviously, *subs*1<==<=*s*, and there are exactly such substrings. Let's call some string *t* an odd proper suprefix of a string *T* iff the following conditions are met: - |*T*|<=&gt;<=|*t*|; - |*t*| is an odd number; - *t* is simultaneously a prefix and a suffix of *T*. For evey *k*-substring () of *s* you have to calculate the maximum length of its odd proper suprefix.
The first line contains one integer *n* (2<=≀<=*n*<=≀<=106) β€” the length *s*. The second line contains the string *s* consisting of *n* lowercase Latin letters.
Print integers. *i*-th of them should be equal to maximum length of an odd proper suprefix of *i*-substring of *s* (or <=-<=1, if there is no such string that is an odd proper suprefix of *i*-substring).
[ "15\nbcabcabcabcabca\n", "24\nabaaabaaaabaaabaaaabaaab\n", "19\ncabcabbcabcabbcabca\n" ]
[ "9 7 5 3 1 -1 -1 -1\n", "15 13 11 9 7 5 3 1 1 -1 -1 1\n", "5 3 1 -1 -1 1 1 -1 -1 -1\n" ]
The answer for first sample test is folowing: - 1-substring: bcabcabcabcabca - 2-substring: cabcabcabcabc - 3-substring: abcabcabcab - 4-substring: bcabcabca - 5-substring: cabcabc - 6-substring: abcab - 7-substring: bca - 8-substring: c
[ { "input": "15\nbcabcabcabcabca", "output": "9 7 5 3 1 -1 -1 -1" }, { "input": "24\nabaaabaaaabaaabaaaabaaab", "output": "15 13 11 9 7 5 3 1 1 -1 -1 1" }, { "input": "19\ncabcabbcabcabbcabca", "output": "5 3 1 -1 -1 1 1 -1 -1 -1" }, { "input": "2\nza", "output": "-1" },...
31
0
0
45,445
436
Cardboard Box
[ "data structures", "greedy" ]
null
null
Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: *a**i* β€” how long it takes to complete the level for one star, *b**i* β€” how long it takes to complete the level for two stars (*a**i*<=&lt;<=*b**i*). You want to open the next box as quickly as possible. So, you need to earn at least *w* stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels.
The first line contains two integers *n* and *w* (1<=≀<=*n*<=≀<=3Β·105;Β 1<=≀<=*w*<=≀<=2*n*) β€” the number of levels in the first box and the number of stars you need to open another box. Each of the following *n* lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*<=&lt;<=*b**i*<=≀<=109) β€” the attributes of the *i*-th level.
In the first line print integer *t* β€” the minimum time you need to open the next box. In the next line, print *n* digits without spaces β€” the description of the optimal scenario: - if you need to pass the *i*-th level for one star, the *i*-th digit should equal 1; - if you need to pass the *i*-th level for two stars, the *i*-th digit should equal 2; - if you do not need to pass the *i*-th level at all, the *i*-th digit should equal 0.
[ "2 3\n1 2\n1 2\n", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30\n" ]
[ "3\n12\n", "14\n01020\n" ]
In the first test sample, answer 21 is also assumed correct.
[]
5,000
96,870,400
0
45,817
0
none
[ "none" ]
null
null
You're trying to set the record on your favorite video game. The game consists of *N* levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the *i*-th level in either *F**i* seconds or *S**i* seconds, where *F**i*<=&lt;<=*S**i*, and there's a *P**i* percent chance of completing it in *F**i* seconds. After completing a level, you may decide to either continue the game and play the next level, or reset the game and start again from the first level. Both the decision and the action are instant. Your goal is to complete all the levels sequentially in at most *R* total seconds. You want to minimize the expected amount of time playing before achieving that goal. If you continue and reset optimally, how much total time can you expect to spend playing?
The first line of input contains integers *N* and *R* , the number of levels and number of seconds you want to complete the game in, respectively. *N* lines follow. The *i*th such line contains integers *F**i*,<=*S**i*,<=*P**i* (1<=≀<=*F**i*<=&lt;<=*S**i*<=≀<=100,<=80<=≀<=*P**i*<=≀<=99), the fast time for level *i*, the slow time for level *i*, and the probability (as a percentage) of completing level *i* with the fast time.
Print the total expected time. Your answer must be correct within an absolute or relative error of 10<=-<=9. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer will be considered correct, if .
[ "1 8\n2 8 81\n", "2 30\n20 30 80\n3 9 85\n", "4 319\n63 79 89\n79 97 91\n75 87 88\n75 90 83\n" ]
[ "3.14\n", "31.4\n", "314.159265358\n" ]
In the first example, you never need to reset. There's an 81% chance of completing the level in 2 seconds and a 19% chance of needing 8 seconds, both of which are within the goal time. The expected time is 0.81Β·2 + 0.19Β·8 = 3.14. In the second example, you should reset after the first level if you complete it slowly. On average it will take 0.25 slow attempts before your first fast attempt. Then it doesn't matter whether you complete the second level fast or slow. The expected time is 0.25Β·30 + 20 + 0.85Β·3 + 0.15Β·9 = 31.4.
[]
30
0
0
45,871
332
Binary Key
[ "dp", "greedy", "implementation" ]
null
null
Let's assume that *p* and *q* are strings of positive length, called the container and the key correspondingly, string *q* only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message *s* from the given container *p*: In the given pseudocode *i*, *j* are integer variables, *s* is a string, '=' is an assignment operator, '==' is a comparison operation, '[]' is the operation of obtaining the string character with the preset index, '&lt;&gt;' is an empty string. We suppose that in all strings the characters are numbered starting from zero. We understand that implementing such algorithm is quite easy, so your task is going to be slightly different. You need to construct the lexicographically minimum key of length *k*, such that when it is used, the algorithm given above extracts message *s* from container *p* (otherwise find out that such key doesn't exist).
The first two lines of the input are non-empty strings *p* and *s* (1<=≀<=|*p*|<=≀<=106, 1<=≀<=|*s*|<=≀<=200), describing the container and the message, correspondingly. The strings can contain any characters with the ASCII codes from 32 to 126, inclusive. The third line contains a single integer *k* (1<=≀<=*k*<=≀<=2000) β€” the key's length.
Print the required key (string of length *k*, consisting only of characters 0 and 1). If the key doesn't exist, print the single character 0.
[ "abacaba\naba\n6\n", "abacaba\naba\n3\n" ]
[ "100001\n", "0\n" ]
String *x* = *x*<sub class="lower-index">1</sub>*x*<sub class="lower-index">2</sub>... *x*<sub class="lower-index">*p*</sub> is lexicographically smaller than string *y* = *y*<sub class="lower-index">1</sub>*y*<sub class="lower-index">2</sub>... *y*<sub class="lower-index">*q*</sub>, if either *p* &lt; *q* and *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*p*</sub> = *y*<sub class="lower-index">*p*</sub>, or there exists such integer *r* (0 ≀ *r* &lt; *min*(*p*, *q*)) that *x*<sub class="lower-index">1</sub> = *y*<sub class="lower-index">1</sub>, *x*<sub class="lower-index">2</sub> = *y*<sub class="lower-index">2</sub>, ... , *x*<sub class="lower-index">*r*</sub> = *y*<sub class="lower-index">*r*</sub> and *x*<sub class="lower-index">*r* + 1</sub> &lt; *y*<sub class="lower-index">*r* + 1</sub>. Symbols are compared according to their ASCII codes.
[]
93
0
0
45,918
0
none
[ "none" ]
null
null
You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest. The track's map is represented by a rectangle *n*<=Γ—<=*m* in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters *S*) and the terminating square (it is marked with a capital Latin letter *T*). The time of movement from one square to another is equal to 1 minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than *k* different types of squares (squares of one type can be visited an infinite number of times). Squares marked with *S* and *T* have no type, so they are not counted. But *S* must be visited exactly once β€” at the very beginning, and *T* must be visited exactly once β€” at the very end. Your task is to find the path from the square *S* to the square *T* that takes minimum time. Among all shortest paths you should choose the lexicographically minimal one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types.
The first input line contains three integers *n*, *m* and *k* (1<=≀<=*n*,<=*m*<=≀<=50,<=*n*Β·*m*<=β‰₯<=2,<=1<=≀<=*k*<=≀<=4). Then *n* lines contain the map. Each line has the length of exactly *m* characters and consists of lowercase Latin letters and characters *S* and *T*. It is guaranteed that the map contains exactly one character *S* and exactly one character *T*. Pretest 12 is one of the maximal tests for this problem.
If there is a path that satisfies the condition, print it as a sequence of letters β€” the plot types. Otherwise, print "-1" (without quotes). You shouldn't print the character *S* in the beginning and *T* in the end. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.
[ "5 3 2\nSba\nccc\naac\nccc\nabT\n", "3 4 1\nSxyy\nyxxx\nyyyT\n", "1 3 3\nTyS\n", "1 4 1\nSxyT\n" ]
[ "bcccc\n", "xxxx\n", "y\n", "-1\n" ]
none
[ { "input": "5 3 2\nSba\nccc\naac\nccc\nabT", "output": "bcccc" }, { "input": "3 4 1\nSxyy\nyxxx\nyyyT", "output": "xxxx" }, { "input": "1 3 3\nTyS", "output": "y" }, { "input": "1 4 1\nSxyT", "output": "-1" }, { "input": "1 3 3\nSaT", "output": "a" }, { ...
92
0
0
45,921
144
Missile Silos
[ "data structures", "dfs and similar", "graphs", "shortest paths" ]
null
null
A country called Berland consists of *n* cities, numbered with integer numbers from 1 to *n*. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance *l* from the capital. The capital is located in the city with number *s*. The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly *l*. Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
The first line contains three integers *n*, *m* and *s* (2<=≀<=*n*<=≀<=105, , 1<=≀<=*s*<=≀<=*n*) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. *s*. Then *m* lines contain the descriptions of roads. Each of them is described by three integers *v**i*, *u**i*, *w**i* (1<=≀<=*v**i*,<=*u**i*<=≀<=*n*, *v**i*<=β‰ <=*u**i*, 1<=≀<=*w**i*<=≀<=1000), where *v**i*, *u**i* are numbers of the cities connected by this road and *w**i* is its length. The last input line contains integer *l* (0<=≀<=*l*<=≀<=109) β€” the distance from the capital to the missile silos. It is guaranteed that: - between any two cities no more than one road exists; - each road connects two different cities; - from each city there is at least one way to any other city by the roads.
Print the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.
[ "4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2\n", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4\n" ]
[ "3\n", "3\n" ]
In the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3). In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
[]
92
102,400
0
45,946
276
Little Girl and Problem on Trees
[ "data structures", "graphs", "trees" ]
null
null
A little girl loves problems on trees very much. Here's one of them. A tree is an undirected connected graph, not containing cycles. The degree of node *x* in the tree is the number of nodes *y* of the tree, such that each of them is connected with node *x* by some edge of the tree. Let's consider a tree that consists of *n* nodes. We'll consider the tree's nodes indexed from 1 to *n*. The cosidered tree has the following property: each node except for node number 1 has the degree of at most 2. Initially, each node of the tree contains number 0. Your task is to quickly process the requests of two types: - Request of form: 0 *v* *x* *d*. In reply to the request you should add *x* to all numbers that are written in the nodes that are located at the distance of at most *d* from node *v*. The distance between two nodes is the number of edges on the shortest path between them. - Request of form: 1 *v*. In reply to the request you should print the current number that is written in node *v*.
The first line contains integers *n* (2<=≀<=*n*<=≀<=105) and *q* (1<=≀<=*q*<=≀<=105) β€” the number of tree nodes and the number of requests, correspondingly. Each of the next *n*<=<=-<=<=1 lines contains two integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*, *u**i*<=β‰ <=*v**i*), that show that there is an edge between nodes *u**i* and *v**i*. Each edge's description occurs in the input exactly once. It is guaranteed that the given graph is a tree that has the property that is described in the statement. Next *q* lines describe the requests. - The request to add has the following format: 0 *v* *x* *d* (1<=≀<=*v*<=≀<=*n*, 1<=≀<=*x*<=≀<=104, 1<=≀<=*d*<=&lt;<=*n*). - The request to print the node value has the following format: 1 *v* (1<=≀<=*v*<=≀<=*n*). The numbers in the lines are separated by single spaces.
For each request to print the node value print an integer β€” the reply to the request.
[ "3 6\n1 2\n1 3\n0 3 1 2\n0 2 3 1\n0 1 5 2\n1 1\n1 2\n1 3\n", "6 11\n1 2\n2 5\n5 4\n1 6\n1 3\n0 3 1 3\n0 3 4 5\n0 2 1 4\n0 1 5 5\n0 4 6 2\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n" ]
[ "9\n9\n6\n", "11\n17\n11\n16\n17\n11\n" ]
none
[ { "input": "3 6\n1 2\n1 3\n0 3 1 2\n0 2 3 1\n0 1 5 2\n1 1\n1 2\n1 3", "output": "9\n9\n6" }, { "input": "6 11\n1 2\n2 5\n5 4\n1 6\n1 3\n0 3 1 3\n0 3 4 5\n0 2 1 4\n0 1 5 5\n0 4 6 2\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6", "output": "11\n17\n11\n16\n17\n11" }, { "input": "4 8\n2 1\n1 4\n2 3\n0 4 92...
62
0
0
45,956
0
none
[ "none" ]
null
null
Π’ БСрляндском государствСнном унивСрситСтС локальная ΡΠ΅Ρ‚ΡŒ ΠΌΠ΅ΠΆΠ΄Ρƒ сСрвСрами Π½Π΅ всСгда Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚ Π±Π΅Π· ошибок. ΠŸΡ€ΠΈ ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‡Π΅ Π΄Π²ΡƒΡ… ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ²Ρ‹Ρ… сообщСний подряд Π²ΠΎΠ·ΠΌΠΎΠΆΠ½Π° ошибка, Π² Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π΅ ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠΉ эти Π΄Π²Π° сообщСния ΡΠ»ΠΈΠ²Π°ΡŽΡ‚ΡΡ Π² ΠΎΠ΄Π½ΠΎ. ΠŸΡ€ΠΈ Ρ‚Π°ΠΊΠΎΠΌ слиянии ΠΊΠΎΠ½Π΅Ρ† ΠΏΠ΅Ρ€Π²ΠΎΠ³ΠΎ сообщСния совмСщаСтся с Π½Π°Ρ‡Π°Π»ΠΎΠΌ Π²Ρ‚ΠΎΡ€ΠΎΠ³ΠΎ. ΠšΠΎΠ½Π΅Ρ‡Π½ΠΎ, совмСщСниС ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΡ€ΠΎΠΈΡΡ…ΠΎΠ΄ΠΈΡ‚ΡŒ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ ΠΏΠΎ ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ²Ρ‹ΠΌ символам. Π”Π»ΠΈΠ½Π° совмСщСния Π΄ΠΎΠ»ΠΆΠ½Π° Π±Ρ‹Ρ‚ΡŒ ΠΏΠΎΠ»ΠΎΠΆΠΈΡ‚Π΅Π»ΡŒΠ½Ρ‹ΠΌ числом, мСньшим Π΄Π»ΠΈΠ½Ρ‹ тСкста сообщСния. НапримСр, ΠΏΡ€ΠΈ ΠΏΠ΅Ρ€Π΅Π΄Π°Ρ‡Π΅ Π΄Π²ΡƒΡ… сообщСний Β«abrakadabraΒ» подряд Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ, Ρ‡Ρ‚ΠΎ ΠΎΠ½ΠΎ Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠ΅Ρ€Π΅Π΄Π°Π½ΠΎ с ошибкой описанного Π²ΠΈΠ΄Π°, ΠΈ Ρ‚ΠΎΠ³Π΄Π° Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½ΠΎ сообщСниС Π²ΠΈΠ΄Π° Β«abrakadabrabrakadabraΒ» ΠΈΠ»ΠΈ Β«abrakadabrakadabraΒ» (Π² ΠΏΠ΅Ρ€Π²ΠΎΠΌ случаС совмСщСниС ΠΏΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»ΠΎ ΠΏΠΎ ΠΎΠ΄Π½ΠΎΠΌΡƒ символу, Π° Π²ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠΌ β€” ΠΏΠΎ Ρ‡Π΅Ρ‚Ρ‹Ρ€Π΅ΠΌ). По ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½Π½ΠΎΠΌΡƒ ΡΠΎΠΎΠ±Ρ‰Π΅Π½ΠΈΡŽ *t* ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΠΈΡ‚Π΅, Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ Π»ΠΈ, Ρ‡Ρ‚ΠΎ это Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ ошибки описанного Π²ΠΈΠ΄Π° Ρ€Π°Π±ΠΎΡ‚Ρ‹ локальной сСти, ΠΈ Ссли Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ, ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΠΈΡ‚Π΅ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΠ΅ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ *s*. НС слСдуСт ΡΡ‡ΠΈΡ‚Π°Ρ‚ΡŒ ошибкой ΡΠΈΡ‚ΡƒΠ°Ρ†ΠΈΡŽ ΠΏΠΎΠ»Π½ΠΎΠ³ΠΎ налоТСния Π΄Ρ€ΡƒΠ³Π° Π½Π° Π΄Ρ€ΡƒΠ³Π° Π΄Π²ΡƒΡ… сообщСний. К ΠΏΡ€ΠΈΠΌΠ΅Ρ€Ρƒ, Ссли ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½ΠΎ сообщСниС Β«abcdΒ», слСдуСт ΡΡ‡ΠΈΡ‚Π°Ρ‚ΡŒ, Ρ‡Ρ‚ΠΎ Π² Π½Ρ‘ΠΌ ошибки Π½Π΅Ρ‚. Аналогично, простоС дописываниС ΠΎΠ΄Π½ΠΎΠ³ΠΎ сообщСния вслСд Π·Π° Π΄Ρ€ΡƒΠ³ΠΈΠΌ Π½Π΅ являСтся ΠΏΡ€ΠΈΠ·Π½Π°ΠΊΠΎΠΌ ошибки. НапримСр, Ссли ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½ΠΎ сообщСниС Β«abcabcΒ», слСдуСт ΡΡ‡ΠΈΡ‚Π°Ρ‚ΡŒ, Ρ‡Ρ‚ΠΎ Π² Π½Ρ‘ΠΌ ошибки Π½Π΅Ρ‚.
Π’ СдинствСнной строкС Π²Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ… слСдуСт нСпустая строка *t*, состоящая ΠΈΠ· строчных Π±ΡƒΠΊΠ² латинского Π°Π»Ρ„Π°Π²ΠΈΡ‚Π°. Π”Π»ΠΈΠ½Π° строки *t* Π½Π΅ прСвосходит 100 символов.
Если сообщСниС *t* Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ ΡΠΎΠ΄Π΅Ρ€ΠΆΠ°Ρ‚ΡŒ ошибки, Π²Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ Β«NOΒ» (Π±Π΅Π· ΠΊΠ°Π²Ρ‹Ρ‡Π΅ΠΊ) Π² Π΅Π΄ΠΈΠ½ΡΡ‚Π²Π΅Π½Π½ΡƒΡŽ строку Π²Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Ρ… Π΄Π°Π½Π½Ρ‹Ρ…. Π’ ΠΏΡ€ΠΎΡ‚ΠΈΠ²Π½ΠΎΠΌ случаС Π² ΠΏΠ΅Ρ€Π²ΠΎΠΉ строкС Π²Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ Β«YESΒ» (Π±Π΅Π· ΠΊΠ°Π²Ρ‹Ρ‡Π΅ΠΊ), Π° Π² ΡΠ»Π΅Π΄ΡƒΡŽΡ‰Π΅ΠΉ строкС Π²Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ строку *s*Β β€” Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΠ΅ сообщСниС, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ ΠΌΠΎΠ³Π»ΠΎ привСсти ΠΊ ошибкС. Если Π²ΠΎΠ·ΠΌΠΎΠΆΠ½Ρ‹Ρ… ΠΎΡ‚Π²Π΅Ρ‚ΠΎΠ² нСсколько, Ρ€Π°Π·Ρ€Π΅ΡˆΠ°Π΅Ρ‚ΡΡ вывСсти любой ΠΈΠ· Π½ΠΈΡ….
[ "abrakadabrabrakadabra\n", "acacacaca\n", "abcabc\n", "abababab\n", "tatbt\n" ]
[ "YES\nabrakadabra\n", "YES\nacaca\n", "NO\n", "YES\nababab\n", "NO\n" ]
Π’ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠΌ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π΅ подходящим ΠΎΡ‚Π²Π΅Ρ‚ΠΎΠΌ Ρ‚Π°ΠΊΠΆΠ΅ являСтся строка acacaca.
[ { "input": "abrakadabrabrakadabra", "output": "YES\nabrakadabra" }, { "input": "acacacaca", "output": "YES\nacaca" }, { "input": "abcabc", "output": "NO" }, { "input": "abababab", "output": "YES\nababab" }, { "input": "tatbt", "output": "NO" }, { "inpu...
46
4,608,000
0
46,013
437
The Child and Zoo
[ "dsu", "sortings" ]
null
null
Of course our child likes walking in a zoo. The zoo has *n* areas, that are numbered from 1 to *n*. The *i*-th area contains *a**i* animals in it. Also there are *m* roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads. Our child is very smart. Imagine the child want to go from area *p* to area *q*. Firstly he considers all the simple routes from *p* to *q*. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as *f*(*p*,<=*q*). Finally, the child chooses one of the routes for which he writes down the value *f*(*p*,<=*q*). After the child has visited the zoo, he thinks about the question: what is the average value of *f*(*p*,<=*q*) for all pairs *p*,<=*q* (*p*<=β‰ <=*q*)? Can you answer his question?
The first line contains two integers *n* and *m* (2<=≀<=*n*<=≀<=105; 0<=≀<=*m*<=≀<=105). The second line contains *n* integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=105). Then follow *m* lines, each line contains two integers *x**i* and *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*; *x**i*<=β‰ <=*y**i*), denoting the road between areas *x**i* and *y**i*. All roads are bidirectional, each pair of areas is connected by at most one road.
Output a real number β€” the value of . The answer will be considered correct if its relative or absolute error doesn't exceed 10<=-<=4.
[ "4 3\n10 20 30 40\n1 3\n2 3\n4 3\n", "3 3\n10 20 30\n1 2\n2 3\n3 1\n", "7 8\n40 20 10 30 20 50 40\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n1 4\n5 7\n" ]
[ "16.666667\n", "13.333333\n", "18.571429\n" ]
Consider the first sample. There are 12 possible situations: - *p* = 1, *q* = 3, *f*(*p*, *q*) = 10. - *p* = 2, *q* = 3, *f*(*p*, *q*) = 20. - *p* = 4, *q* = 3, *f*(*p*, *q*) = 30. - *p* = 1, *q* = 2, *f*(*p*, *q*) = 10. - *p* = 2, *q* = 4, *f*(*p*, *q*) = 20. - *p* = 4, *q* = 1, *f*(*p*, *q*) = 10. Another 6 cases are symmetrical to the above. The average is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7d9c496a5e88de440a3524fc0ff31a1eb3c1319f.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Consider the second sample. There are 6 possible situations: - *p* = 1, *q* = 2, *f*(*p*, *q*) = 10. - *p* = 2, *q* = 3, *f*(*p*, *q*) = 20. - *p* = 1, *q* = 3, *f*(*p*, *q*) = 10. Another 3 cases are symmetrical to the above. The average is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/fb2ccbdfc02919359d0cc1f9a87c77b936f33464.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "4 3\n10 20 30 40\n1 3\n2 3\n4 3", "output": "16.666667" }, { "input": "3 3\n10 20 30\n1 2\n2 3\n3 1", "output": "13.333333" }, { "input": "7 8\n40 20 10 30 20 50 40\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n1 4\n5 7", "output": "18.571429" }, { "input": "10 14\n594 965 90 32...
46
0
0
46,071
768
Jon and Orbs
[ "dp", "math", "probabilities" ]
null
null
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are *k* different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where Ξ΅<=&lt;<=10<=-<=7. To better prepare himself, he wants to know the answer for *q* different values of *p**i*. Since he is busy designing the battle strategy with Sam, he asks you for your help.
First line consists of two space separated integers *k*, *q* (1<=≀<=*k*,<=*q*<=≀<=1000) β€” number of different kinds of orbs and number of queries respectively. Each of the next *q* lines contain a single integer *p**i* (1<=≀<=*p**i*<=≀<=1000) β€” *i*-th query.
Output *q* lines. On *i*-th of them output single integer β€” answer for *i*-th query.
[ "1 1\n1\n", "2 2\n1\n2\n" ]
[ "1\n", "2\n2\n" ]
none
[ { "input": "1 1\n1", "output": "1" }, { "input": "2 2\n1\n2", "output": "2\n2" }, { "input": "3 5\n1\n4\n20\n50\n300", "output": "3\n3\n3\n3\n3" }, { "input": "4 5\n2\n4\n30\n100\n1000", "output": "4\n4\n4\n4\n7" }, { "input": "5 6\n1\n2\n3\n4\n5\n6", "output"...
2,000
248,627,200
0
46,093
909
Colorful Points
[ "data structures", "greedy", "implementation" ]
null
null
You are given a set of points on a straight line. Each point has a color assigned to it. For point *a*, its neighbors are the points which don't have any other points between them and *a*. Each point has at most two neighbors - one from the left and one from the right. You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it. How many operations will you need to perform until the next operation does not have any points to delete?
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc. The number of the points is between 1 and 106.
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
[ "aabb\n", "aabcaa\n" ]
[ "2\n", "1\n" ]
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to. In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied.
[ { "input": "aabb", "output": "2" }, { "input": "aabcaa", "output": "1" }, { "input": "abbcccbba", "output": "1" }, { "input": "aaaaaaaaaaa", "output": "0" }, { "input": "aaaaaaaaabbbbbaaaabaaaaaaaaaaaaaaaaabaaaaaabbbbbbbaaabbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaa...
2,000
13,414,400
0
46,143
717
Festival Organization
[ "combinatorics", "math", "number theory" ]
null
null
The Prodiggers are quite a cool band and for this reason, they have been the surprise guest at the ENTER festival for the past 80 years. At the beginning of their careers, they weren’t so successful, so they had to spend time digging channels to earn money; hence the name. Anyway, they like to tour a lot and have surprising amounts of energy to do extremely long tours. However, they hate spending two consecutive days without having a concert, so they would like to avoid it. A tour is defined by a sequence of concerts and days-off. You need to count in how many ways The Prodiggers can select *k* different tours of the same length between *l* and *r*. For example if *k*<==<=2, *l*<==<=1 and *r*<==<=2, if we define concert day as {1} and day-off as {0}, here are all possible tours: {0}, {1}, {00}, {01}, {10}, {11}. But tour 00 can not be selected because it has 2 days-off in a row. Now, we need to count in how many ways we can select *k*<==<=2 tours of the same length in range [1;2]. Here they are: {0,1}; {01,10}; {01,11}; {10,11}. Since their schedule is quite busy, they want you to tell them in how many ways can do that, modulo 1<=000<=000<=007 (109<=+<=7).
The first line of the input contains three integers *k*, *l* and *r* (1<=≀<=*k*<=≀<=200, 1<=≀<=*l*<=≀<=*r*<=≀<=1018).
Output a single number: the number of ways to select *k* different tours of the same length, modulo 1<=000<=000<=007.
[ "1 1 2\n" ]
[ "5\n" ]
none
[]
46
5,632,000
-1
46,154
884
Anti-Palindromize
[ "flows", "graphs", "greedy" ]
null
null
A string *a* of length *m* is called antipalindromic iff *m* is even, and for each *i* (1<=≀<=*i*<=≀<=*m*) *a**i*<=β‰ <=*a**m*<=-<=*i*<=+<=1. Ivan has a string *s* consisting of *n* lowercase Latin letters; *n* is even. He wants to form some string *t* that will be an antipalindromic permutation of *s*. Also Ivan has denoted the beauty of index *i* as *b**i*, and the beauty of *t* as the sum of *b**i* among all indices *i* such that *s**i*<==<=*t**i*. Help Ivan to determine maximum possible beauty of *t* he can get.
The first line contains one integer *n* (2<=≀<=*n*<=≀<=100, *n* is even) β€” the number of characters in *s*. The second line contains the string *s* itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string. The third line contains *n* integer numbers *b*1, *b*2, ..., *b**n* (1<=≀<=*b**i*<=≀<=100), where *b**i* is the beauty of index *i*.
Print one number β€” the maximum possible beauty of *t*.
[ "8\nabacabac\n1 1 1 1 1 1 1 1\n", "8\nabaccaba\n1 2 3 4 5 6 7 8\n", "8\nabacabca\n1 2 3 4 4 3 2 1\n" ]
[ "8\n", "26\n", "17\n" ]
none
[ { "input": "8\nabacabac\n1 1 1 1 1 1 1 1", "output": "8" }, { "input": "8\nabaccaba\n1 2 3 4 5 6 7 8", "output": "26" }, { "input": "8\nabacabca\n1 2 3 4 4 3 2 1", "output": "17" }, { "input": "100\nbaaacbccbccaccaccaaabcabcabccacaabcbccbccabbabcbcbbaacacbacacacaacccbcbbbbacc...
108
307,200
0
46,264
917
Stranger Trees
[ "dp", "math", "matrices", "trees" ]
null
null
Will shares a psychic connection with the Upside Down Monster, so everything the monster knows, Will knows. Suddenly, he started drawing, page after page, non-stop. Joyce, his mom, and Chief Hopper put the drawings together, and they realized, it's a labeled tree! A tree is a connected acyclic graph. Will's tree has *n* vertices. Joyce and Hopper don't know what that means, so they're investigating this tree and similar trees. For each *k* such that 0<=≀<=*k*<=≀<=*n*<=-<=1, they're going to investigate all labeled trees with *n* vertices that share exactly *k* edges with Will's tree. Two labeled trees are different if and only if there's a pair of vertices (*v*,<=*u*) such that there's an edge between *v* and *u* in one tree and not in the other one. Hopper and Joyce want to know how much work they have to do, so they asked you to tell them the number of labeled trees with *n* vertices that share exactly *k* edges with Will's tree, for each *k*. The answer could be very large, so they only asked you to tell them the answers modulo 1000000007<==<=109<=+<=7.
The first line of input contains a single integer *n* (2<=≀<=*n*<=≀<=100)Β β€” the size of the tree. The next *n*<=-<=1 lines contain the edges of Will's tree. Each line contains two integers *v* and *u* (1<=≀<=*v*,<=*u*<=≀<=*n*, *v*<=β‰ <=*u*), endpoints of an edge. It is guaranteed that the given graph is a tree.
Print *n* integers in one line. *i*-th integer should be the number of the number of labeled trees with *n* vertices that share exactly *i*<=-<=1 edges with Will's tree, modulo 1000<=000<=007<==<=109<=+<=7.
[ "3\n1 2\n1 3\n", "4\n1 2\n2 3\n3 4\n", "4\n1 2\n1 3\n1 4\n" ]
[ "0 2 1 ", "1 7 7 1 ", "0 9 6 1 " ]
none
[]
62
0
0
46,300
413
2048
[ "bitmasks", "dp" ]
null
null
The programmers from the R2 company love playing 2048. One day, they decided to invent their own simplified version of this game β€” 2*k* on a stripe. Imagine an infinite in one direction stripe, consisting of unit squares (the side of each square is equal to the height of the stripe). Each square can either be empty or contain some number. Initially, all squares are empty. Then at infinity one of the unit squares number 2 or 4 appears. Then the player presses a button once, and the appeared number begins to move towards the beginning of the stripe. Let's assume that some number *x* moves to the beginning of the stripe, then it will stop if: 1. it either gets in the first square of the stripe; 1. or it is in the square that is preceded by a square with number *y* (*y*<=β‰ <=*x*). But if number *x* at some point of time gets to the square with the same number then both numbers add to each other and result in 2*x*. The new number 2*x* continues moving to the beginning of the stripe by the same rules. After the final stop of the number moving process, the infinity gets a new number 2 or 4 and the process repeats. Read the notes to the test samples to better understand the moving strategy. I guess you've understood that the game progress fully depends on the order in which numbers 2 and 4 appear. Let's look at some sequence of numbers 2 and 4 in the game. We assume that the sequence is winning if it results in at least one square getting the number greater or equal than 2*k*. The goal of the game is to make up a winning sequence of *n* numbers. But not everything is so simple, some numbers in the sequence are identified beforehand. You are given a sequence consisting of numbers 0, 2, 4. Count how many ways there are to replace each 0 of the sequence with 2 or 4 to get a winning sequence.
The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=2000;Β 3<=≀<=*k*<=≀<=11). The next line contains sequence of *n* integers, each of them is either 0, or 2, or 4.
Print a single integer β€” the number of ways to replace zeroes by numbers 2 or 4 to get a winning sequence. As this number can be rather large, print it modulo 1000000007 (109<=+<=7).
[ "7 4\n2 2 4 2 2 2 2\n", "1 3\n0\n", "2 3\n0 4\n", "5 4\n2 0 0 4 4\n" ]
[ "1\n", "0\n", "1\n", "2\n" ]
Consider the first example. The beginning of the strip will look as follows: 2  →  4  →  8  →  8 2  →  8 4  →  8 4 2  →  16. To better understand the game, you can see the original game on http://gabrielecirulli.github.io/2048/. Please note that the game that is described on the strip is slightly different from the original game (when the two numbers add up in the original game, they do not keep moving). Be careful, the game is addictive, there isn't much time for the contest!
[]
31
0
0
46,578
461
Appleman and a Game
[ "binary search", "shortest paths", "strings" ]
null
null
Appleman and Toastman like games. Today they play a game with strings with the following rules. Firstly Toastman tells Appleman two strings *s* and *t* both consisting only of letters 'A', 'B', 'C', 'D'. Then Appleman must build string *s* as quickly as possible. Initially he has empty string, and in one second he can append to end of the current string any contiguous substring of *t*. Now, Toastman and Appleman are beginning to play the game. Toastman has already told string *t* to Appleman, but he hasn't come up with string *s* yet. Toastman only thinks, that he should choose string *s* consisting of *n* characters. Of course, he wants to find the worst string for Appleman (such string, that Appleman will spend as much time as possible during the game). Tell Toastman, how much time will Appleman spend during the game if Toastman finds the worst string for him. You can assume that Appleman plays optimally, therefore he builds any string *s* in minimal possible time.
The first line contains an integer *n* (1<=≀<=*n*<=≀<=1018). The second line contains string *t* (1<=≀<=|*t*|<=≀<=105). String *t* consists of only letters 'A', 'B', 'C', 'D'. Each letter appears at least once in string *t*.
Print a single integer β€” the largest possible time Appleman needs.
[ "5\nABCCAD\n", "5\nAAABACADBABBBCBDCACBCCCDDDBDCDD\n" ]
[ "5\n", "4\n" ]
In the first example, Toastman can choose *s* equal to "AAAAA". In the second example, Toastman can choose *s* equal to "DADDA".
[]
30
0
0
46,669
1,008
Turn the Rectangles
[ "greedy", "sortings" ]
null
null
There are $n$ rectangles in a row. You can either turn each rectangle by $90$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles. Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$)Β β€” the number of rectangles. Each of the next $n$ lines contains two integers $w_i$ and $h_i$ ($1 \leq w_i, h_i \leq 10^9$)Β β€” the width and the height of the $i$-th rectangle.
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO". You can print each letter in any case (upper or lower).
[ "3\n3 4\n4 6\n3 5\n", "2\n3 4\n5 5\n" ]
[ "YES\n", "NO\n" ]
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3]. In the second test, there is no way the second rectangle will be not higher than the first one.
[ { "input": "3\n3 4\n4 6\n3 5", "output": "YES" }, { "input": "2\n3 4\n5 5", "output": "NO" }, { "input": "10\n4 3\n1 1\n6 5\n4 5\n2 4\n9 5\n7 9\n9 2\n4 10\n10 1", "output": "NO" }, { "input": "10\n241724251 76314740\n80658193 177743680\n213953908 406274173\n485639518 85918805...
249
0
0
46,819
749
Leaving Auction
[ "binary search", "data structures" ]
null
null
There are *n* people taking part in auction today. The rules of auction are classical. There were *n* bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all. Each bid is define by two integers (*a**i*,<=*b**i*), where *a**i* is the index of the person, who made this bid and *b**i* is its size. Bids are given in chronological order, meaning *b**i*<=&lt;<=*b**i*<=+<=1 for all *i*<=&lt;<=*n*. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. *a**i*<=β‰ <=*a**i*<=+<=1 for all *i*<=&lt;<=*n*. Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added. Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples. You have several questions in your mind, compute the answer for each of them.
The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=200<=000)Β β€” the number of participants and bids. Each of the following *n* lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*<=≀<=*n*,<=1<=≀<=*b**i*<=≀<=109,<=*b**i*<=&lt;<=*b**i*<=+<=1)Β β€” the number of participant who made the *i*-th bid and the size of this bid. Next line contains an integer *q* (1<=≀<=*q*<=≀<=200<=000)Β β€” the number of question you have in mind. Each of next *q* lines contains an integer *k* (1<=≀<=*k*<=≀<=*n*), followed by *k* integers *l**j* (1<=≀<=*l**j*<=≀<=*n*)Β β€” the number of people who are not coming in this question and their indices. It is guarenteed that *l**j* values are different for a single question. It's guaranteed that the sum of *k* over all question won't exceed 200<=000.
For each question print two integerΒ β€” the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.
[ "6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2\n", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3\n" ]
[ "2 100000\n1 10\n3 1000\n", "0 0\n1 10\n" ]
Consider the first sample: - In the first question participant number 3 is absent so the sequence of bids looks as follows: <li> 1 10 - 2 100 - 1 10 000 - 2 100 000 Participant number 2 wins with the bid 100 000.</li>- In the second question participants 2 and 3 are absent, so the sequence of bids looks: <li> 1 10 - 1 10 000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem). </li>- In the third question participants 1 and 2 are absent and the sequence is: <li> 3 1 000 - 3 1 000 000 The winner is participant 3 with the bid 1 000. </li>
[ { "input": "6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "output": "2 100000\n1 10\n3 1000" }, { "input": "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3", "output": "0 0\n1 10" }, { "input": "1\n1 1\n1\n1 1", "output": "0 0" }, { "input": "2\n1 1\n2 ...
30
0
0
46,829
321
Ciel and Gondolas
[ "data structures", "divide and conquer", "dp" ]
null
null
Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are *n* people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and *n*-th people to refer the last one in the queue. There will be *k* gondolas, and the way we allocate gondolas looks like this: - When the first gondolas come, the *q*1 people in head of the queue go into the gondolas. - Then when the second gondolas come, the *q*2 people in head of the remain queue go into the gondolas.Β Β Β Β ...- The remain *q**k* people go into the last (*k*-th) gondolas. Note that *q*1, *q*2, ..., *q**k* must be positive. You can get from the statement that and *q**i*<=&gt;<=0. You know, people don't want to stay with strangers in the gondolas, so your task is to find an optimal allocation way (that is find an optimal sequence *q*) to make people happy. For every pair of people *i* and *j*, there exists a value *u**ij* denotes a level of unfamiliar. You can assume *u**ij*<==<=*u**ji* for all *i*,<=*j* (1<=≀<=*i*,<=*j*<=≀<=*n*) and *u**ii*<==<=0 for all *i* (1<=≀<=*i*<=≀<=*n*). Then an unfamiliar value of a gondolas is the sum of the levels of unfamiliar between any pair of people that is into the gondolas. A total unfamiliar value is the sum of unfamiliar values for all gondolas. Help Fox Ciel to find the minimal possible total unfamiliar value for some optimal allocation.
The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=4000 and 1<=≀<=*k*<=≀<=*min*(*n*,<=800)) β€” the number of people in the queue and the number of gondolas. Each of the following *n* lines contains *n* integers β€” matrix *u*, (0<=≀<=*u**ij*<=≀<=9, *u**ij*<==<=*u**ji* and *u**ii*<==<=0). Please, use fast input methods (for example, please use BufferedReader instead of Scanner for Java).
Print an integer β€” the minimal possible total unfamiliar value.
[ "5 2\n0 0 1 1 1\n0 0 1 1 1\n1 1 0 0 0\n1 1 0 0 0\n1 1 0 0 0\n", "8 3\n0 1 1 1 1 1 1 1\n1 0 1 1 1 1 1 1\n1 1 0 1 1 1 1 1\n1 1 1 0 1 1 1 1\n1 1 1 1 0 1 1 1\n1 1 1 1 1 0 1 1\n1 1 1 1 1 1 0 1\n1 1 1 1 1 1 1 0\n", "3 2\n0 2 0\n2 0 3\n0 3 0\n" ]
[ "0\n", "7\n", "2\n" ]
In the first example, we can allocate people like this: {1, 2} goes into a gondolas, {3, 4, 5} goes into another gondolas. In the second example, an optimal solution is : {1, 2, 3} | {4, 5, 6} | {7, 8}.
[ { "input": "5 2\n0 0 1 1 1\n0 0 1 1 1\n1 1 0 0 0\n1 1 0 0 0\n1 1 0 0 0", "output": "0" }, { "input": "8 3\n0 1 1 1 1 1 1 1\n1 0 1 1 1 1 1 1\n1 1 0 1 1 1 1 1\n1 1 1 0 1 1 1 1\n1 1 1 1 0 1 1 1\n1 1 1 1 1 0 1 1\n1 1 1 1 1 1 0 1\n1 1 1 1 1 1 1 0", "output": "7" }, { "input": "3 2\n0 2 0\n2 0...
0
0
-1
46,848
13
Letter A
[ "geometry", "implementation" ]
B. Letter A
1
64
Little Petya learns how to write. The teacher gave pupils the task to write the letter *A* on the sheet of paper. It is required to check whether Petya really had written the letter *A*. You are given three segments on the plane. They form the letter *A* if the following conditions hold: - Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments. - The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. - The third segment divides each of the first two segments in proportion not less than 1<=/<=4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1<=/<=4).
The first line contains one integer *t* (1<=≀<=*t*<=≀<=10000) β€” the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers β€” coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.
Output one line for each test case. Print Β«YESΒ» (without quotes), if the segments form the letter *A* and Β«NOΒ» otherwise.
[ "3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1\n" ]
[ "YES\nNO\nYES\n" ]
none
[ { "input": "3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1", "output": "YES\nNO\nYES" } ]
0
0
-1
46,870
316
EKG
[ "dfs and similar", "dp" ]
null
null
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another. (Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left. The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic. Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time... As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
The first line contains two integers *n* (1<=≀<=*n*<=≀<=103) and *x* (1<=≀<=*x*<=≀<=*n*) β€” the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to *n*. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=*n*) β€” the number of the beaver followed by the *i*-th beaver. If *a**i*<==<=0, then the *i*-th beaver doesn't know who is should be in front of him. It is guaranteed that values *a**i* are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue. The input limits for scoring 30 points are (subproblem B1): - It is guaranteed that the number of zero elements *a**i* doesn't exceed 20. The input limits for scoring 100 points are (subproblems B1+B2): - The number of zero elements *a**i* is arbitrary.
Print all possible positions of the Smart Beaver in the line in the increasing order.
[ "6 1\n2 0 4 0 6 0\n", "6 2\n2 3 0 5 6 0\n", "4 1\n0 0 0 0\n", "6 2\n0 0 1 0 4 5\n" ]
[ "2\n4\n6\n", "2\n5\n", "1\n2\n3\n4\n", "1\n3\n4\n6\n" ]
[ { "input": "6 1\n2 0 4 0 6 0", "output": "2\n4\n6" }, { "input": "6 2\n2 3 0 5 6 0", "output": "2\n5" }, { "input": "4 1\n0 0 0 0", "output": "1\n2\n3\n4" }, { "input": "6 2\n0 0 1 0 4 5", "output": "1\n3\n4\n6" }, { "input": "10 7\n10 8 6 5 0 0 0 4 3 9", "out...
500
512,000
0
46,871
467
George and Job
[ "dp", "implementation" ]
null
null
The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work. Given a sequence of *n* integers *p*1,<=*p*2,<=...,<=*p**n*. You are to choose *k* pairs of integers: in such a way that the value of sum is maximal possible. Help George to cope with the task.
The first line contains three integers *n*, *m* and *k* (1<=≀<=(*m*<=Γ—<=*k*)<=≀<=*n*<=≀<=5000). The second line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* (0<=≀<=*p**i*<=≀<=109).
Print an integer in a single line β€” the maximum possible value of sum.
[ "5 2 1\n1 2 3 4 5\n", "7 1 3\n2 10 7 18 5 33 0\n" ]
[ "9\n", "61\n" ]
none
[ { "input": "5 2 1\n1 2 3 4 5", "output": "9" }, { "input": "7 1 3\n2 10 7 18 5 33 0", "output": "61" }, { "input": "13 8 1\n73 7 47 91 54 74 99 11 67 35 84 18 19", "output": "515" }, { "input": "8 3 1\n8 46 37 81 81 57 11 2", "output": "219" }, { "input": "20 5 3\...
124
9,932,800
-1
46,895
750
New Year and Snowy Grid
[ "dfs and similar", "dsu", "graphs", "interactive" ]
null
null
Pay attention to the output section below, where you will see the information about flushing the output. Bearland is a grid with *h* rows and *w* columns. Rows are numbered 1 through *h* from top to bottom. Columns are numbered 1 through *w* from left to right. Every cell is either allowed (denoted by '.' in the input) or permanently blocked (denoted by '#'). Bearland is a cold land, where heavy snow often makes travelling harder. Every day a few allowed cells are temporarily blocked by snow. Note, that this block works only on this particular day and next day any of these cells might be allowed again (unless there is another temporarily block). It's possible to move directly between two cells only if they share a side and none of them is permanently or temporarily blocked. Limak is a little polar bear who lives in Bearland. His house is at the top left cell, while his school is at the bottom right cell. Every day Limak should first go from his house to the school and then return back to his house. Since he gets bored easily, he doesn't want to visit the same cell twice on one day, except for the cell with his house, where he starts and ends. If Limak can reach a school and return home avoiding revisiting cells, he calls a day interesting. There are *q* days you must process, one after another. For each of these days you should check if it's interesting and print "YES" or "NO" on a separate line. In order to be able to read the description of the next day you should print the answer for the previous one and flush the output. It's guaranteed that a day with no cells temporarily blocked by snow would be interesting. It's also guaranteed that cells with Limak's house and school are never blocked (neither permanently or temporarily).
The first line of the input contains three integers *h*, *w* and *q* (2<=≀<=*h*,<=*w*<=≀<=1000, 1<=≀<=*q*<=≀<=10<=000)Β β€” the height and the width of the grid, and the number of days, respectively. Next *h* lines describe which cells are allowed and which permanently blocked. The *i*-th line contains a string of length *w*, describing the *i*-th row. Every character is either '.' (denoting an allowed cell) or '#' (denoting a permanently blocked cell). It's guaranteed that a day with no cells temporarily blocked by snow would be interesting. Then, the description of *q* days is given. The description of the *i*-th day starts with a line containing a single integer *k**i* (1<=≀<=*k**i*<=≀<=10)Β β€” the number of cells that are temporarily blocked by snow on that day. Each of next *k**i* lines contains two integers *r**i*,<=*j* and *c**i*,<=*j* (1<=≀<=*r**i*,<=*j*<=≀<=*h*, 1<=≀<=*c**i*,<=*j*<=≀<=*w*), representing a cell at the intersection of the row *r**i*,<=*j* and the column *c**i*,<=*j*. The given *k**i* cells are distinct and none of them is permanently blocked. Also, none of them contains Limak's house or school.
For each of *q* days print "YES" if that day is interesting, and otherwise print "NO", both without the quotes. After printing an answer, you have to both print the end-of-line character and flush the output. Then you can proceed to the next day. You can get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output. To flush you can use (just after printing a YES/NO and end-of-line): - fflush(stdout) in C++; - System.out.flush() in Java; - stdout.flush() in Python; - flush(output) in Pascal; - See the documentation for other languages.
[ "3 5 4\n.....\n.....\n.#...\n1\n1 4\n1\n1 5\n2\n2 4\n3 1\n2\n1 5\n3 3\n", "9 31 5\n...............................\n...............................\n.###.###.#.###...###.###.#.###.\n...#.#.#.#.#.......#.#.#.#...#.\n.###.#.#.#.###...###.#.#.#...#.\n.#...#.#.#.#.#...#...#.#.#...#.\n.###.###.#.###...###.###.#...#.\n...
[ "NO\nYES\nYES\nNO\n", "NO\nYES\nYES\nYES\nNO\n" ]
In the first sample, there are 4 days. Drawings below show how Limak could go to school and return to his home in the second and the third day (on the left and on the right respectively). A permanently blocked cell is painted red, while cells temporarily blocked by snow are painted orange. Black and green arrows should Limak's way to the school and back to the house respectively. For the second sample, below you can see how the grid looks like on each day, where '#' denotes a cell that is blocked, either temporarily or permanently.
[]
15
0
0
46,917
732
Sockets
[ "greedy", "sortings" ]
null
null
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point β€” the organization of electricity supplement for all the participants workstations. There are *n* computers for participants, the *i*-th of which has power equal to positive integer *p**i*. At the same time there are *m* sockets available, the *j*-th of which has power euqal to positive integer *s**j*. It is possible to connect the *i*-th computer to the *j*-th socket if and only if their powers are the same: *p**i*<==<=*s**j*. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adaptersΒ β€” power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power *x*, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and . Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket. The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers *c* at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters *u* to connect *c* computers. Help organizers calculate the maximum number of connected computers *c* and the minimum number of adapters *u* needed for this. The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
The first line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=200<=000)Β β€” the number of computers and the number of sockets. The second line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≀<=*p**i*<=≀<=109)Β β€” the powers of the computers. The third line contains *m* integers *s*1,<=*s*2,<=...,<=*s**m* (1<=≀<=*s**i*<=≀<=109)Β β€” the power of the sockets.
In the first line print two numbers *c* and *u*Β β€” the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect *c* computers. In the second line print *m* integers *a*1,<=*a*2,<=...,<=*a**m* (0<=≀<=*a**i*<=≀<=109), where *a**i* equals the number of adapters orginizers need to plug into the *i*-th socket. The sum of all *a**i* should be equal to *u*. In third line print *n* integers *b*1,<=*b*2,<=...,<=*b**n* (0<=≀<=*b**i*<=≀<=*m*), where the *b**j*-th equals the number of the socket which the *j*-th computer should be connected to. *b**j*<==<=0 means that the *j*-th computer should not be connected to any socket. All *b**j* that are different from 0 should be distinct. The power of the *j*-th computer should be equal to the power of the socket *b**j* after plugging in *a**b**j* adapters. The number of non-zero *b**j* should be equal to *c*. If there are multiple answers, print any of them.
[ "2 2\n1 1\n2 2\n", "2 1\n2 100\n99\n" ]
[ "2 2\n1 1\n1 2\n", "1 6\n6\n1 0\n" ]
none
[ { "input": "2 2\n1 1\n2 2", "output": "2 2\n1 1\n1 2" }, { "input": "2 1\n2 100\n99", "output": "1 6\n6\n1 0" }, { "input": "1 1\n1\n1", "output": "1 0\n0\n1" }, { "input": "2 1\n2 570129\n753393670", "output": "1 29\n29\n1 0" }, { "input": "1 2\n258\n270411237 42...
343
57,958,400
0
47,070
216
Martian Luck
[ "math", "number theory" ]
null
null
You know that the Martians use a number system with base *k*. Digit *b* (0<=≀<=*b*<=&lt;<=*k*) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year *b* (by Martian chronology). A digital root *d*(*x*) of number *x* is a number that consists of a single digit, resulting after cascading summing of all digits of number *x*. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number. For example, *d*(35047)<==<=*d*((3<=+<=5<=+<=0<=+<=4)7)<==<=*d*(157)<==<=*d*((1<=+<=5)7)<==<=*d*(67)<==<=67. In this sample the calculations are performed in the 7-base notation. If a number's digital root equals *b*, the Martians also call this number lucky. You have string *s*, which consists of *n* digits in the *k*-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers. Note that substring *s*[*i*... *j*] of the string *s*<==<=*a*1*a*2... *a**n* (1<=≀<=*i*<=≀<=*j*<=≀<=*n*) is the string *a**i**a**i*<=+<=1... *a**j*. Two substrings *s*[*i*1... *j*1] and *s*[*i*2... *j*2] of the string *s* are different if either *i*1<=β‰ <=*i*2 or *j*1<=β‰ <=*j*2.
The first line contains three integers *k*, *b* and *n* (2<=≀<=*k*<=≀<=109, 0<=≀<=*b*<=&lt;<=*k*, 1<=≀<=*n*<=≀<=105). The second line contains string *s* as a sequence of *n* integers, representing digits in the *k*-base notation: the *i*-th integer equals *a**i* (0<=≀<=*a**i*<=&lt;<=*k*) β€” the *i*-th digit of string *s*. The numbers in the lines are space-separated.
Print a single integer β€” the number of substrings that are lucky numbers. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "10 5 6\n3 2 0 5 6 1\n", "7 6 4\n3 5 0 4\n", "257 0 3\n0 0 256\n" ]
[ "5", "1", "3" ]
In the first sample the following substrings have the sought digital root: *s*[1... 2] = "3 2", *s*[1... 3] = "3 2 0", *s*[3... 4] = "0 5", *s*[4... 4] = "5" and *s*[2... 6] = "2 0 5 6 1".
[ { "input": "10 5 6\n3 2 0 5 6 1", "output": "5" }, { "input": "7 6 4\n3 5 0 4", "output": "1" }, { "input": "257 0 3\n0 0 256", "output": "3" }, { "input": "2 1 1\n0", "output": "0" }, { "input": "2 0 20\n1 1 1 0 1 1 1 1 0 0 0 0 1 0 0 0 0 1 0 1", "output": "22...
124
0
0
47,122
915
Physical Education Lessons
[ "data structures", "implementation", "sortings" ]
null
null
This year Alex has finished school, and now he is a first-year student of Berland State University. For him it was a total surprise that even though he studies programming, he still has to attend physical education lessons. The end of the term is very soon, but, unfortunately, Alex still hasn't attended a single lesson! Since Alex doesn't want to get expelled, he wants to know the number of working days left until the end of the term, so he can attend physical education lessons during these days. But in BSU calculating the number of working days is a complicated matter: There are *n* days left before the end of the term (numbered from 1 to *n*), and initially all of them are working days. Then the university staff sequentially publishes *q* orders, one after another. Each order is characterised by three numbers *l*, *r* and *k*: - If *k*<==<=1, then all days from *l* to *r* (inclusive) become non-working days. If some of these days are made working days by some previous order, then these days still become non-working days; - If *k*<==<=2, then all days from *l* to *r* (inclusive) become working days. If some of these days are made non-working days by some previous order, then these days still become working days. Help Alex to determine the number of working days left after each order!
The first line contains one integer *n*, and the second line β€” one integer *q* (1<=≀<=*n*<=≀<=109, 1<=≀<=*q*<=≀<=3Β·105) β€” the number of days left before the end of the term, and the number of orders, respectively. Then *q* lines follow, *i*-th line containing three integers *l**i*, *r**i* and *k**i* representing *i*-th order (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=*n*, 1<=≀<=*k**i*<=≀<=2).
Print *q* integers. *i*-th of them must be equal to the number of working days left until the end of the term after the first *i* orders are published.
[ "4\n6\n1 2 1\n3 4 1\n2 3 2\n1 3 2\n2 4 1\n1 4 2\n" ]
[ "2\n0\n2\n3\n1\n4\n" ]
none
[ { "input": "4\n6\n1 2 1\n3 4 1\n2 3 2\n1 3 2\n2 4 1\n1 4 2", "output": "2\n0\n2\n3\n1\n4" }, { "input": "3\n8\n2 2 1\n3 3 2\n1 1 1\n1 3 2\n2 3 2\n3 3 1\n1 2 1\n2 2 2", "output": "2\n2\n1\n3\n3\n2\n0\n1" }, { "input": "7\n10\n5 7 1\n5 6 2\n7 7 2\n6 7 2\n5 5 1\n3 6 2\n1 3 2\n5 6 1\n1 3 1\n...
1,000
77,721,600
0
47,143
0
none
[ "none" ]
null
null
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide. He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
The first line of the input data contains an integer *n* (1<=≀<=*n*<=≀<=105). The second line contains an array of original integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≀<=*a**i*<=≀<=109).
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
[ "4\n2 1 1 4\n", "5\n-2 -2 -2 0 1\n" ]
[ "5\n", "8\n" ]
Notes to sample tests: Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end. In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3]. In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
[ { "input": "4\n2 1 1 4", "output": "5" }, { "input": "5\n-2 -2 -2 0 1", "output": "8" }, { "input": "1\n10", "output": "1" }, { "input": "2\n5 6", "output": "2" }, { "input": "5\n5 5 4 5 5", "output": "7" }, { "input": "8\n1 2 0 0 0 0 3 3", "output...
154
0
0
47,261
762
Radio stations
[ "binary search", "data structures" ]
null
null
In the lattice points of the coordinate line there are *n* radio stations, the *i*-th of which is described by three integers: - *x**i* β€” the coordinate of the *i*-th station on the line, - *r**i* β€” the broadcasting range of the *i*-th station, - *f**i* β€” the broadcasting frequency of the *i*-th station. We will say that two radio stations with numbers *i* and *j* reach each other, if the broadcasting range of each of them is more or equal to the distance between them. In other words *min*(*r**i*,<=*r**j*)<=β‰₯<=|*x**i*<=-<=*x**j*|. Let's call a pair of radio stations (*i*,<=*j*) bad if *i*<=&lt;<=*j*, stations *i* and *j* reach each other and they are close in frequency, that is, |*f**i*<=-<=*f**j*|<=≀<=*k*. Find the number of bad pairs of radio stations.
The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=105, 0<=≀<=*k*<=≀<=10) β€” the number of radio stations and the maximum difference in the frequencies for the pair of stations that reach each other to be considered bad. In the next *n* lines follow the descriptions of radio stations. Each line contains three integers *x**i*, *r**i* and *f**i* (1<=≀<=*x**i*,<=*r**i*<=≀<=109, 1<=≀<=*f**i*<=≀<=104) β€” the coordinate of the *i*-th radio station, it's broadcasting range and it's broadcasting frequency. No two radio stations will share a coordinate.
Output the number of bad pairs of radio stations.
[ "3 2\n1 3 10\n3 2 5\n4 10 8\n", "3 3\n1 3 10\n3 2 5\n4 10 8\n", "5 1\n1 3 2\n2 2 4\n3 2 1\n4 2 1\n5 3 3\n", "5 1\n1 5 2\n2 5 4\n3 5 1\n4 5 1\n5 5 3\n" ]
[ "1\n", "2\n", "2\n", "5\n" ]
none
[ { "input": "3 2\n1 3 10\n3 2 5\n4 10 8", "output": "1" }, { "input": "3 3\n1 3 10\n3 2 5\n4 10 8", "output": "2" }, { "input": "5 1\n1 3 2\n2 2 4\n3 2 1\n4 2 1\n5 3 3", "output": "2" }, { "input": "5 1\n1 5 2\n2 5 4\n3 5 1\n4 5 1\n5 5 3", "output": "5" }, { "input...
2,000
5,529,600
0
47,429
875
National Property
[ "2-sat", "dfs and similar", "graphs", "implementation" ]
null
null
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library. Some long and uninteresting story was removed... The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter *x* is denoted by *x*'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2<=&lt;<=3, 2'<=&lt;<=3', 3'<=&lt;<=2. A word *x*1,<=*x*2,<=...,<=*x**a* is not lexicographically greater than *y*1,<=*y*2,<=...,<=*y**b* if one of the two following conditions holds: - *a*<=≀<=*b* and *x*1<==<=*y*1,<=...,<=*x**a*<==<=*y**a*, i.e. the first word is the prefix of the second word; - there is a position 1<=≀<=*j*<=≀<=*min*(*a*,<=*b*), such that *x*1<==<=*y*1,<=...,<=*x**j*<=-<=1<==<=*y**j*<=-<=1 and *x**j*<=&lt;<=*y**j*, i.e. at the first position where the words differ the first word has a smaller letter than the second word has. For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence. Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet. Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible. Note that some words can be equal.
The first line contains two integers *n* and *m* (2<=≀<=*n*<=≀<=100<=000, 1<=≀<=*m*<=≀<=100<=000)Β β€” the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to *m*. Each of the next *n* lines contains a description of one word in format *l**i*,<=*s**i*,<=1,<=*s**i*,<=2,<=...,<=*s**i*,<=*l**i* (1<=≀<=*l**i*<=≀<=100<=000, 1<=≀<=*s**i*,<=*j*<=≀<=*m*), where *l**i* is the length of the word, and *s**i*,<=*j* is the sequence of letters in the word. The words are given in the order Denis has them in the sequence. It is guaranteed that the total length of all words is not greater than 100<=000.
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes). If the required is possible, in the second line print *k*Β β€” the number of letters Denis has to capitalize (make large), and in the third line print *k* distinct integersΒ β€” these letters. Note that you don't need to minimize the value *k*. You can print the letters in any order. If there are multiple answers, print any of them.
[ "4 3\n1 2\n1 1\n3 1 3 2\n2 1 1\n", "6 5\n2 1 2\n2 1 2\n3 1 2 3\n2 1 5\n2 4 4\n2 4 4\n", "4 3\n4 3 2 2 1\n3 1 1 3\n3 2 3 3\n2 3 1\n" ]
[ "Yes\n2\n2 3 ", "Yes\n0\n", "No\n" ]
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following: - 2' - 1 - 1 3' 2' - 1 1 The condition 2' &lt; 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' &lt; 1, then the third word is not lexicographically larger than the fourth word. In the second example the words are in lexicographical order from the beginning, so Denis can do nothing. In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
[ { "input": "4 3\n1 2\n1 1\n3 1 3 2\n2 1 1", "output": "Yes\n2\n2 3 " }, { "input": "6 5\n2 1 2\n2 1 2\n3 1 2 3\n2 1 5\n2 4 4\n2 4 4", "output": "Yes\n0" }, { "input": "4 3\n4 3 2 2 1\n3 1 1 3\n3 2 3 3\n2 3 1", "output": "No" }, { "input": "4 4\n3 3 4 1\n4 3 4 2 2\n4 2 1 2 3\n...
30
0
0
47,485
228
Two Tables
[ "brute force", "implementation" ]
null
null
You've got two rectangular tables with sizes *n**a*<=Γ—<=*m**a* and *n**b*<=Γ—<=*m**b* cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the *i*-th row and the *j*-th column, as *a**i*,<=*j*; we will define the element of the second table, located at the intersection of the *i*-th row and the *j*-th column, as *b**i*,<=*j*. We will call the pair of integers (*x*,<=*y*) a shift of the second table relative to the first one. We'll call the overlap factor of the shift (*x*,<=*y*) value: where the variables *i*,<=*j* take only such values, in which the expression *a**i*,<=*j*Β·*b**i*<=+<=*x*,<=*j*<=+<=*y* makes sense. More formally, inequalities 1<=≀<=*i*<=≀<=*n**a*,<=1<=≀<=*j*<=≀<=*m**a*,<=1<=≀<=*i*<=+<=*x*<=≀<=*n**b*,<=1<=≀<=*j*<=+<=*y*<=≀<=*m**b* must hold. If there are no values of variables *i*,<=*j*, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts.
The first line contains two space-separated integers *n**a*,<=*m**a* (1<=≀<=*n**a*,<=*m**a*<=≀<=50) β€” the number of rows and columns in the first table. Then *n**a* lines contain *m**a* characters each β€” the elements of the first table. Each character is either a "0", or a "1". The next line contains two space-separated integers *n**b*,<=*m**b* (1<=≀<=*n**b*,<=*m**b*<=≀<=50) β€” the number of rows and columns in the second table. Then follow the elements of the second table in the format, similar to the first table. It is guaranteed that the first table has at least one number "1". It is guaranteed that the second table has at least one number "1".
Print two space-separated integers *x*,<=*y* (|*x*|,<=|*y*|<=≀<=109) β€” a shift with maximum overlap factor. If there are multiple solutions, print any of them.
[ "3 2\n01\n10\n00\n2 3\n001\n111\n", "3 3\n000\n010\n000\n1 1\n1\n" ]
[ "0 1\n", "-1 -1\n" ]
none
[ { "input": "3 2\n01\n10\n00\n2 3\n001\n111", "output": "0 1" }, { "input": "3 3\n000\n010\n000\n1 1\n1", "output": "-1 -1" }, { "input": "2 4\n1010\n0011\n5 5\n01100\n01110\n00111\n00110\n00110", "output": "1 1" }, { "input": "3 1\n0\n1\n0\n2 2\n11\n00", "output": "-1 1" ...
654
6,656,000
3
47,628
501
Misha and Forest
[ "constructive algorithms", "data structures", "greedy", "sortings", "trees" ]
null
null
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of *n* vertices. For each vertex *v* from 0 to *n*<=-<=1 he wrote down two integers, *degree**v* and *s**v*, were the first integer is the number of vertices adjacent to vertex *v*, and the second integer is the XOR sum of the numbers of vertices adjacent to *v* (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values *degree**v* and *s**v* left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
The first line contains integer *n* (1<=≀<=*n*<=≀<=216), the number of vertices in the graph. The *i*-th of the next lines contains numbers *degree**i* and *s**i* (0<=≀<=*degree**i*<=≀<=*n*<=-<=1, 0<=≀<=*s**i*<=&lt;<=216), separated by a space.
In the first line print number *m*, the number of edges of the graph. Next print *m* lines, each containing two distinct numbers, *a* and *b* (0<=≀<=*a*<=≀<=*n*<=-<=1, 0<=≀<=*b*<=≀<=*n*<=-<=1), corresponding to edge (*a*,<=*b*). Edges can be printed in any order; vertices of the edge can also be printed in any order.
[ "3\n2 3\n1 0\n1 0\n", "2\n1 1\n1 0\n" ]
[ "2\n1 0\n2 0\n", "1\n0 1\n" ]
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β€” as "xor".
[ { "input": "3\n2 3\n1 0\n1 0", "output": "2\n1 0\n2 0" }, { "input": "2\n1 1\n1 0", "output": "1\n0 1" }, { "input": "10\n3 13\n2 6\n1 5\n3 5\n1 3\n2 2\n2 6\n1 6\n1 3\n2 3", "output": "9\n2 5\n4 3\n7 6\n8 3\n5 0\n6 1\n3 9\n1 0\n9 0" }, { "input": "10\n1 2\n1 7\n1 0\n1 8\n0 0\...
374
11,878,400
3
47,629
580
Kefa and Dishes
[ "bitmasks", "dp" ]
null
null
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were *n* dishes. Kefa knows that he needs exactly *m* dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the *i*-th dish gives him *a**i* units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself *k* rules of eating food of the following type β€” if he eats dish *x* exactly before dish *y* (there should be no other dishes between *x* and *y*), then his satisfaction level raises by *c*. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!
The first line of the input contains three space-separated numbers, *n*, *m* and *k* (1<=≀<=*m*<=≀<=*n*<=≀<=18, 0<=≀<=*k*<=≀<=*n*<=*<=(*n*<=-<=1)) β€” the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains *n* space-separated numbers *a**i*, (0<=≀<=*a**i*<=≀<=109) β€” the satisfaction he gets from the *i*-th dish. Next *k* lines contain the rules. The *i*-th rule is described by the three numbers *x**i*, *y**i* and *c**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*, 0<=≀<=*c**i*<=≀<=109). That means that if you eat dish *x**i* right before dish *y**i*, then the Kefa's satisfaction increases by *c**i*. It is guaranteed that there are no such pairs of indexes *i* and *j* (1<=≀<=*i*<=&lt;<=*j*<=≀<=*k*), that *x**i*<==<=*x**j* and *y**i*<==<=*y**j*.
In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.
[ "2 2 1\n1 1\n2 1 1\n", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2\n" ]
[ "3\n", "12\n" ]
In the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule. In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.
[ { "input": "2 2 1\n1 1\n2 1 1", "output": "3" }, { "input": "4 3 2\n1 2 3 4\n2 1 5\n3 4 2", "output": "12" }, { "input": "1 1 0\n1000000000", "output": "1000000000" }, { "input": "4 2 1\n100 1 2 200\n2 3 400", "output": "403" }, { "input": "7 4 3\n2 6 13 5 7 1 9\n...
2,000
232,448,000
0
47,697
366
Dima and Trap Graph
[ "binary search", "data structures", "dfs and similar", "dsu", "shortest paths", "two pointers" ]
null
null
Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal... Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate interested and kicked him into the first node. A trap graph is an undirected graph consisting of *n* nodes and *m* edges. For edge number *k*, Dima denoted a range of integers from *l**k* to *r**k* (*l**k*<=≀<=*r**k*). In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it *x*), then Seryozha must go some way from the starting node with number 1 to the final node with number *n*. At that, Seryozha can go along edge *k* only if *l**k*<=≀<=*x*<=≀<=*r**k*. Seryozha is a mathematician. He defined the loyalty of some path from the 1-st node to the *n*-th one as the number of integers *x*, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible!
The first line of the input contains two integers *n* and *m* (2<=≀<=*n*<=≀<=103,<=0<=≀<=*m*<=≀<=3Β·103). Then follow *m* lines describing the edges. Each line contains four integers *a**k*, *b**k*, *l**k* and *r**k* (1<=≀<=*a**k*,<=*b**k*<=≀<=*n*,<=1<=≀<=*l**k*<=≀<=*r**k*<=≀<=106). The numbers mean that in the trap graph the *k*-th edge connects nodes *a**k* and *b**k*, this edge corresponds to the range of integers from *l**k* to *r**k*. Note that the given graph can have loops and multiple edges.
In a single line of the output print an integer β€” the maximum loyalty among all paths from the first node to the *n*-th one. If such paths do not exist or the maximum loyalty equals 0, print in a single line "Nice work, Dima!" without the quotes.
[ "4 4\n1 2 1 10\n2 4 3 5\n1 3 1 5\n2 4 2 7\n", "5 6\n1 2 1 10\n2 5 11 20\n1 4 2 5\n1 3 10 11\n3 4 12 10000\n4 5 6 6\n" ]
[ "6\n", "Nice work, Dima!\n" ]
Explanation of the first example. Overall, we have 2 ways to get from node 1 to node 4: first you must go along the edge 1-2 with range [1-10], then along one of the two edges 2-4. One of them contains range [3-5], that is, we can pass through with numbers 3, 4, 5. So the loyalty of such path is 3. If we go along edge 2-4 with range [2-7], then we can pass through with numbers 2, 3, 4, 5, 6, 7. The loyalty is 6. That is the answer. The edge 1-2 have no influence on the answer because its range includes both ranges of the following edges.
[ { "input": "4 4\n1 2 1 10\n2 4 3 5\n1 3 1 5\n2 4 2 7", "output": "6" }, { "input": "5 6\n1 2 1 10\n2 5 11 20\n1 4 2 5\n1 3 10 11\n3 4 12 10000\n4 5 6 6", "output": "Nice work, Dima!" }, { "input": "6 6\n1 2 1 10\n2 3 1 10\n3 6 1 1\n1 4 1 4\n4 5 1 3\n5 6 1 3", "output": "3" }, { ...
62
1,228,800
0
47,707
0
none
[ "none" ]
null
null
Hamed has recently found a string *t* and suddenly became quite fond of it. He spent several days trying to find all occurrences of *t* in other strings he had. Finally he became tired and started thinking about the following problem. Given a string *s* how many ways are there to extract *k*<=β‰₯<=1 non-overlapping substrings from it such that each of them contains string *t* as a substring? More formally, you need to calculate the number of ways to choose two sequences *a*1,<=*a*2,<=...,<=*a**k* and *b*1,<=*b*2,<=...,<=*b**k* satisfying the following requirements: - *k*<=β‰₯<=1 - - - - Β Β *t* is a substring of string *s**a**i**s**a**i*<=+<=1... *s**b**i* (string *s* is considered as 1-indexed). As the number of ways can be rather large print it modulo 109<=+<=7.
Input consists of two lines containing strings *s* and *t* (1<=≀<=|*s*|,<=|*t*|<=≀<=105). Each string consists of lowercase Latin letters.
Print the answer in a single line.
[ "ababa\naba\n", "welcometoroundtwohundredandeightytwo\nd\n", "ddd\nd\n" ]
[ "5\n", "274201\n", "12\n" ]
none
[ { "input": "ababa\naba", "output": "5" }, { "input": "welcometoroundtwohundredandeightytwo\nd", "output": "274201" }, { "input": "ddd\nd", "output": "12" }, { "input": "vnssnssnssnssnssnssnssnssnssnssnssnssnssnssnssnssn\nnssnssns", "output": "943392" }, { "input":...
312
7,475,200
3
47,743
935
Fafa and Ancient Alphabet
[ "math", "probabilities" ]
null
null
Ancient Egyptians are known to have used a large set of symbols to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words *S*1 and *S*2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set have equal probability for being in the position of any erased symbol. Fifa challenged Fafa to calculate the probability that *S*1 is lexicographically greater than *S*2. Can you help Fafa with this task? You know that , i.Β e. there were *m* distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to *m* in alphabet order. A word *x* is lexicographically greater than a word *y* of the same length, if the words are same up to some position, and then the word *x* has a larger character, than the word *y*. We can prove that the probability equals to some fraction , where *P* and *Q* are coprime integers, and . Print as the answer the value , i.Β e. such a non-negative integer less than 109<=+<=7, such that , where means that *a* and *b* give the same remainders when divided by *m*.
The first line contains two integers *n* and *m* (1<=≀<=*n*,<=<=*m*<=≀<=105) β€” the length of each of the two words and the size of the alphabet , respectively. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=*m*) β€” the symbols of *S*1. If *a**i*<==<=0, then the symbol at position *i* was erased. The third line contains *n* integers representing *S*2 with the same format as *S*1.
Print the value , where *P* and *Q* are coprime and is the answer to the problem.
[ "1 2\n0\n1\n", "1 2\n1\n0\n", "7 26\n0 15 12 9 13 0 14\n11 1 0 13 15 12 0\n" ]
[ "500000004\n", "0\n", "230769233\n" ]
In the first sample, the first word can be converted into (1) or (2). The second option is the only one that will make it lexicographically larger than the second word. So, the answer to the problem will be <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a762254bc6d3a2cc6ae07485c1de945962e7e524.png" style="max-width: 100.0%;max-height: 100.0%;"/>, that is 500000004, because <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/cbff288b4c38669aa9b8013ee25b8dde80420841.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second example, there is no replacement for the zero in the second word that will make the first one lexicographically larger. So, the answer to the problem is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a468ab19fec68399601f37993805846b7dd342ad.png" style="max-width: 100.0%;max-height: 100.0%;"/>, that is 0.
[ { "input": "1 2\n0\n1", "output": "500000004" }, { "input": "1 2\n1\n0", "output": "0" }, { "input": "7 26\n0 15 12 9 13 0 14\n11 1 0 13 15 12 0", "output": "230769233" }, { "input": "6 26\n14 5 19 18 9 14\n0 0 0 0 0 0", "output": "182369325" }, { "input": "4 26\n...
451
9,011,200
3
47,750
0
none
[ "none" ]
null
null
Tree is a connected acyclic graph. Suppose you are given a tree consisting of *n* vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed . You are given a tree of size *n* and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.
The first line of the input contains an integer *n* (2<=≀<=*n*<=≀<=400<=000)Β β€” the number of vertices in the tree. Each of the next *n*<=-<=1 lines contains a pair of vertex indices *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*)Β β€” endpoints of the corresponding edge.
Print *n* integers. The *i*-th of them should be equal to 1 if the *i*-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.
[ "3\n1 2\n2 3\n", "5\n1 2\n1 3\n1 4\n1 5\n" ]
[ "1 1 1 \n", "1 0 0 0 0 \n" ]
In the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2, 3) with the edge (1, 3).
[]
46
0
0
47,768
0
none
[ "none" ]
null
null
The game of bingo is played on a 5<=Γ—<=5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an *n*<=Γ—<=*n* grid with distinct numbers between 1 and *m* (*m*<=β‰₯<=*n*2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then *k* distinct numbers between 1 and *m* will be called at random (called uniformly among all available sets of *k* numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns). Determine the expected value of the score. The expected score may be very large. If the expected score is larger than 1099, print 1099 instead (for example as "1e99" without the quotes).
Input will consist of three integers *n*, *m*, *k* (1<=≀<=*n*<=≀<=300;Β *n*2<=≀<=*m*<=≀<=100000;Β *n*<=≀<=*k*<=≀<=*m*).
Print the smaller of 1099 and the expected score. Your answer must be correct within an absolute or relative error of 10<=-<=9.
[ "1 2 1\n", "2 4 3\n", "7 59164 40872\n" ]
[ "2.5\n", "4\n", "3.1415926538\n" ]
none
[]
46
0
0
47,835
217
Blackboard Fibonacci
[ "brute force", "math" ]
null
null
Fibonacci numbers are the sequence of integers: *f*0<==<=0, *f*1<==<=1, *f*2<==<=1, *f*3<==<=2, *f*4<==<=3, *f*5<==<=5, ..., *f**n*<==<=*f**n*<=-<=2<=+<=*f**n*<=-<=1. So every next number is the sum of the previous two. Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations: - operation "T": replace the top number with the sum of both numbers; - operation "B": replace the bottom number with the sum of both numbers. If he performs *n* operations, starting with "T" and then choosing operations alternately (so that the sequence of operations looks like "TBTBTBTB..."), the last number written will be equal to *f**n*<=+<=1. Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute *f*7, then he would want to do *n*<==<=6 operations: "TBTBTB". If he instead performs the sequence of operations "TTTBBT", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations (Β«TTΒ» or Β«BBΒ»). You are given the number *n* of operations that Bajtek has made in an attempt to compute *f**n*<=+<=1 and the number *r* that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of *n* operations resulting in *r* with that number of mistakes. Assume that Bajtek always correctly starts with operation "T".
The first line contains the integers *n* and *r* (1<=≀<=*n*,<=*r*<=≀<=106).
The first line of the output should contain one number β€” the minimum possible number of mistakes made by Bajtek. The second line should contain *n* characters, starting with "T", describing one possible sequence of operations with that number of mistakes. Each character must be either "T" or "B". If the required sequence doesn't exist, output "IMPOSSIBLE" (without quotes).
[ "6 10\n", "4 5\n", "2 1\n" ]
[ "2\nTBBTTB\n", "0\nTBTB\n", "IMPOSSIBLE\n" ]
none
[ { "input": "6 10", "output": "2\nTBBTTB" }, { "input": "4 5", "output": "0\nTBTB" }, { "input": "2 1", "output": "IMPOSSIBLE" }, { "input": "15 682", "output": "IMPOSSIBLE" }, { "input": "1145 997855", "output": "IMPOSSIBLE" }, { "input": "16 458", ...
46
0
0
47,881
515
Drazil and Park
[ "data structures" ]
null
null
Drazil is a monkey. He lives in a circular park. There are *n* trees around the park. The distance between the *i*-th tree and (*i*<=+<=1)-st trees is *d**i*, the distance between the *n*-th tree and the first tree is *d**n*. The height of the *i*-th tree is *h**i*. Drazil starts each day with the morning run. The morning run consists of the following steps: - Drazil chooses two different trees - He starts with climbing up the first tree - Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it - Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees. If the two trees Drazil chooses are *x*-th and *y*-th, we can estimate the energy the morning run takes to him as 2(*h**x*<=+<=*h**y*)<=+<=*dist*(*x*,<=*y*). Since there are children on exactly one of two arcs connecting *x* and *y*, the distance *dist*(*x*,<=*y*) between trees *x* and *y* is uniquely defined. Now, you know that on the *i*-th day children play between *a**i*-th tree and *b**i*-th tree. More formally, if *a**i*<=≀<=*b**i*, children play around the trees with indices from range [*a**i*,<=*b**i*], otherwise they play around the trees with indices from . Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.
The first line contains two integer *n* and *m* (3<=≀<=*n*<=≀<=105, 1<=≀<=*m*<=≀<=105), denoting number of trees and number of days, respectively. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≀<=*d**i*<=≀<=109), the distances between consecutive trees. The third line contains *n* integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≀<=*h**i*<=≀<=109), the heights of trees. Each of following *m* lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children.
For each day print the answer in a separate line.
[ "5 3\n2 2 2 2 2\n3 5 2 1 4\n1 3\n2 2\n4 5\n", "3 3\n5 1 4\n5 1 4\n3 3\n2 2\n1 1\n" ]
[ "12\n16\n18\n", "17\n22\n11\n" ]
none
[ { "input": "5 3\n2 2 2 2 2\n3 5 2 1 4\n1 3\n2 2\n4 5", "output": "12\n16\n18" }, { "input": "3 3\n5 1 4\n5 1 4\n3 3\n2 2\n1 1", "output": "17\n22\n11" }, { "input": "10 10\n8477 33103 38654 6582 27496 1106 15985 3644 29818 8849\n88745 72099 87767 85285 73517 94562 87214 63194 83791 77619...
46
0
0
47,886
926
Endless Roses Most Beautiful
[]
null
null
Arkady decided to buy roses for his girlfriend. A flower shop has white, orange and red roses, and the total amount of them is *n*. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color. Arkady wants to buy exactly *k* roses. For each rose in the shop he knows its beauty and color: the beauty of the *i*-th rose is *b**i*, and its color is *c**i* ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose). Compute the maximum possible total beauty of a bouquet of *k* roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
The first line contains two integers *n* and *k* (1<=≀<=*k*<=≀<=*n*<=≀<=200<=000) β€” the number of roses in the show and the number of roses Arkady wants to buy. The second line contains a sequence of integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≀<=*b**i*<=≀<=10<=000), where *b**i* equals the beauty of the *i*-th rose. The third line contains a string *c* of length *n*, consisting of uppercase English letters 'W', 'O' and 'R', where *c**i* denotes the color of the *i*-th rose: 'W' denotes white, 'O' Β β€” orange, 'R' β€” red.
Print the maximum possible total beauty of a bouquet of *k* roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
[ "5 3\n4 3 4 1 6\nRROWW\n", "5 2\n10 20 14 20 11\nRRRRR\n", "11 5\n5 6 3 2 3 4 7 5 4 5 6\nRWOORWORROW\n" ]
[ "11\n", "-1\n", "28\n" ]
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11. In the second example Arkady can not buy a bouquet because all roses have the same color.
[ { "input": "5 3\n4 3 4 1 6\nRROWW", "output": "11" }, { "input": "5 2\n10 20 14 20 11\nRRRRR", "output": "-1" }, { "input": "11 5\n5 6 3 2 3 4 7 5 4 5 6\nRWOORWORROW", "output": "28" }, { "input": "15 10\n8560 6244 9607 5137 7187 3217 5527 9919 282 8748 3529 6110 5767 521 339...
1,000
63,283,200
0
47,959
977
Cyclic Components
[ "dfs and similar", "dsu", "graphs" ]
null
null
You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles. Here are some definitions of graph theory. An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices. Two vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$. A connected component is a cycle if and only if its vertices can be reordered in such a way that: - the first vertex is connected with the second vertex by an edge, - the second vertex is connected with the third vertex by an edge, - ... - the last vertex is connected with the first vertex by an edge, - all the described edges of a cycle are distinct. A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
The first line contains two integer numbers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) β€” number of vertices and edges. The following $m$ lines contains edges: edge $i$ is given as a pair of vertices $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$). There is no multiple edges in the given graph, i.e. for each pair ($v_i, u_i$) there no other pairs ($v_i, u_i$) and ($u_i, v_i$) in the list of edges.
Print one integer β€” the number of connected components which are also cycles.
[ "5 4\n1 2\n3 4\n5 4\n3 5\n", "17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6\n" ]
[ "1\n", "2\n" ]
In the first example only component $[3, 4, 5]$ is also a cycle. The illustration above corresponds to the second example.
[ { "input": "5 4\n1 2\n3 4\n5 4\n3 5", "output": "1" }, { "input": "17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6", "output": "2" }, { "input": "4 4\n1 2\n2 3\n1 3\n1 4", "output": "0" }, { "input": "5 5\n1 2\n2 3\n3 4\n4 1\n3 5...
748
37,580,800
-1
48,024
959
Mahmoud and Ehab and yet another xor task
[ "bitmasks", "dp", "math", "matrices" ]
null
null
Ehab has an array *a* of *n* integers. He likes the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud *q* queries. In each of them, he gave Mahmoud 2 integers *l* and *x*, and asked him to find the number of subsequences of the first *l* elements of the array such that their bitwise-xor sum is *x*. Can you help Mahmoud answer the queries? A subsequence can contain elements that are not neighboring.
The first line contains integers *n* and *q* (1<=≀<=*n*,<=*q*<=≀<=105), the number of elements in the array and the number of queries. The next line contains *n* integers *a*1, *a*2, ..., *a**n* (0<=≀<=*a**i*<=&lt;<=220), the elements of the array. The next *q* lines, each contains integers *l* and *x* (1<=≀<=*l*<=≀<=*n*, 0<=≀<=*x*<=&lt;<=220), representing the queries.
For each query, output its answer modulo 109<=+<=7 in a newline.
[ "5 5\n0 1 2 3 4\n4 3\n2 0\n3 7\n5 7\n5 8\n", "3 2\n1 1 1\n3 1\n2 0\n" ]
[ "4\n2\n0\n4\n0\n", "4\n2\n" ]
The bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself.
[ { "input": "5 5\n0 1 2 3 4\n4 3\n2 0\n3 7\n5 7\n5 8", "output": "4\n2\n0\n4\n0" }, { "input": "3 2\n1 1 1\n3 1\n2 0", "output": "4\n2" }, { "input": "20 20\n353123 353123 677328 353123 0 997043 677328 420884 968991 566539 420884 801220 1030642 937882 762558 599450 196420 299659 101896 60...
1,000
7,168,000
0
48,027
85
Embassy Queue
[ "data structures", "greedy" ]
B. Embassy Queue
2
256
In an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order. For each action several separate windows are singled out: *k*1 separate windows for the first action (the first type windows), *k*2 windows for the second one (the second type windows), and *k*3 for the third one (the third type windows). The service time for one person in any of the first type window equals to *t*1. Similarly, it takes *t*2 time to serve a person in any of the second type windows. And it takes *t*3 to serve one person in any of the third type windows. Thus, the service time depends only on the window type and is independent from the person who is applying for visa. At some moment *n* people come to the embassy, the *i*-th person comes at the moment of time *c**i*. The person is registered under some number. After that he sits in the hall and waits for his number to be shown on a special board. Besides the person's number the board shows the number of the window where one should go and the person goes there immediately. Let's consider that the time needed to approach the window is negligible. The table can show information for no more than one person at a time. The electronic queue works so as to immediately start working with the person who has approached the window, as there are no other people in front of the window. The Client Service Quality inspectors noticed that several people spend too much time in the embassy (this is particularly tiresome as the embassy has no mobile phone reception and 3G). It was decided to organise the system so that the largest time a person spends in the embassy were minimum. Help the inspectors organise the queue. Consider that all actions except for being served in at the window, happen instantly.
The first line contains three space-separated integers *k*1, *k*2, *k*3 (1<=≀<=*k**i*<=≀<=109), they are the number of windows of the first, second and third type correspondingly. The second line contains three space-separated integers *t*1, *t*2, *t*3 (1<=≀<=*t**i*<=≀<=105), they are the periods of time needed to serve one person in the window of the first, second and third type correspondingly. The third line contains an integer *n* (1<=≀<=*n*<=≀<=105), it is the number of people. The fourth line contains *n* space-separated integers *c**i* (1<=≀<=*c**i*<=≀<=109) in the non-decreasing order; *c**i* is the time when the person number *i* comes to the embassy.
Print the single number, the maximum time a person will spend in the embassy if the queue is organized optimally. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams (also you may use the %I64d specificator).
[ "1 1 1\n1 1 1\n5\n1 1 1 1 1\n", "2 1 1\n5 1 1\n5\n1 2 3 3 5\n" ]
[ "7\n", "13\n" ]
In the first test 5 people come simultaneously at the moment of time equal to 1. There is one window of every type, it takes 1 unit of time to be served at each window. That's why the maximal time a person spends in the embassy is the time needed to be served at the windows (3 units of time) plus the time the last person who comes to the first window waits (4 units of time). Windows in the second test work like this: The first window of the first type: [1, 6) β€” the first person, [6, 11) β€” third person, [11, 16) β€” fifth person The second window of the first type: [2, 7) β€” the second person, [7, 12) β€” the fourth person The only second type window: [6, 7) β€” first, [7, 8) β€” second, [11, 12) β€” third, [12, 13) β€” fourth, [16, 17) β€” fifth The only third type window: [7, 8) β€” first, [8, 9) β€” second, [12, 13) β€” third, [13, 14) β€” fourth, [17, 18) β€” fifth We can see that it takes most time to serve the fifth person.
[ { "input": "1 1 1\n1 1 1\n5\n1 1 1 1 1", "output": "7" }, { "input": "2 1 1\n5 1 1\n5\n1 2 3 3 5", "output": "13" }, { "input": "1 1 1\n1 1 1\n5\n1 2 3 4 5", "output": "3" }, { "input": "1 1 1\n1 1 1\n5\n1 2 3 3 4", "output": "4" }, { "input": "9 5 6\n8 2 2\n1\n5"...
496
16,793,600
3.844719
48,037
780
Underground Lab
[ "constructive algorithms", "dfs and similar", "graphs" ]
null
null
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex. The lab can be pictured as a connected graph with *n* vertices and *m* edges. *k* clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone. Each clone can visit at most vertices before the lab explodes. Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
The first line contains three integers *n*, *m*, and *k* (1<=≀<=*n*<=≀<=2Β·105, *n*<=-<=1<=≀<=*m*<=≀<=2Β·105, 1<=≀<=*k*<=≀<=*n*)Β β€” the number of vertices and edges in the lab, and the number of clones. Each of the next *m* lines contains two integers *x**i* and *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*)Β β€” indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
You should print *k* lines. *i*-th of these lines must start with an integer *c**i* ()Β β€” the number of vertices visited by *i*-th clone, followed by *c**i* integersΒ β€” indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
[ "3 2 1\n2 1\n3 1\n", "5 4 2\n1 2\n1 3\n1 4\n1 5\n" ]
[ "3 2 1 3\n", "3 2 1 3\n3 4 1 5" ]
In the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone. In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
[]
61
5,632,000
-1
48,083
993
Nikita and Order Statistics
[ "chinese remainder theorem", "fft", "math" ]
null
null
Nikita likes tasks on order statistics, for example, he can easily find the $k$-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number $x$ is the $k$-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly $k$ numbers of this segment which are less than $x$. Nikita wants to get answer for this question for each $k$ from $0$ to $n$, where $n$ is the size of the array.
The first line contains two integers $n$ and $x$ $(1 \le n \le 2 \cdot 10^5, -10^9 \le x \le 10^9)$. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(-10^9 \le a_i \le 10^9)$Β β€” the given array.
Print $n+1$ integers, where the $i$-th number is the answer for Nikita's question for $k=i-1$.
[ "5 3\n1 2 3 4 5\n", "2 6\n-5 9\n", "6 99\n-1 -1 -1 -1 -1 -1\n" ]
[ "6 5 4 0 0 0 ", "1 2 0 ", "0 6 5 4 3 2 1 " ]
none
[ { "input": "5 3\n1 2 3 4 5", "output": "6 5 4 0 0 0 " }, { "input": "2 6\n-5 9", "output": "1 2 0 " }, { "input": "6 99\n-1 -1 -1 -1 -1 -1", "output": "0 6 5 4 3 2 1 " }, { "input": "5 -2\n-1 -1 -4 -5 1", "output": "4 5 6 0 0 0 " }, { "input": "5 -6\n-4 2 -7 -1 -5...
2,000
185,548,800
0
48,150
358
Dima and Containers
[ "constructive algorithms", "greedy", "implementation" ]
null
null
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck. Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: 1. Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. 1. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation. As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!
The first line contains integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of Inna's commands. Then *n* lines follow, describing Inna's commands. Each line consists an integer: 1. Integer *a* (1<=≀<=*a*<=≀<=105) means that Inna gives Dima a command to add number *a* into one of containers. 1. Integer 0 shows that Inna asks Dima to make at most three extractions from different containers.
Each command of the input must correspond to one line of the output β€” Dima's action. For the command of the first type (adding) print one word that corresponds to Dima's choice: - pushStack β€” add to the end of the stack; - pushQueue β€” add to the end of the queue; - pushFront β€” add to the beginning of the deck; - pushBack β€” add to the end of the deck. For a command of the second type first print an integer *k* (0<=≀<=*k*<=≀<=3), that shows the number of extract operations, then print *k* words separated by space. The words can be: - popStack β€” extract from the end of the stack; - popQueue β€” extract from the beginning of the line; - popFront β€” extract from the beginning from the deck; - popBack β€” extract from the end of the deck. The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers. The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.
[ "10\n0\n1\n0\n1\n2\n0\n1\n2\n3\n0\n", "4\n1\n2\n3\n0\n" ]
[ "0\npushStack\n1 popStack\npushStack\npushQueue\n2 popStack popQueue\npushStack\npushQueue\npushFront\n3 popStack popQueue popFront\n", "pushStack\npushQueue\npushFront\n3 popStack popQueue popFront\n" ]
none
[ { "input": "10\n0\n1\n0\n1\n2\n0\n1\n2\n3\n0", "output": "0\npushStack\n1 popStack\npushStack\npushQueue\n2 popStack popQueue\npushStack\npushQueue\npushFront\n3 popStack popQueue popFront" }, { "input": "4\n1\n2\n3\n0", "output": "pushStack\npushQueue\npushFront\n3 popStack popQueue popFront" ...
77
0
0
48,269
463
Caisa and Tree
[ "brute force", "dfs and similar", "math", "number theory", "trees" ]
null
null
Caisa is now at home and his son has a simple task for him. Given a rooted tree with *n* vertices, numbered from 1 to *n* (vertex 1 is the root). Each vertex of the tree has a value. You should answer *q* queries. Each query is one of the following: - Format of the query is "1 *v*". Let's write out the sequence of vertices along the path from the root to vertex *v*: *u*1,<=*u*2,<=...,<=*u**k* (*u*1<==<=1;Β *u**k*<==<=*v*). You need to output such a vertex *u**i* that *gcd*(*value*Β *of*Β *u**i*,<=*value*Β *of*Β *v*)<=&gt;<=1 and *i*<=&lt;<=*k*. If there are several possible vertices *u**i* pick the one with maximum value of *i*. If there is no such vertex output -1. - Format of the query is "2 *v* *w*". You must change the value of vertex *v* to *w*. You are given all the queries, help Caisa to solve the problem.
The first line contains two space-separated integers *n*, *q* (1<=≀<=*n*,<=*q*<=≀<=105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=2Β·106), where *a**i* represent the value of node *i*. Each of the next *n*<=-<=1 lines contains two integers *x**i* and *y**i* (1<=≀<=*x**i*,<=*y**i*<=≀<=*n*;Β *x**i*<=β‰ <=*y**i*), denoting the edge of the tree between vertices *x**i* and *y**i*. Each of the next *q* lines contains a query in the format that is given above. For each query the following inequalities hold: 1<=≀<=*v*<=≀<=*n* and 1<=≀<=*w*<=≀<=2Β·106. Note that: there are no more than 50 queries that changes the value of a vertex.
For each query of the first type output the result of the query.
[ "4 6\n10 8 4 3\n1 2\n2 3\n3 4\n1 1\n1 2\n1 3\n1 4\n2 1 9\n1 4\n" ]
[ "-1\n1\n2\n-1\n1\n" ]
*gcd*(*x*, *y*) is greatest common divisor of two integers *x* and *y*.
[ { "input": "4 6\n10 8 4 3\n1 2\n2 3\n3 4\n1 1\n1 2\n1 3\n1 4\n2 1 9\n1 4", "output": "-1\n1\n2\n-1\n1" }, { "input": "4 46\n1826622 227609 1815373 691816\n4 1\n3 1\n1 2\n1 2\n1 3\n2 3 1226461\n1 2\n2 2 329857\n1 4\n1 2\n1 2\n1 3\n1 3\n1 1\n1 4\n1 1\n1 3\n1 3\n1 2\n1 4\n1 4\n1 3\n1 2\n1 2\n2 3 106992...
233
268,390,400
0
48,370
0
none
[ "none" ]
null
null
Natasha travels around Mars in the Mars rover. But suddenly it broke down, namelyΒ β€” the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $1$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output. There are four types of logical elements: [AND](https://en.wikipedia.org/wiki/Logical_conjunction) ($2$ inputs), [OR](https://en.wikipedia.org/wiki/Logical_disjunction) ($2$ inputs), [XOR](https://en.wikipedia.org/wiki/Exclusive_or) ($2$ inputs), [NOT](https://en.wikipedia.org/wiki/Negation) ($1$ input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input. For each input, determine what the output will be if Natasha changes this input.
The first line contains a single integer $n$ ($2 \le n \le 10^6$)Β β€” the number of vertices in the graph (both inputs and elements). The $i$-th of the next $n$ lines contains a description of $i$-th vertex: the first word "AND", "OR", "XOR", "NOT" or "IN" (means the input of the scheme) is the vertex type. If this vertex is "IN", then the value of this input follows ($0$ or $1$), otherwise follow the indices of input vertices of this element: "AND", "OR", "XOR" have $2$ inputs, whereas "NOT" has $1$ input. The vertices are numbered from one. It is guaranteed that input data contains a correct logical scheme with an output produced by the vertex $1$.
Print a string of characters '0' and '1' (without quotes)Β β€” answers to the problem for each input in the ascending order of their vertex indices.
[ "10\nAND 9 4\nIN 1\nIN 1\nXOR 6 5\nAND 3 7\nIN 0\nNOT 10\nIN 1\nIN 1\nAND 2 8\n" ]
[ "10110" ]
The original scheme from the example (before the input is changed): <img class="tex-graphics" src="https://espresso.codeforces.com/4507113582d40356e140857daa04318b91197f46.png" style="max-width: 100.0%;max-height: 100.0%;"/> Green indicates bits '1', yellow indicates bits '0'. If Natasha changes the input bit $2$ to $0$, then the output will be $1$. If Natasha changes the input bit $3$ to $0$, then the output will be $0$. If Natasha changes the input bit $6$ to $1$, then the output will be $1$. If Natasha changes the input bit $8$ to $0$, then the output will be $1$. If Natasha changes the input bit $9$ to $0$, then the output will be $0$.
[ { "input": "10\nAND 9 4\nIN 1\nIN 1\nXOR 6 5\nAND 3 7\nIN 0\nNOT 10\nIN 1\nIN 1\nAND 2 8", "output": "10110" }, { "input": "3\nAND 2 3\nIN 0\nIN 0", "output": "00" }, { "input": "3\nAND 2 3\nIN 1\nIN 0", "output": "01" }, { "input": "3\nAND 2 3\nIN 0\nIN 1", "output": "10...
62
0
0
48,390
148
Terse princess
[ "constructive algorithms", "greedy" ]
null
null
Β«Next pleaseΒ», β€” the princess called and cast an estimating glance at the next groom. The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured Β«Oh...Β». Whenever the groom is richer than all previous ones added together, she exclaims Β«Wow!Β» (no Β«Oh...Β» in this case). At the sight of the first groom the princess stays calm and says nothing. The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw *n* grooms, said Β«Oh...Β» exactly *a* times and exclaimed Β«Wow!Β» exactly *b* times. Your task is to output a sequence of *n* integers *t*1,<=*t*2,<=...,<=*t**n*, where *t**i* describes the fortune of *i*-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.
The only line of input data contains three integer numbers *n*,<=*a* and *b* (1<=≀<=*n*<=≀<=100,<=0<=≀<=*a*,<=*b*<=≀<=15,<=*n*<=&gt;<=*a*<=+<=*b*), separated with single spaces.
Output any sequence of integers *t*1,<=*t*2,<=...,<=*t**n*, where *t**i* (1<=≀<=*t**i*<=≀<=50000) is the fortune of *i*-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1.
[ "10 2 3\n", "5 0 0\n" ]
[ "5 1 3 6 16 35 46 4 200 99", "10 10 6 6 5" ]
Let's have a closer look at the answer for the first sample test. - The princess said Β«Oh...Β» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99. - The princess exclaimed Β«Wow!Β» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.
[ { "input": "10 2 3", "output": "1 2 4 8 9 10 10 10 10 10 " }, { "input": "5 0 0", "output": "1 1 1 1 1 " }, { "input": "5 2 2", "output": "1 2 4 5 6 " }, { "input": "6 2 2", "output": "1 2 4 5 6 6 " }, { "input": "10 9 0", "output": "-1" }, { "input": ...
62
0
0
48,512
963
Cutting Rectangle
[ "brute force", "math", "number theory" ]
null
null
A rectangle with sides $A$ and $B$ is cut into rectangles with cuts parallel to its sides. For example, if $p$ horizontal and $q$ vertical cuts were made, $(p + 1) \cdot (q + 1)$ rectangles were left after the cutting. After the cutting, rectangles were of $n$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $a \times b$ and $b \times a$ are considered different if $a \neq b$. For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle. Calculate the amount of pairs $(A; B)$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $A$ and $B$. Note that pairs $(A; B)$ and $(B; A)$ are considered different when $A \neq B$.
The first line consists of a single integer $n$ ($1 \leq n \leq 2 \cdot 10^{5}$)Β β€” amount of different types of rectangles left after cutting the initial rectangle. The next $n$ lines each consist of three integers $w_{i}, h_{i}, c_{i}$ $(1 \leq w_{i}, h_{i}, c_{i} \leq 10^{12})$Β β€” the lengths of the sides of the rectangles of this type and the amount of the rectangles of this type. It is guaranteed that the rectangles of the different types are different.
Output one integerΒ β€” the answer to the problem.
[ "1\n1 1 9\n", "2\n2 3 20\n2 4 40\n", "2\n1 2 5\n2 3 5\n" ]
[ "3\n", "6\n", "0\n" ]
In the first sample there are three suitable pairs: $(1; 9)$, $(3; 3)$ and $(9; 1)$. In the second sample case there are 6 suitable pairs: $(2; 220)$, $(4; 110)$, $(8; 55)$, $(10; 44)$, $(20; 22)$ and $(40; 11)$. Here the sample of cut for $(20; 22)$. The third sample has no suitable pairs.
[ { "input": "1\n1 1 9", "output": "3" }, { "input": "2\n2 3 20\n2 4 40", "output": "6" }, { "input": "2\n1 2 5\n2 3 5", "output": "0" } ]
93
0
-1
48,529
364
Free Market
[ "dp", "greedy" ]
null
null
John Doe has recently found a "Free Market" in his city β€” that is the place where you can exchange some of your possessions for other things for free. John knows that his city has *n* items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that each item is one of a kind and that means that you cannot exchange set {*a*,<=*b*} for set {*v*,<=*a*}. However, you can always exchange set *x* for any set *y*, unless there is item *p*, such that *p* occurs in *x* and *p* occurs in *y*. For each item, John knows its value *c**i*. John's sense of justice doesn't let him exchange a set of items *x* for a set of items *y*, if *s*(*x*)<=+<=*d*<=&lt;<=*s*(*y*) (*s*(*x*) is the total price of items in the set *x*). During one day John can exchange only one set of items for something else. Initially, he has no items. John wants to get a set of items with the maximum total price. Find the cost of such set and the minimum number of days John can get it in.
The first line contains two space-separated integers *n*, *d* (1<=≀<=*n*<=≀<=50, 1<=≀<=*d*<=≀<=104) β€” the number of items on the market and John's sense of justice value, correspondingly. The second line contains *n* space-separated integers *c**i* (1<=≀<=*c**i*<=≀<=104).
Print two space-separated integers: the maximum possible price in the set of items John can get and the minimum number of days needed to get such set.
[ "3 2\n1 3 10\n", "3 5\n1 2 3\n", "10 10000\n10000 9999 1 10000 10000 10000 1 2 3 4\n" ]
[ "4 3\n", "6 2\n", "50010 6\n" ]
In the first sample John can act like this: - Take the first item (1 - 0 ≀ 2). - Exchange the first item for the second one (3 - 1 ≀ 2). - Take the first item (1 - 0 ≀ 2).
[]
31
0
0
48,572
616
Expensive Strings
[ "string suffix structures", "strings" ]
null
null
You are given *n* strings *t**i*. Each string has cost *c**i*. Let's define the function of string , where *p**s*,<=*i* is the number of occurrences of *s* in *t**i*, |*s*| is the length of the string *s*. Find the maximal value of function *f*(*s*) over all strings. Note that the string *s* is not necessarily some string from *t*.
The first line contains the only integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of strings in *t*. Each of the next *n* lines contains contains a non-empty string *t**i*. *t**i* contains only lowercase English letters. It is guaranteed that the sum of lengths of all strings in *t* is not greater than 5Β·105. The last line contains *n* integers *c**i* (<=-<=107<=≀<=*c**i*<=≀<=107) β€” the cost of the *i*-th string.
Print the only integer *a* β€” the maximal value of the function *f*(*s*) over all strings *s*. Note one more time that the string *s* is not necessarily from *t*.
[ "2\naa\nbb\n2 1\n", "2\naa\nab\n2 1\n" ]
[ "4\n", "5\n" ]
none
[ { "input": "2\naa\nbb\n2 1", "output": "4" }, { "input": "2\naa\nab\n2 1", "output": "5" }, { "input": "1\naaa\n2", "output": "8" }, { "input": "3\na\naa\naaa\n1 2 3", "output": "16" }, { "input": "3\na\naaa\naa\n2 1 3", "output": "11" }, { "input": "1...
31
0
0
48,729
598
Chocolate Bar
[ "brute force", "dp" ]
null
null
You have a rectangular chocolate bar consisting of *n*<=Γ—<=*m* single squares. You want to eat exactly *k* squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length. For example, if you have a chocolate bar consisting of 2<=Γ—<=3 unit squares then you can break it horizontally and get two 1<=Γ—<=3 pieces (the cost of such breaking is 32<==<=9), or you can break it vertically in two ways and get two pieces: 2<=Γ—<=1 and 2<=Γ—<=2 (the cost of such breaking is 22<==<=4). For several given values *n*, *m* and *k* find the minimum total cost of breaking. You can eat exactly *k* squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to *k* squares. The remaining *n*Β·*m*<=-<=*k* squares are not necessarily form a single rectangular piece.
The first line of the input contains a single integer *t* (1<=≀<=*t*<=≀<=40910)Β β€” the number of values *n*, *m* and *k* to process. Each of the next *t* lines contains three integers *n*, *m* and *k* (1<=≀<=*n*,<=*m*<=≀<=30,<=1<=≀<=*k*<=≀<=*min*(*n*Β·*m*,<=50))Β β€” the dimensions of the chocolate bar and the number of squares you want to eat respectively.
For each *n*, *m* and *k* print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly *k* squares.
[ "4\n2 2 1\n2 2 3\n2 2 2\n2 2 4\n" ]
[ "5\n5\n4\n0\n" ]
In the first query of the sample one needs to perform two breaks: - to split 2 × 2 bar into two pieces of 2 × 1 (cost is 2<sup class="upper-index">2</sup> = 4), - to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 1<sup class="upper-index">2</sup> = 1). In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
[ { "input": "4\n2 2 1\n2 2 3\n2 2 2\n2 2 4", "output": "5\n5\n4\n0" } ]
217
9,728,000
0
48,810
814
An unavoidable detour for home
[ "combinatorics", "dp", "graphs", "shortest paths" ]
null
null
Those unwilling to return home from a long journey, will be affected by the oddity of the snail and lose their way. Mayoi, the oddity's carrier, wouldn't like this to happen, but there's nothing to do with this before a cure is figured out. For now, she would only like to know the enormous number of possibilities to be faced with if someone gets lost. There are *n* towns in the region, numbered from 1 to *n*. The town numbered 1 is called the capital. The traffic network is formed by bidirectional roads connecting pairs of towns. No two roads connect the same pair of towns, and no road connects a town with itself. The time needed to travel through each of the roads is the same. Lost travelers will not be able to find out how the towns are connected, but the residents can help them by providing the following facts: - Starting from each town other than the capital, the shortest path (i.e. the path passing through the minimum number of roads) to the capital exists, and is unique; - Let *l**i* be the number of roads on the shortest path from town *i* to the capital, then *l**i*<=β‰₯<=*l**i*<=-<=1 holds for all 2<=≀<=*i*<=≀<=*n*; - For town *i*, the number of roads connected to it is denoted by *d**i*, which equals either 2 or 3. You are to count the number of different ways in which the towns are connected, and give the answer modulo 109<=+<=7. Two ways of connecting towns are considered different if a pair (*u*,<=*v*) (1<=≀<=*u*,<=*v*<=≀<=*n*) exists such there is a road between towns *u* and *v* in one of them but not in the other.
The first line of input contains a positive integer *n* (3<=≀<=*n*<=≀<=50) β€” the number of towns. The second line contains *n* space-separated integers *d*1,<=*d*2,<=...,<=*d**n* (2<=≀<=*d**i*<=≀<=3) β€” the number of roads connected to towns 1,<=2,<=...,<=*n*, respectively. It is guaranteed that the sum of *d**i* over all *i* is even.
Output one integer β€” the total number of different possible ways in which the towns are connected, modulo 109<=+<=7.
[ "4\n3 2 3 2\n", "5\n2 3 3 2 2\n", "5\n2 2 2 2 2\n", "20\n2 2 2 2 3 2 3 2 2 2 2 2 2 2 2 2 2 3 3 2\n" ]
[ "1\n", "2\n", "2\n", "82944\n" ]
In the first example, the following structure is the only one to satisfy the constraints, the distances from towns 2, 3, 4 to the capital are all 1. In the second example, the following two structures satisfy the constraints.
[]
3,000
307,200
0
48,860
294
Shaass the Great
[ "dp", "trees" ]
null
null
The great Shaass is the new king of the Drakht empire. The empire has *n* cities which are connected by *n*<=-<=1 bidirectional roads. Each road has an specific length and connects a pair of cities. There's a unique simple path connecting each pair of cities. His majesty the great Shaass has decided to tear down one of the roads and build another road with the same length between some pair of cities. He should build such road that it's still possible to travel from each city to any other city. He might build the same road again. You as his advisor should help him to find a way to make the described action. You should find the way that minimize the total sum of pairwise distances between cities after the action. So calculate the minimum sum.
The first line of the input contains an integer *n* denoting the number of cities in the empire, (2<=≀<=*n*<=≀<=5000). The next *n*<=-<=1 lines each contains three integers *a**i*, *b**i* and *w**i* showing that two cities *a**i* and *b**i* are connected using a road of length *w**i*, (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*,<=1<=≀<=*w**i*<=≀<=106).
On the only line of the output print the minimum pairwise sum of distances between the cities. Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
[ "3\n1 2 2\n1 3 4\n", "6\n1 2 1\n2 3 1\n3 4 1\n4 5 1\n5 6 1\n", "6\n1 3 1\n2 3 1\n3 4 100\n4 5 2\n4 6 1\n" ]
[ "12\n", "29\n", "825\n" ]
none
[]
46
0
0
48,872
263
Squares
[ "greedy", "implementation", "sortings" ]
null
null
Vasya has found a piece of paper with a coordinate system written on it. There are *n* distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to *n*. It turned out that points with coordinates (0,<=0) and (*a**i*,<=*a**i*) are the opposite corners of the *i*-th square. Vasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly *k* drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. Help Vasya find a point that would meet the described limits.
The first line contains two space-separated integers *n*, *k* (1<=≀<=*n*,<=*k*<=≀<=50). The second line contains space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109). It is guaranteed that all given squares are distinct.
In a single line print two space-separated integers *x* and *y* (0<=≀<=*x*,<=*y*<=≀<=109) β€” the coordinates of the point that belongs to exactly *k* squares. If there are multiple answers, you are allowed to print any of them. If there is no answer, print "-1" (without the quotes).
[ "4 3\n5 1 3 4\n", "3 1\n2 4 1\n", "4 50\n5 1 10 2\n" ]
[ "2 1\n", "4 0\n", "-1\n" ]
none
[ { "input": "4 3\n5 1 3 4", "output": "2 1" }, { "input": "3 1\n2 4 1", "output": "4 0" }, { "input": "4 50\n5 1 10 2", "output": "-1" }, { "input": "3 4\n5 1 4", "output": "-1" }, { "input": "1 1\n2", "output": "2 1" }, { "input": "1 2\n10", "outpu...
124
0
3
48,903
166
Shoe Store
[ "dp", "graph matchings", "greedy", "sortings", "two pointers" ]
null
null
The warehouse in your shop has *n* shoe pairs. Each pair is characterized by two integers: its price *c**i* and its size *s**i*. We know that on this very day all numbers *s**i* are different, that is, there is no more than one pair of each size. The shop has *m* customers who came at the same time. The customer number *i* has *d**i* money and the size of his feet equals *l**i*. The customer number *i* can buy the pair number *j*, if *c**j*<=≀<=*d**i*, and also if *l**i*<==<=*s**j* or *l**i*<==<=*s**j*<=-<=1; that is, it is necessary that he has enough money to pay for the shoes. It is also necessary that the size of his feet equals to or is less by 1 than the size of the shoes he chooses. Your task is to sell some customers pairs of shoes (a pair per person) so as to maximize the sum of the sold pairs *c**j* that is, the profit. It is guaranteed that each customer buys no more than one pair and each pair will be bought by no more than one customer.
The first input line contains the only integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of shoe pairs in the warehouse. Then *n* lines contain the descriptions of pairs of shoes as two integers *c**i* and *s**i* (1<=≀<=*c**i*,<=*s**i*<=≀<=109), the numbers are separated by a space. It is guaranteed that all numbers *s**i* are different. The next line contains an integer *m* (1<=≀<=*m*<=≀<=105) β€” the number of customers in the shop. Next *m* lines contain the customers' descriptions as two integers *d**i* and *l**i* (1<=≀<=*d**i*,<=*l**i*<=≀<=109), the numbers are separated by a space.
In the first line print the only integer β€” the maximum profit you can get from selling shoes. In the second line print an integer *k* β€” the number of shoe pairs you will sell. In the following *k* lines print the descriptions of the sold pairs β€” two space-separated integers where the first number is the customer's number and the second number is the number of the shoes the customer will buy. You can print pairs of numbers "the customer's number and the shoes' number" in any order, the customers and the pairs of shoes are numbered starting from 1 in the order in which they are given in the input. If there are several optimal answers, you are allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator instead.
[ "3\n10 1\n30 2\n20 3\n2\n20 1\n20 2\n", "3\n10 4\n20 5\n30 6\n2\n70 4\n50 5\n" ]
[ "30\n2\n2 3\n1 1\n", "50\n2\n2 3\n1 2\n" ]
none
[]
92
0
0
48,955
840
Leha and Function
[ "combinatorics", "greedy", "math", "number theory", "sortings" ]
null
null
Leha like all kinds of strange things. Recently he liked the function *F*(*n*,<=*k*). Consider all possible *k*-element subsets of the set [1,<=2,<=...,<=*n*]. For subset find minimal element in it. *F*(*n*,<=*k*) β€” mathematical expectation of the minimal element among all *k*-element subsets. But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays *A* and *B*, each consists of *m* integers. For all *i*,<=*j* such that 1<=≀<=*i*,<=*j*<=≀<=*m* the condition *A**i*<=β‰₯<=*B**j* holds. Help Leha rearrange the numbers in the array *A* so that the sum is maximally possible, where *A*' is already rearranged array.
First line of input data contains single integer *m* (1<=≀<=*m*<=≀<=2Β·105) β€” length of arrays *A* and *B*. Next line contains *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≀<=*a**i*<=≀<=109) β€” array *A*. Next line contains *m* integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≀<=*b**i*<=≀<=109) β€” array *B*.
Output *m* integers *a*'1,<=*a*'2,<=...,<=*a*'*m* β€” array *A*' which is permutation of the array *A*.
[ "5\n7 3 5 3 4\n2 1 3 2 3\n", "7\n4 6 5 8 8 2 6\n2 1 2 2 1 1 2\n" ]
[ "4 7 3 5 3\n", "2 6 4 5 8 8 6\n" ]
none
[ { "input": "5\n7 3 5 3 4\n2 1 3 2 3", "output": "4 7 3 5 3" }, { "input": "7\n4 6 5 8 8 2 6\n2 1 2 2 1 1 2", "output": "2 6 4 5 8 8 6" } ]
1,232
31,436,800
3
49,072
708
Incorrect Flow
[ "flows" ]
null
null
At the entrance examination for the magistracy of the MSU Cyber-Mechanics Department Sasha got the question about Ford-Fulkerson algorithm. He knew the topic perfectly as he worked with it many times on programming competition. As the task for the question he was given a network with partially build flow that he had to use in order to demonstrate the workflow of the algorithm. He quickly finished to write the text and took a look at the problem only to understand that the given network is incorrect! Suppose you are given a directed graph *G*(*V*,<=*E*) with two special nodes *s* and *t* called source and sink. We denote as *n* the number of nodes in the graph, i.e. *n*<==<=|*V*| and *m* stands for the number of directed edges in the graph, i.e. *m*<==<=|*E*|. For the purpose of this problem we always consider node 1 to be the source and node *n* to be the sink. In addition, for each edge of the graph *e* we define the capacity function *c*(*e*) and flow function *f*(*e*). Function *f*(*e*) represents the correct flow if the following conditions are satisfied: 1. For each edge the flow is non-negative and does not exceed capacity *c*(*e*), i.e. 0<=≀<=*f*(*e*)<=≀<=*c*(*e*). 1. For each node , that is not source or sink (*v*<=β‰ <=*s* and *v*<=β‰ <=*t*) the sum of flows of all edges going in *v* is equal to the sum of the flows among all edges going out from *v*. In other words, there is no flow stuck in *v*. It was clear that as the exam was prepared last night and there are plenty of mistakes in the tasks. Sasha asked one of the professors to fix the network or give the correct task, but the reply was that the magistrate student should be able to fix the network himself. As the professor doesn't want the task to become easier, he asks Sasha to fix the network in a such way that the total number of changes is minimum possible. Sasha is not allowed to remove edges, add new ones or reverse the direction of existing edges. The only thing he is able to do is to change capacity function *c*(*e*) and flow function *f*(*e*). Moreover, all the values should remain non-negative integers. There is no requirement on the flow to be maximum in any sense. Find the minimum possible total change of the functions *f*(*e*) and *c*(*e*) that Sasha has to make in order to make the flow correct. The total change is defined as the sum of absolute differences, i.e. if new functions are *f*<=*<=(*e*) and *c*<=*<=(*e*), then the total change is .
The first line of the input contains two integers *n* and *m* (2<=≀<=*n*<=≀<=100, 0<=≀<=*m*<=≀<=100)Β β€” the number of nodes and edges in the graph respectively. Each of the following *m* lines contains the description of the edges, consisting of four integers *u**i*, *v**i*, *c**i* and *f**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*, *u**i*<=β‰ <=*v**i*, 0<=≀<=*c**i*,<=*f**i*<=≀<=1<=000<=000)Β β€” index of the node the edges starts from, the index of the node the edge goes to, current capacity and flow value. Node number 1 is the source, and node number *n* is the sink. It's guaranteed that no edge goes to the source, and no edges starts in the sink. Given graph contains no self-loops but may contain multiple edges.
Print one integerΒ β€” the minimum total sum of changes that Sasha has to do in order to get the correct flow description.
[ "2 1\n1 2 2 1\n", "2 1\n1 2 1 2\n", "3 3\n1 2 1 1\n2 3 2 2\n1 3 3 3\n", "4 2\n2 3 1 1\n3 2 1 1\n" ]
[ "0\n", "1\n", "1\n", "0\n" ]
In the first sample, the flow is initially correct. Note, that the flow is not maximum, but this is not required. In the second sample, the flow value of the only edge is greater than its capacity. There are two ways to fix this: either increase the capacity up to 2 or reduce the flow down to 1. In the third sample, there is only 1 unit of flow coming to vertex 2, but there are 2 units going out of it. One of the possible solutions is to reduce the value of the flow on the second edge by 1. In the fourth sample, there is isolated circulation of flow, but this description is correct by definition.
[]
30
0
0
49,126
87
Beautiful Road
[ "dfs and similar", "dp", "dsu", "graphs", "implementation", "sortings", "trees" ]
D. Beautiful Road
1
256
A long time ago in some country in Asia were civil wars. Each of *n* cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city. Road making was difficult, so the country had few roads, exactly *n*<=-<=1. Also you could reach any city from any other city going on those roads. Even during the war the Oriental people remain spiritually rich and appreciate the beauty of nature. And to keep the memory of this great crusade for the centuries to come, they planted one beautiful tree by the road on which the army spent most time. The Oriental people love nature, that's why if there were several such roads, then one tree was planted by each of them. Recently, when the records of the war were found, it became clear that each city attacked each other one exactly once. There were exactly *n*(*n*<=-<=1) attacks in total. Everyone has been wondering what road after those wars became the most beautiful, that is, by which road they planted the largest number of beautiful trees.
The first line contains an integer *n* (2<=≀<=*n*<=≀<=105), which represents the number of cities. Next *n*<=-<=1 lines contain three integers each: the numbers of cities *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*), connected by the *i*-th road and the number of days *d**i* the army spends to go on it (1<=≀<=*d**i*<=≀<=109). The lengths of several roads may coincide.
Print on the first line two integers β€” the number of beautiful trees on the most beautiful road and the number of the most beautiful roads. Print on the second line the list of the most beautiful roads in the sorted order by the numbers' increasing. The roads are numbered from 1 to *n*<=-<=1 in the order in which they are given in the input data. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator).
[ "2\n2 1 5\n", "6\n1 2 1\n1 3 5\n3 4 2\n3 5 3\n3 6 4\n" ]
[ "2 1\n1 \n", "16 1\n2 \n" ]
none
[ { "input": "2\n2 1 5", "output": "2 1\n1 " }, { "input": "6\n1 2 1\n1 3 5\n3 4 2\n3 5 3\n3 6 4", "output": "16 1\n2 " }, { "input": "10\n10 6 43981\n4 2 6730\n1 2 35174\n5 3 61951\n8 7 43981\n7 1 6730\n5 8 6730\n9 3 52479\n6 4 18138", "output": "32 1\n4 " }, { "input": "9\n6 ...
1,000
50,176,000
0
49,159
191
Demonstration
[ "greedy" ]
null
null
In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares. Bertown has *n* squares, numbered from 1 to *n*, they are numbered in the order of increasing distance between them and the city center. That is, square number 1 is central, and square number *n* is the farthest from the center. Naturally, the opposition wants to hold a meeting as close to the city center as possible (that is, they want an square with the minimum number). There are exactly *k* (*k*<=&lt;<=*n*) days left before the demonstration. Now all squares are free. But the Bertown city administration never sleeps, and the approval of an application for the demonstration threatens to become a very complex process. The process of approval lasts several days, but every day the following procedure takes place: - The opposition shall apply to hold a demonstration at a free square (the one which isn't used by the administration). - The administration tries to move the demonstration to the worst free square left. To do this, the administration organizes some long-term activities on the square, which is specified in the application of opposition. In other words, the administration starts using the square and it is no longer free. Then the administration proposes to move the opposition demonstration to the worst free square. If the opposition has applied for the worst free square then request is accepted and administration doesn't spend money. If the administration does not have enough money to organize an event on the square in question, the opposition's application is accepted. If administration doesn't have enough money to organize activity, then rest of administration's money spends and application is accepted - If the application is not accepted, then the opposition can agree to the administration's proposal (that is, take the worst free square), or withdraw the current application and submit another one the next day. If there are no more days left before the meeting, the opposition has no choice but to agree to the proposal of City Hall. If application is accepted opposition can reject it. It means than opposition still can submit more applications later, but square remains free. In order to organize an event on the square *i*, the administration needs to spend *a**i* bourles. Because of the crisis the administration has only *b* bourles to confront the opposition. What is the best square that the opposition can take, if the administration will keep trying to occupy the square in question each time? Note that the administration's actions always depend only on the actions of the opposition.
The first line contains two integers *n* and *k* β€” the number of squares and days left before the meeting, correspondingly (1<=≀<=*k*<=&lt;<=*n*<=≀<=105). The second line contains a single integer *b* β€” the number of bourles the administration has (1<=≀<=*b*<=≀<=1018). The third line contains *n* space-separated integers *a**i* β€” the sum of money, needed to organise an event on square *i* (1<=≀<=*a**i*<=≀<=109). Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Print a single number β€” the minimum number of the square where the opposition can organize the demonstration.
[ "5 2\n8\n2 4 5 3 1\n", "5 2\n8\n3 2 4 1 5\n", "5 4\n1000000000000000\n5 4 3 2 1\n" ]
[ "2\n", "5\n", "5\n" ]
In the first sample the opposition can act like this. On day one it applies for square 3. The administration has to organize an event there and end up with 3 bourles. If on the second day the opposition applies for square 2, the administration won't have the money to intervene. In the second sample the opposition has only the chance for the last square. If its first move occupies one of the first four squares, the administration is left with at least 4 bourles, which means that next day it can use its next move to move the opposition from any square to the last one. In the third sample administration has a lot of money, so opposition can occupy only last square.
[]
62
0
0
49,228
599
Spongebob and Squares
[ "brute force", "math" ]
null
null
Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly *x* distinct squares in the table consisting of *n* rows and *m* columns. For example, in a 3<=Γ—<=5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3<=Γ—<=5 table is 15<=+<=8<=+<=3<==<=26.
The first line of the input contains a single integer *x* (1<=≀<=*x*<=≀<=1018)Β β€” the number of squares inside the tables Spongebob is interested in.
First print a single integer *k*Β β€” the number of tables with exactly *x* distinct squares inside. Then print *k* pairs of integers describing the tables. Print the pairs in the order of increasing *n*, and in case of equalityΒ β€” in the order of increasing *m*.
[ "26\n", "2\n", "8\n" ]
[ "6\n1 26\n2 9\n3 5\n5 3\n9 2\n26 1\n", "2\n1 2\n2 1\n", "4\n1 8\n2 3\n3 2\n8 1\n" ]
In a 1 × 2 table there are 2 1 × 1 squares. So, 2 distinct squares in total. In a 2 × 3 table there are 6 1 × 1 squares and 2 2 × 2 squares. That is equal to 8 squares in total.
[ { "input": "26", "output": "6\n1 26\n2 9\n3 5\n5 3\n9 2\n26 1" }, { "input": "2", "output": "2\n1 2\n2 1" }, { "input": "8", "output": "4\n1 8\n2 3\n3 2\n8 1" }, { "input": "1", "output": "1\n1 1" }, { "input": "5005", "output": "12\n1 5005\n5 335\n6 240\n10 9...
265
14,950,400
0
49,411
630
Forecast
[ "math" ]
null
null
The Department of economic development of IT City created a model of city development till year 2100. To prepare report about growth perspectives it is required to get growth estimates from the model. To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots. The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.
The only line of the input contains three integers *a*,<=*b*,<=*c* (<=-<=1000<=≀<=*a*,<=*b*,<=*c*<=≀<=1000) β€” the coefficients of *ax*2<=+<=*bx*<=+<=*c*<==<=0 equation.
In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10<=-<=6.
[ "1 30 200\n" ]
[ "-10.000000000000000\n-20.000000000000000" ]
none
[ { "input": "1 30 200", "output": "-10.000000000000000\n-20.000000000000000" }, { "input": "1 1 -1", "output": "0.618033988749895\n-1.618033988749895" }, { "input": "-1 1 1", "output": "1.618033988749895\n-0.618033988749895" }, { "input": "1000 1 -1", "output": "0.03112672...
62
0
3
49,450
955
Icicles
[]
null
null
Andrew's favourite Krakozyabra has recenly fled away and now he's eager to bring it back! At the moment the refugee is inside an icy cave with *n* icicles dangling from the ceiling located in integer coordinates numbered from 1 to *n*. The distance between floor and the *i*-th icicle is equal to *a**i*. Andrew is free to choose an arbitrary integer point *T* in range from 1 to *n* inclusive and at time instant 0 launch a sound wave spreading into both sides (left and right) at the speed of one point per second. Any icicle touched by the wave starts falling at the same speed (that means that in a second the distance from floor to icicle decreases by one but cannot become less that zero). While distance from icicle to floor is more than zero, it is considered passable; as soon as it becomes zero, the icicle blocks the path and prohibits passing. Krakozyabra is initially (i.e. at time instant 0) is located at point and starts running in the right direction at the speed of one point per second. You can assume that events in a single second happen in the following order: first Krakozyabra changes its position, and only then the sound spreads and icicles fall; in particular, that means that if Krakozyabra is currently at point and the falling (i.e. already touched by the sound wave) icicle at point *i* is 1 point from the floor, then Krakozyabra will pass it and find itself at and only after that the icicle will finally fall and block the path. Krakozyabra is considered entrapped if there are fallen (i.e. with *a**i*<==<=0) icicles both to the left and to the right of its current position. Help Andrew find the minimum possible time it takes to entrap Krakozyabra by choosing the optimal value of *T* or report that this mission is impossible.
The first line contains the number of icicles *n* (2<=≀<=*n*<=≀<=105). The next line contains *n* space-separated numbers *a**i* (1<=≀<=*a**i*<=≀<=105)Β β€” the distances from floor to icicles.
Print an only integer β€” the minimum time it takes to entrap Krakozyabra between two fallen icicles. If it is impossible, print <=-<=1.
[ "5\n1 4 3 5 1\n", "4\n1 2 1 1\n", "2\n2 1\n", "2\n1 2\n" ]
[ "3\n", "2\n", "3\n", "-1\n" ]
In sample case one it's optimal to launch the sound wave from point 3. Then in two seconds icicles 1 and 5 will start falling, and in one more seconds they will block the paths. Krakozyabra will be located at <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/36de0b98a41a7a3c26317908808c214e6d4ac3ff.png" style="max-width: 100.0%;max-height: 100.0%;"/> at that time. Note that icicle number 3 will also be fallen, so there will actually be two icicles blocking the path to the left. In sample case two it is optimal to launch the wave from point 2 and entrap Krakozyabra in 2 seconds. In sample case four the answer is impossible.
[]
15
0
0
49,752
926
Mobile Communications
[]
null
null
A sum of *p* rubles is charged from Arkady's mobile phone account every day in the morning. Among the following *m* days, there are *n* days when Arkady will top up the account: in the day *d**i* he will deposit *t**i* rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following *m* days. Determine the number of days starting from the 1-st to the *m*-th such that the account will have a negative amount on it after the daily payment (i.Β e. in evening). Initially the account's balance is zero rubles.
The first line contains three integers *n*, *p* and *m* (1<=≀<=*n*<=≀<=100<=000, 1<=≀<=*p*<=≀<=109, 1<=≀<=*m*<=≀<=109, *n*<=≀<=*m*) β€” the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check. The *i*-th of the following *n* lines contains two integers *d**i* and *t**i* (1<=≀<=*d**i*<=≀<=*m*, 1<=≀<=*t**i*<=≀<=109) β€” the index of the day when Arkady will make the *i*-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i.Β e. *d**i*<=&gt;<=*d**i*<=-<=1 for all *i* from 2 to *n*.
Print the number of days from the 1-st to the *m*-th such that the account will have a negative amount on it after the daily payment.
[ "3 6 7\n2 13\n4 20\n7 9\n", "5 4 100\n10 70\n15 76\n21 12\n30 100\n67 85\n" ]
[ "3\n", "26\n" ]
In the first example the balance will change as following (remember, initially the balance is zero): 1. in the first day 6 rubles will be charged, the balance in the evening will be equal to  - 6; 1. in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1; 1. in the third day 6 rubles will be charged, the balance in the evening will be equal to  - 5; 1. in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9; 1. in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3; 1. in the sixth day 6 rubles will be charged, the balance in the evening will be equal to  - 3; 1. in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0. Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day.
[ { "input": "3 6 7\n2 13\n4 20\n7 9", "output": "3" }, { "input": "5 4 100\n10 70\n15 76\n21 12\n30 100\n67 85", "output": "26" }, { "input": "14 25 100\n1 209\n2 224\n3 58\n4 31\n5 135\n6 16\n7 130\n8 113\n9 230\n10 60\n11 209\n12 185\n13 118\n14 16", "output": "31" }, { "inp...
62
7,065,600
0
49,796
0
none
[ "none" ]
C. 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...
218
6,963,200
3.93253
49,847
484
Kindergarten
[ "data structures", "dp", "greedy" ]
null
null
In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's sociability is the maximum difference of charisma of two children in the group (in particular, if the group consists of one child, its sociability equals a zero). The teacher wants to divide the children into some number of groups in such way that the total sociability of the groups is maximum. Help him find this value.
The first line contains integer *n*Β β€” the number of children in the line (1<=≀<=*n*<=≀<=106). The second line contains *n* integers *a**i*Β β€” the charisma of the *i*-th child (<=-<=109<=≀<=*a**i*<=≀<=109).
Print the maximum possible total sociability of all groups.
[ "5\n1 2 3 1 2\n", "3\n3 3 3\n" ]
[ "3\n", "0\n" ]
In the first test sample one of the possible variants of an division is following: the first three children form a group with sociability 2, and the two remaining children form a group with sociability 1. In the second test sample any division leads to the same result, the sociability will be equal to 0 in each group.
[ { "input": "5\n1 2 3 1 2", "output": "3" }, { "input": "3\n3 3 3", "output": "0" }, { "input": "1\n0", "output": "0" }, { "input": "2\n-1000000000 1000000000", "output": "2000000000" }, { "input": "4\n1 4 2 3", "output": "4" }, { "input": "4\n23 5 7 1"...
15
0
-1
49,896
0
none
[ "none" ]
null
null
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes *u* and *v* connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with *h* nodes, which are the hydra's heads. The stomach is connected with *t* nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of *h*<=+<=*t*<=+<=2 nodes. Also, Petya's got a non-directed graph *G*, consisting of *n* nodes and *m* edges. Petya got this graph as a last year birthday present from his mom. Graph *G* contains no self-loops or multiple edges. Now Petya wants to find a hydra in graph *G*. Or else, to make sure that the graph doesn't have a hydra.
The first line contains four integers *n*, *m*, *h*, *t* (1<=≀<=*n*,<=*m*<=≀<=105, 1<=≀<=*h*,<=*t*<=≀<=100) β€” the number of nodes and edges in graph *G*, and the number of a hydra's heads and tails. Next *m* lines contain the description of the edges of graph *G*. The *i*-th of these lines contains two integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, *a*<=β‰ <=*b*) β€” the numbers of the nodes, connected by the *i*-th edge. It is guaranteed that graph *G* contains no self-loops and multiple edges. Consider the nodes of graph *G* numbered with integers from 1 to *n*.
If graph *G* has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers β€” the numbers of nodes *u* and *v*. In the third line print *h* numbers β€” the numbers of the nodes that are the heads. In the fourth line print *t* numbers β€” the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
[ "9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1\n", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n" ]
[ "YES\n4 1\n5 6 \n9 3 2 \n", "NO\n" ]
The first sample is depicted on the picture below:
[]
154
307,200
0
49,925
1,000
Two-Paths
[ "data structures", "dp", "trees" ]
null
null
You are given a weighted tree (undirected connected graph with no cycles, loops or multiple edges) with $n$ vertices. The edge $\{u_j, v_j\}$ has weight $w_j$. Also each vertex $i$ has its own value $a_i$ assigned to it. Let's call a path starting in vertex $u$ and ending in vertex $v$, where each edge can appear no more than twice (regardless of direction), a 2-path. Vertices can appear in the 2-path multiple times (even start and end vertices). For some 2-path $p$ profit $\text{Pr}(p) = \sum\limits_{v \in \text{distinct vertices in } p}{a_v} - \sum\limits_{e \in \text{distinct edges in } p}{k_e \cdot w_e}$, where $k_e$ is the number of times edge $e$ appears in $p$. That is, vertices are counted once, but edges are counted the number of times they appear in $p$. You are about to answer $m$ queries. Each query is a pair of vertices $(qu, qv)$. For each query find 2-path $p$ from $qu$ to $qv$ with maximal profit $\text{Pr}(p)$.
The first line contains two integers $n$ and $q$ ($2 \le n \le 3 \cdot 10^5$, $1 \le q \le 4 \cdot 10^5$) β€” the number of vertices in the tree and the number of queries. The second line contains $n$ space-separated integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^9)$ β€” the values of the vertices. Next $n - 1$ lines contain descriptions of edges: each line contains three space separated integers $u_i$, $v_i$ and $w_i$ ($1 \le u_i, v_i \le n$, $u_i \neq v_i$, $1 \le w_i \le 10^9$) β€” there is edge $\{u_i, v_i\}$ with weight $w_i$ in the tree. Next $q$ lines contain queries (one per line). Each query contains two integers $qu_i$ and $qv_i$ $(1 \le qu_i, qv_i \le n)$ β€” endpoints of the 2-path you need to find.
For each query print one integer per line β€” maximal profit $\text{Pr}(p)$ of the some 2-path $p$ with the corresponding endpoints.
[ "7 6\n6 5 5 3 2 1 2\n1 2 2\n2 3 2\n2 4 1\n4 5 1\n6 4 2\n7 3 25\n1 1\n4 4\n5 6\n6 4\n3 4\n3 7\n" ]
[ "9\n9\n9\n8\n12\n-14\n" ]
Explanation of queries: 1. $(1, 1)$ β€” one of the optimal 2-paths is the following: $1 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1$. $\text{Pr}(p) = (a_1 + a_2 + a_3 + a_4 + a_5) - (2 \cdot w(1,2) + 2 \cdot w(2,3) + 2 \cdot w(2,4) + 2 \cdot w(4,5)) = 21 - 2 \cdot 12 = 9$. 1. $(4, 4)$: $4 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 4$. $\text{Pr}(p) = (a_1 + a_2 + a_3 + a_4) - 2 \cdot (w(1,2) + w(2,3) + w(2,4)) = 19 - 2 \cdot 10 = 9$. 1. $(5, 6)$: $5 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 4 \rightarrow 6$. 1. $(6, 4)$: $6 \rightarrow 4 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 4$. 1. $(3, 4)$: $3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 4$. 1. $(3, 7)$: $3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 7$.
[ { "input": "7 6\n6 5 5 3 2 1 2\n1 2 2\n2 3 2\n2 4 1\n4 5 1\n6 4 2\n7 3 25\n1 1\n4 4\n5 6\n6 4\n3 4\n3 7", "output": "9\n9\n9\n8\n12\n-14" }, { "input": "2 4\n5 3\n1 2 2\n1 1\n1 2\n2 1\n2 2", "output": "5\n6\n6\n4" }, { "input": "5 1\n1000000000 1000000000 1000000000 1000000000 1000000000...
3,042
268,390,400
0
49,940
533
Encoding
[ "hashing", "string suffix structures", "strings" ]
null
null
Polycarp invented a new way to encode strings. Let's assume that we have string *T*, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in *T* with its pair letter if there is a pair letter for it. For example, if you chose pairs (l, r), (p, q) and (a, o), then word "parallelogram" according to the given encoding principle transforms to word "qolorreraglom". Polycarpus already has two strings, *S* and *T*. He suspects that string *T* was obtained after applying the given encoding method from some substring of string *S*. Find all positions *m**i* in *S* (1<=≀<=*m**i*<=≀<=|*S*|<=-<=|*T*|<=+<=1), such that *T* can be obtained fro substring *S**m**i**S**m**i*<=+<=1... *S**m**i*<=+<=|*T*|<=-<=1 by applying the described encoding operation by using some set of pairs of English alphabet letters
The first line of the input contains two integers, |*S*| and |*T*| (1<=≀<=|*T*|<=≀<=|*S*|<=≀<=2Β·105) β€” the lengths of string *S* and string *T*, respectively. The second and third line of the input contain strings *S* and *T*, respectively. Both strings consist only of lowercase English letters.
Print number *k* β€” the number of suitable positions in string *S*. In the next line print *k* integers *m*1,<=*m*2,<=...,<=*m**k* β€” the numbers of the suitable positions in the increasing order.
[ "11 5\nabacabadaba\nacaba\n", "21 13\nparaparallelogramgram\nqolorreraglom\n" ]
[ "3\n1 3 7\n", "1\n5\n" ]
none
[]
124
0
0
50,001
725
Too Much Money
[ "brute force", "greedy" ]
null
null
Alfred wants to buy a toy moose that costs *c* dollars. The store doesn’t give change, so he must give the store exactly *c* dollars, no more and no less. He has *n* coins. To make *c* dollars from his coins, he follows the following algorithm: let *S* be the set of coins being used. *S* is initially empty. Alfred repeatedly adds to *S* the highest-valued coin he has such that the total value of the coins in *S* after adding the coin doesn’t exceed *c*. If there is no such coin, and the value of the coins in *S* is still less than *c*, he gives up and goes home. Note that Alfred never removes a coin from *S* after adding it. As a programmer, you might be aware that Alfred’s algorithm can fail even when there is a set of coins with value exactly *c*. For example, if Alfred has one coin worth $3, one coin worth $4, and two coins worth $5, and the moose costs $12, then Alfred will add both of the $5 coins to *S* and then give up, since adding any other coin would cause the value of the coins in *S* to exceed $12. Of course, Alfred could instead combine one $3 coin, one $4 coin, and one $5 coin to reach the total. Bob tried to convince Alfred that his algorithm was flawed, but Alfred didn’t believe him. Now Bob wants to give Alfred some coins (in addition to those that Alfred already has) such that Alfred’s algorithm fails. Bob can give Alfred any number of coins of any denomination (subject to the constraint that each coin must be worth a positive integer number of dollars). There can be multiple coins of a single denomination. He would like to minimize the total value of the coins he gives Alfred. Please find this minimum value. If there is no solution, print "Greed is good". You can assume that the answer, if it exists, is positive. In other words, Alfred's algorithm will work if Bob doesn't give him any coins.
The first line contains *c* (1<=≀<=*c*<=≀<=200<=000)Β β€” the price Alfred wants to pay. The second line contains *n* (1<=≀<=*n*<=≀<=200<=000)Β β€” the number of coins Alfred initially has. Then *n* lines follow, each containing a single integer *x* (1<=≀<=*x*<=≀<=*c*) representing the value of one of Alfred's coins.
If there is a solution, print the minimum possible total value of the coins in a solution. Otherwise, print "Greed is good" (without quotes).
[ "12\n3\n5\n3\n4\n", "50\n8\n1\n2\n4\n8\n16\n37\n37\n37\n" ]
[ "5\n", "Greed is good\n" ]
In the first sample, Bob should give Alfred a single coin worth $5. This creates the situation described in the problem statement. In the second sample, there is no set of coins that will cause Alfred's algorithm to fail.
[]
2,000
3,686,400
0
50,276
67
Sequence of Balls
[ "dp" ]
C. Sequence of Balls
1
256
You are given a sequence of balls *A* by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, *B* that suits you better. So, you allow yourself four operations: - You can insert any ball with any label into the sequence at any position. - You can delete (remove) any ball from any position. - You can replace any ball with any other ball. - You can exchange (swap) two adjacent balls. Your teacher now places time constraints on each operation, meaning that an operation can only be performed in certain time. So, the first operation takes time *t**i*, the second one takes *t**d*, the third one takes *t**r* and the fourth one takes *t**e*. Also, it is given that 2Β·*t**e*<=β‰₯<=*t**i*<=+<=*t**d*. Find the minimal time to convert the sequence *A* to the sequence *B*.
The first line contains four space-separated integers *t**i*,<=*t**d*,<=*t**r*,<=*t**e* (0<=&lt;<=*t**i*,<=*t**d*,<=*t**r*,<=*t**e*<=≀<=100). The following two lines contain sequences *A* and *B* on separate lines. The length of each line is between 1 and 4000 characters inclusive.
Print a single integer representing minimum time to convert *A* into *B*.
[ "1 1 1 1\nyoushouldnot\nthoushaltnot\n", "2 4 10 3\nab\nba\n", "1 10 20 30\na\nza\n" ]
[ "5\n", "3\n", "1\n" ]
In the second sample, you could delete the ball labeled 'a' from the first position and then insert another 'a' at the new second position with total time 6. However exchanging the balls give total time 3.
[]
1,000
18,329,600
0
50,327
527
Data Center Drama
[ "dfs and similar", "graphs" ]
null
null
The project of a data center of a Big Software Company consists of *n* computers connected by *m* cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is not yet approved, it wasn't determined yet in which direction information will go along each cable. The cables are put so that each computer is connected with each one, perhaps through some other computers. The person in charge of the cleaning the data center will be Claudia Ivanova, the janitor. She loves to tie cables into bundles using cable ties. For some reasons, she groups the cables sticking out of a computer into groups of two, and if it isn't possible, then she gets furious and attacks the computer with the water from the bucket. It should also be noted that due to the specific physical characteristics of the Very Important Information, it is strictly forbidden to connect in one bundle two cables where information flows in different directions. The management of the data center wants to determine how to send information along each cable so that Claudia Ivanova is able to group all the cables coming out of each computer into groups of two, observing the condition above. Since it may not be possible with the existing connections plan, you are allowed to add the minimum possible number of cables to the scheme, and then you need to determine the direction of the information flow for each cable (yes, sometimes data centers are designed based on the janitors' convenience...)
The first line contains two numbers, *n* and *m* (1<=≀<=*n*<=≀<=100<=000, 1<=≀<=*m*<=≀<=200<=000) β€” the number of computers and the number of the already present cables, respectively. Each of the next lines contains two numbers *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*) β€” the indices of the computers connected by the *i*-th cable. The data centers often have a very complex structure, so a pair of computers may have more than one pair of cables between them and some cables may connect a computer with itself.
In the first line print a single number *p* (*p*<=β‰₯<=*m*) β€” the minimum number of cables in the final scheme. In each of the next *p* lines print a pair of numbers *c**i*,<=*d**i* (1<=≀<=*c**i*,<=*d**i*<=≀<=*n*), describing another cable. Such entry means that information will go along a certain cable in direction from *c**i* to *d**i*. Among the cables you printed there should be all the cables presented in the original plan in some of two possible directions. It is guaranteed that there is a solution where *p* doesn't exceed 500<=000. If there are several posible solutions with minimum possible value of *p*, print any of them.
[ "4 6\n1 2\n2 3\n3 4\n4 1\n1 3\n1 3\n", "3 4\n1 2\n2 3\n1 1\n3 3\n" ]
[ "6\n1 2\n3 4\n1 4\n3 2\n1 3\n1 3", "6\n2 1\n2 3\n1 1\n3 3\n3 1\n1 1\n" ]
Picture for the first sample test. The tied pairs of cables are shown going out from the same point. Picture for the second test from the statement. The added cables are drawin in bold. Alternative answer for the second sample test:
[ { "input": "4 6\n1 2\n2 3\n3 4\n4 1\n1 3\n1 3", "output": "6\n3 4\n1 4\n3 1\n2 1\n2 3\n1 3" }, { "input": "3 4\n1 2\n2 3\n1 1\n3 3", "output": "6\n1 1\n3 3\n2 3\n2 1\n3 1\n1 1" }, { "input": "1 1\n1 1", "output": "2\n1 1\n1 1" }, { "input": "1 2\n1 1\n1 1", "output": "2\n...
46
0
0
50,396
875
Royal Questions
[ "dsu", "graphs", "greedy" ]
null
null
In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his *n* sons-princes marry the brides with as big dowry as possible. In search of candidates, the king asked neighboring kingdoms, and after a while several delegations arrived with *m* unmarried princesses. Receiving guests, Karl learned that the dowry of the *i* th princess is *w**i* of golden coins. Although the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride. Knowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince. Help the king to organize the marriage of his sons in the most profitable way for the treasury.
The first line contains two integers *n*, *m* (2<=≀<=*n*<=≀<=200<=000, 1<=≀<=*m*<=≀<=200<=000)Β β€” number of princes and princesses respectively. Each of following *m* lines contains three integers *a**i*, *b**i*, *w**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, *a**i*<=β‰ <=*b**i*, 1<=≀<=*w**i*<=≀<=10<=000)Β β€” number of princes, which *i*-th princess is ready to marry and the value of her dowry.
Print the only integerΒ β€” the maximum number of gold coins that a king can get by playing the right weddings.
[ "2 3\n1 2 5\n1 2 1\n2 1 10\n", "3 2\n1 2 10\n3 2 20\n" ]
[ "15", "30" ]
none
[ { "input": "2 3\n1 2 5\n1 2 1\n2 1 10", "output": "15" }, { "input": "3 2\n1 2 10\n3 2 20", "output": "30" }, { "input": "2 2\n1 2 1\n1 2 2", "output": "3" }, { "input": "3 3\n1 3 4\n1 3 2\n1 3 8", "output": "12" }, { "input": "2 1\n1 2 6", "output": "6" }, ...
46
5,529,600
-1
50,423
540
Ice Cave
[ "dfs and similar" ]
null
null
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice. The level of the cave where you are is a rectangular square grid of *n* rows and *m* columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked. Let's number the rows with integers from 1 to *n* from top to bottom and the columns with integers from 1 to *m* from left to right. Let's denote a cell on the intersection of the *r*-th row and the *c*-th column as (*r*,<=*c*). You are staying in the cell (*r*1,<=*c*1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (*r*2,<=*c*2) since the exit to the next level is there. Can you do this?
The first line contains two integers, *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=500)Β β€” the number of rows and columns in the cave description. Each of the next *n* lines describes the initial state of the level of the cave, each line consists of *m* characters "." (that is, intact ice) and "X" (cracked ice). The next line contains two integers, *r*1 and *c*1 (1<=≀<=*r*1<=≀<=*n*,<=1<=≀<=*c*1<=≀<=*m*)Β β€” your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (*r*1,<=*c*1), that is, the ice on the starting cell is initially cracked. The next line contains two integers *r*2 and *c*2 (1<=≀<=*r*2<=≀<=*n*,<=1<=≀<=*c*2<=≀<=*m*)Β β€” the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.
If you can reach the destination, print 'YES', otherwise print 'NO'.
[ "4 6\nX...XX\n...XX.\n.X..X.\n......\n1 6\n2 2\n", "5 4\n.X..\n...X\nX.X.\n....\n.XX.\n5 3\n1 1\n", "4 7\n..X.XX.\n.XX..X.\nX...X..\nX......\n2 2\n1 6\n" ]
[ "YES\n", "NO\n", "YES\n" ]
In the first sample test one possible path is: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c61f56de718beea14935ccdc85ae2c4ad45c1454.png" style="max-width: 100.0%;max-height: 100.0%;"/> After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.
[ { "input": "4 6\nX...XX\n...XX.\n.X..X.\n......\n1 6\n2 2", "output": "YES" }, { "input": "5 4\n.X..\n...X\nX.X.\n....\n.XX.\n5 3\n1 1", "output": "NO" }, { "input": "4 7\n..X.XX.\n.XX..X.\nX...X..\nX......\n2 2\n1 6", "output": "YES" }, { "input": "5 3\n.XX\n...\n.X.\n.X.\n....
46
102,400
0
50,451
936
World of Tank
[ "dp", "greedy" ]
null
null
Vitya loves programming and problem solving, but sometimes, to distract himself a little, he plays computer games. Once he found a new interesting game about tanks, and he liked it so much that he went through almost all levels in one day. Remained only the last level, which was too tricky. Then Vitya remembered that he is a programmer, and wrote a program that helped him to pass this difficult level. Try do the same. The game is organized as follows. There is a long road, two cells wide and *n* cells long. Some cells have obstacles. You control a tank that occupies one cell. Initially, the tank is located before the start of the road, in a cell with coordinates (0,<=1). Your task is to move the tank to the end of the road, to the cell (*n*<=+<=1,<=1) or (*n*<=+<=1,<=2). Every second the tank moves one cell to the right: the coordinate *x* is increased by one. When you press the up or down arrow keys, the tank instantly changes the lane, that is, the *y* coordinate. When you press the spacebar, the tank shoots, and the nearest obstacle along the lane in which the tank rides is instantly destroyed. In order to load a gun, the tank needs *t* seconds. Initially, the gun is not loaded, that means, the first shot can be made only after *t* seconds after the tank starts to move. If at some point the tank is in the same cell with an obstacle not yet destroyed, it burns out. If you press the arrow exactly at the moment when the tank moves forward, the tank will first move forward, and then change the lane, so it will not be possible to move diagonally. Your task is to find out whether it is possible to pass the level, and if possible, to find the order of actions the player need to make.
The first line contains four integers *n*, *m*1, *m*2 and *t*, the length of the field, the number of obstacles in the first lane, the number of obstacles in the second lane and the number of tank steps before reloading, respectively (1<=≀<=*n*<=≀<=109; 0<=≀<=*m*1,<=*m*2<=≀<=*n*; 0<=≀<=*m*1<=+<=*m*2<=≀<=106; 1<=≀<=*t*<=≀<=*n*). The next two lines contain a description of the obstacles. The first of these lines contains *m*1 numbers *x**i* β€” the obstacle coordinates in the first lane (1<=≀<=*x**i*<=≀<=*n*; *x**i*<=&lt;<=*x**i*<=+<=1). The *y* coordinate for all these obstacles will be 1. The second line contains *m*2 numbers describing the obstacles of the second lane in the same format. The *y* coordinate of all these obstacles will be 2.
In the first line print Β«YesΒ», if it is possible to pass the level, or Β«NoΒ», otherwise. If it is possible, then in the second line print the number of times the tank moves from one lane to another, and in the next line print the coordinates of the transitions, one number per transition: the coordinate *x* (0<=≀<=*x*<=≀<=*n*<=+<=1). All transition coordinates coordinates must be distinct and should be output in strictly increasing order.The number of transitions should not exceed 2Β·106. If the tank can pass the level, then it can do it using no more than 2Β·106 transitions. In the fourth line print the number of shots that the tank makes during the movement, in the following lines print two numbers, *x* and *y* coordinates of the point (1<=≀<=*x*<=≀<=*n*, 1<=≀<=*y*<=≀<=2), from which the tank fired a shot, the number of shots must not exceed *m*1<=+<=*m*2. Shots must be output in the order in which they are fired. If there are several solutions, output any one.
[ "6 2 3 2\n2 6\n3 5 6\n", "1 1 1 1\n1\n1\n", "9 5 2 5\n1 2 7 8 9\n4 6\n" ]
[ "Yes\n2\n0 3 \n2\n2 2\n4 1\n", "No\n", "Yes\n4\n0 3 5 10 \n1\n5 2\n" ]
Picture for the first sample test.
[]
78
307,200
0
50,569
837
Prefix Sums
[ "binary search", "brute force", "combinatorics", "math", "matrices" ]
null
null
Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≀<=*i*<=≀<=*m*). You have an infinite sequence of arrays *A*0,<=*A*1,<=*A*2..., where *A*0 is given in the input, and for each *i*<=β‰₯<=1 *A**i*<==<=*p*(*A**i*<=-<=1). Also you have a positive integer *k*. You have to find minimum possible *i* such that *A**i* contains a number which is larger or equal than *k*.
The first line contains two integers *n* and *k* (2<=≀<=*n*<=≀<=200000, 1<=≀<=*k*<=≀<=1018). *n* is the size of array *A*0. The second line contains *n* integers *A*00,<=*A*01... *A*0*n*<=-<=1 β€” the elements of *A*0 (0<=≀<=*A*0*i*<=≀<=109). At least two elements of *A*0 are positive.
Print the minimum *i* such that *A**i* contains a number which is larger or equal than *k*.
[ "2 2\n1 1\n", "3 6\n1 1 1\n", "3 1\n1 0 1\n" ]
[ "1\n", "2\n", "0\n" ]
none
[ { "input": "2 2\n1 1", "output": "1" }, { "input": "3 6\n1 1 1", "output": "2" }, { "input": "3 1\n1 0 1", "output": "0" }, { "input": "3 1000000000000000000\n5 4 5", "output": "632455531" }, { "input": "4 1000000000000000000\n0 4 4 5", "output": "707106780" ...
514
8,192,000
0
50,653
524
The Art of Dealing with ATM
[ "binary search", "sortings" ]
null
null
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most *k* bills from it, and the bills may be of at most two distinct denominations. For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at *k*<==<=20 such ATM can give sums 100<=000 burles and 96<=000 burles, but it cannot give sums 99<=000 and 101<=000 burles. Let's suppose that the country uses bills of *n* distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash *q* times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the *q* of requests for cash withdrawal.
The first line contains two integers *n*, *k* (1<=≀<=*n*<=≀<=5000, 1<=≀<=*k*<=≀<=20). The next line contains *n* space-separated integers *a**i* (1<=≀<=*a**i*<=≀<=107) β€” the denominations of the bills that are used in the country. Numbers *a**i* follow in the strictly increasing order. The next line contains integer *q* (1<=≀<=*q*<=≀<=20) β€” the number of requests for cash withdrawal that you will make. The next *q* lines contain numbers *x**i* (1<=≀<=*x**i*<=≀<=2Β·108) β€” the sums of money in burles that you are going to withdraw from the ATM.
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print <=-<=1, if it is impossible to get the corresponding sum.
[ "6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950\n", "5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15\n" ]
[ "6\n20\n19\n20\n-1\n3\n-1\n-1\n", "1\n1\n1\n2\n2\n2\n2\n-1\n" ]
none
[ { "input": "6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950", "output": "6\n20\n19\n20\n-1\n3\n-1\n-1" }, { "input": "5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15", "output": "1\n1\n1\n2\n2\n2\n2\n-1" }, { "input": "5 5\n1 2 3 6 102\n10\n1\n4\n30\n1...
265
0
0
50,706
489
Unbearable Controversy of Being
[ "brute force", "combinatorics", "dfs and similar", "graphs" ]
null
null
Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different! Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections *a*, *b*, *c* and *d*, such that there are two paths from *a* to *c* β€” one through *b* and the other one through *d*, he calls the group a "damn rhombus". Note that pairs (*a*,<=*b*), (*b*,<=*c*), (*a*,<=*d*), (*d*,<=*c*) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him. Given that the capital of Berland has *n* intersections and *m* roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city. When rhombi are compared, the order of intersections *b* and *d* doesn't matter.
The first line of the input contains a pair of integers *n*, *m* (1<=≀<=*n*<=≀<=3000,<=0<=≀<=*m*<=≀<=30000) β€” the number of intersections and roads, respectively. Next *m* lines list the roads, one per line. Each of the roads is given by a pair of integers *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*;*a**i*<=β‰ <=*b**i*) β€” the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one.
Print the required number of "damn rhombi".
[ "5 4\n1 2\n2 3\n1 4\n4 3\n", "4 12\n1 2\n1 3\n1 4\n2 1\n2 3\n2 4\n3 1\n3 2\n3 4\n4 1\n4 2\n4 3\n" ]
[ "1\n", "12\n" ]
none
[ { "input": "5 4\n1 2\n2 3\n1 4\n4 3", "output": "1" }, { "input": "4 12\n1 2\n1 3\n1 4\n2 1\n2 3\n2 4\n3 1\n3 2\n3 4\n4 1\n4 2\n4 3", "output": "12" }, { "input": "1 0", "output": "0" }, { "input": "10 20\n6 10\n4 2\n1 5\n6 1\n8 9\n1 3\n2 6\n9 7\n4 5\n3 7\n9 2\n3 9\n4 8\n1 10...
0
0
-1
50,748
0
none
[ "none" ]
null
null
In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far. The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall. Traditionally GUC has *n* professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from 1 to *n*, with 1 being the most senior professor and *n* being the most junior professor. The ceremonial hall has *n* seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, *m* pairs of seats are in "senior-junior" relation, and the tradition requires that for all *m* pairs of seats (*a**i*,<=*b**i*) the professor seated in "senior" position *a**i* should be more senior than the professor seated in "junior" position *b**i*. GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that: - The seating of the professors changes every year. - Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall. - Each consecutive year lexicographically next arrangement of the professors is used. The arrangement of the professors is the list of *n* integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc. Given *n*, the number of professors, *y*, the current year and *m* pairs of restrictions, output the arrangement of the professors for this year.
The first line contains three integers *n*, *y* and *m* (1<=≀<=*n*<=≀<=16,<=2001<=≀<=*y*<=≀<=1018,<=0<=≀<=*m*<=≀<=100) β€” the number of professors, the year for which the arrangement should be computed, and the number of pairs of seats for which the seniority relation should be kept, respectively. The next *m* lines contain one pair of integers each, "*a**i* *b**i*", indicating that professor on the *a**i*-th seat is more senior than professor on the *b**i*-th seat (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*,<=*a**i*<=β‰ <=*b**i*). Some pair may be listed more than once. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin stream (you may also use the %I64d specificator).
Print the order in which the professors should be seated in the requested year. If by this year the GUC would have ran out of arrangements, or the given "senior-junior" relation are contradictory, print "The times have changed" (without quotes).
[ "3 2001 2\n1 2\n2 3\n", "7 2020 6\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n", "10 3630801 0\n", "3 2001 3\n1 2\n2 3\n3 1\n" ]
[ "1 2 3\n", "1 2 3 7 4 6 5\n", "The times have changed\n", "The times have changed\n" ]
In the first example the lexicographically first order of seating is 1 2 3. In the third example the GUC will run out of arrangements after the year 3630800. In the fourth example there are no valid arrangements for the seating. The lexicographical comparison of arrangements is performed by the &lt; operator in modern programming languages. The arrangement *a* is lexicographically less that the arrangement *b*, if there exists such *i* (1 ≀ *i* ≀ *n*), that *a*<sub class="lower-index">*i*</sub> &lt; *b*<sub class="lower-index">*i*</sub>, and for any *j* (1 ≀ *j* &lt; *i*) *a*<sub class="lower-index">*j*</sub> = *b*<sub class="lower-index">*j*</sub>.
[]
62
0
0
50,788
630
Area of a Star
[ "geometry" ]
null
null
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star. A "star" figure having *n*<=β‰₯<=5 corners where *n* is a prime number is constructed the following way. On the circle of radius *r* *n* points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.
The only line of the input contains two integers *n* (5<=≀<=*n*<=&lt;<=109, *n* is prime) and *r* (1<=≀<=*r*<=≀<=109) β€” the number of the star corners and the radius of the circumcircle correspondingly.
Output one number β€” the star area. The relative error of your answer should not be greater than 10<=-<=7.
[ "7 10\n" ]
[ "108.395919545675" ]
none
[ { "input": "7 10", "output": "108.395919545675" }, { "input": "5 1", "output": "1.122569941449" }, { "input": "7 1000", "output": "1083959.195456745256" }, { "input": "11 1000000000", "output": "1061689977712182980.125000000000" }, { "input": "999999937 1", "o...
0
0
-1
50,794
138
Hellish Constraints
[ "brute force", "dp", "two pointers" ]
null
null
Katya recently started to invent programming tasks and prepare her own contests. What she does not like is boring and simple constraints. Katya is fed up with all those "*N* does not exceed a thousand" and "the sum of *a**i* does not exceed a million" and she decided to come up with something a little more complicated. The last problem written by Katya deals with strings. The input is a string of small Latin letters. To make the statement longer and strike terror into the people who will solve the contest, Katya came up with the following set of *k* restrictions of the same type (characters in restrictions can be repeated and some restrictions may contradict each other): - The number of characters *c*1 in a string is not less than *l*1 and not more than *r*1. - ... - The number of characters *c**i* in a string is not less than *l**i* and not more than *r**i*. - ... - The number of characters *c**k* in a string is not less than *l**k* and not more than *r**k*. However, having decided that it is too simple and obvious, Katya added the following condition: a string meets no less than *L* and not more than *R* constraints from the above given list. Katya does not like to compose difficult and mean tests, so she just took a big string *s* and wants to add to the tests all its substrings that meet the constraints. However, Katya got lost in her conditions and asked you to count the number of substrings of the string *s* that meet the conditions (each occurrence of the substring is counted separately).
The first line contains a non-empty string *s*, consisting of small Latin letters. The length of the string *s* does not exceed 105. The second line contains three space-separated integers *k*, *L* and *R* (0<=≀<=*L*<=≀<=*R*<=≀<=*k*<=≀<=500). Next *k* lines contain Katya's constrictions in the following form "*c**i* *l**i* *r**i*". All letters *c**i* are small Latin letters, *l**i* and *r**i* are integers (0<=≀<=*l**i*<=≀<=*r**i*<=≀<=|*s*|, where |*s*| is the length of string *s*). Letters *c**i* are not necessarily different.
Print a single number β€” the number of substrings that meet the constrictions. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cout stream or the %I64d specificator.
[ "codeforces\n2 0 0\no 1 2\ne 1 2\n", "codeforces\n2 1 1\no 1 2\no 1 2\n" ]
[ "7\n", "0\n" ]
In the first test we should count the number of strings that do not contain characters "e" and "o". All such strings are as follows (in the order of occurrence in the initial string from the left to the right): "c", "d"', "f", "r", "rc", "c", "s". In the second test we cannot achieve fulfilling exactly one of the two identical constrictions, so the answer is 0.
[]
124
0
0
50,827
727
Games on a CD
[ "data structures", "hashing", "string suffix structures", "strings" ]
null
null
Several years ago Tolya had *n* computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD in clockwise order. The names were distinct, the length of each name was equal to *k*. The names didn't overlap. Thus, there is a cyclic string of length *n*Β·*k* written on the CD. Several years have passed and now Tolya can't remember which games he burned to his CD. He knows that there were *g* popular games that days. All of the games he burned were among these *g* games, and no game was burned more than once. You have to restore any valid list of games Tolya could burn to the CD several years ago.
The first line of the input contains two positive integers *n* and *k* (1<=≀<=*n*<=≀<=105, 1<=≀<=*k*<=≀<=105)Β β€” the amount of games Tolya burned to the CD, and the length of each of the names. The second line of the input contains one string consisting of lowercase English lettersΒ β€” the string Tolya wrote on the CD, split in arbitrary place. The length of the string is *n*Β·*k*. It is guaranteed that the length is not greater than 106. The third line of the input contains one positive integer *g* (*n*<=≀<=*g*<=≀<=105)Β β€” the amount of popular games that could be written on the CD. It is guaranteed that the total length of names of all popular games is not greater than 2Β·106. Each of the next *g* lines contains a single stringΒ β€” the name of some popular game. Each name consists of lowercase English letters and has length *k*. It is guaranteed that the names are distinct.
If there is no answer, print "NO" (without quotes). Otherwise, print two lines. In the first line print "YES" (without quotes). In the second line, print *n* integersΒ β€” the games which names were written on the CD. You should print games in the order they could have been written on the CD, it means, in clockwise order. You can print games starting from any position. Remember, that no game was burned to the CD more than once. If there are several possible answers, print any of them.
[ "3 1\nabc\n4\nb\na\nc\nd\n", "4 2\naabbccdd\n4\ndd\nab\nbc\ncd\n" ]
[ "YES\n2 1 3 \n", "NO\n" ]
none
[ { "input": "3 1\nabc\n4\nb\na\nc\nd", "output": "YES\n2 1 3 " }, { "input": "4 2\naabbccdd\n4\ndd\nab\nbc\ncd", "output": "NO" }, { "input": "2 2\nkdcj\n4\ncj\nkd\njk\ndc", "output": "YES\n3 4 " }, { "input": "10 10\nlgfrjgityzwtmfyygmpsmokiwphewhpoelsvnctwxmpimqvblgrisozncsi...
46
0
0
50,865
961
Tufurama
[ "data structures" ]
null
null
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused β€” what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method. TV series have *n* seasons (numbered 1 through *n*), the *i*-th season has *a**i* episodes (numbered 1 through *a**i*). Polycarp thinks that if for some pair of integers *x* and *y* (*x*<=&lt;<=*y*) exist both season *x* episode *y* and season *y* episode *x* then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
The first line contains one integer *n* (1<=<=≀<=*n*<=<=≀<=<=2Β·105) β€” the number of seasons. The second line contains *n* integers separated by space *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109) β€” number of episodes in each season.
Print one integer β€” the number of pairs *x* and *y* (*x*<=&lt;<=*y*) such that there exist both season *x* episode *y* and season *y* episode *x*.
[ "5\n1 2 3 4 5\n", "3\n8 12 7\n", "3\n3 2 1\n" ]
[ "0\n", "3\n", "2\n" ]
Possible pairs in the second example: 1. *x* = 1, *y* = 2 (season 1 episode 2 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 2 episode 1); 1. *x* = 2, *y* = 3 (season 2 episode 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 3 episode 2); 1. *x* = 1, *y* = 3 (season 1 episode 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 3 episode 1). In the third example: 1. *x* = 1, *y* = 2 (season 1 episode 2 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 2 episode 1); 1. *x* = 1, *y* = 3 (season 1 episode 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 3 episode 1).
[ { "input": "5\n1 2 3 4 5", "output": "0" }, { "input": "3\n8 12 7", "output": "3" }, { "input": "3\n3 2 1", "output": "2" }, { "input": "5\n2 3 4 5 6", "output": "4" }, { "input": "8\n7 2 6 6 5 1 4 9", "output": "9" }, { "input": "10\n1000000000 100000...
498
44,236,800
3
51,079
54
First Digit Law
[ "dp", "math", "probabilities" ]
C. First Digit Law
2
256
In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law). Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are *N* random variables, the *i*-th of which can take any integer value from some segment [*L**i*;*R**i*] (all numbers from this segment are equiprobable). It means that the value of the *i*-th quantity can be equal to any integer number from a given interval [*L**i*;*R**i*] with probability 1<=/<=(*R**i*<=-<=*L**i*<=+<=1). The Hedgehog wants to know the probability of the event that the first digits of at least *K*% of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD β€” most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least *K* per cent of those *N* values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one.
The first line contains number *N* which is the number of random variables (1<=≀<=*N*<=≀<=1000). Then follow *N* lines containing pairs of numbers *L**i*,<=*R**i*, each of whom is a description of a random variable. It is guaranteed that 1<=≀<=*L**i*<=≀<=*R**i*<=≀<=1018. The last line contains an integer *K* (0<=≀<=*K*<=≀<=100). All the numbers in the input file are integers. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Print the required probability. Print the fractional number with such a precision that the relative or absolute error of the result won't exceed 10<=-<=9.
[ "1\n1 2\n50\n", "2\n1 2\n9 11\n50\n" ]
[ "0.500000000000000", "0.833333333333333" ]
none
[ { "input": "1\n1 2\n50", "output": "0.500000000000000" }, { "input": "2\n1 2\n9 11\n50", "output": "0.833333333333333" }, { "input": "3\n2 9\n20 99\n5 5\n0", "output": "1.000000000000000" }, { "input": "3\n2 9\n20 99\n5 5\n100", "output": "0.000000000000000" }, { ...
748
409,600
0
51,162
913
Don't Exceed
[ "math", "probabilities" ]
null
null
You generate real numbers *s*1,<=*s*2,<=...,<=*s**n* as follows: - *s*0<==<=0; - *s**i*<==<=*s**i*<=-<=1<=+<=*t**i*, where *t**i* is a real number chosen independently uniformly at random between 0 and 1, inclusive. You are given real numbers *x*1,<=*x*2,<=...,<=*x**n*. You are interested in the probability that *s**i*<=≀<=*x**i* is true for all *i* simultaneously. It can be shown that this can be represented as , where *P* and *Q* are coprime integers, and . Print the value of *P*Β·*Q*<=-<=1 modulo 998244353.
The first line contains integer *n* (1<=≀<=*n*<=≀<=30). The next *n* lines contain real numbers *x*1,<=*x*2,<=...,<=*x**n*, given with at most six digits after the decimal point (0<=&lt;<=*x**i*<=≀<=*n*).
Print a single integer, the answer to the problem.
[ "4\n1.00\n2\n3.000000\n4.0\n", "1\n0.50216\n", "2\n0.5\n1.0\n", "6\n0.77\n1.234567\n2.1\n1.890\n2.9999\n3.77\n" ]
[ "1\n", "342677322\n", "623902721\n", "859831967\n" ]
In the first example, the sought probability is 1 since the sum of *i* real numbers which don't exceed 1 doesn't exceed *i*. In the second example, the probability is *x*<sub class="lower-index">1</sub> itself. In the third example, the sought probability is 3 / 8.
[]
46
0
0
51,206
45
Prime Problem
[ "number theory" ]
G. Prime Problem
1
256
In Berland prime numbers are fashionable β€” the respectable citizens dwell only on the floors with numbers that are prime numbers. The numismatists value particularly high the coins with prime nominal values. All the prime days are announced holidays! Yet even this is not enough to make the Berland people happy. On the main street of the capital stand *n* houses, numbered from 1 to *n*. The government decided to paint every house a color so that the sum of the numbers of the houses painted every color is a prime number. However it turned out that not all the citizens approve of this decision β€” many of them protest because they don't want many colored houses on the capital's main street. That's why it is decided to use the minimal possible number of colors. The houses don't have to be painted consecutively, but every one of *n* houses should be painted some color. The one-colored houses should not stand consecutively, any way of painting is acceptable. There are no more than 5 hours left before the start of painting, help the government find the way when the sum of house numbers for every color is a prime number and the number of used colors is minimal.
The single input line contains an integer *n* (2<=≀<=*n*<=≀<=6000) β€” the number of houses on the main streets of the capital.
Print the sequence of *n* numbers, where the *i*-th number stands for the number of color for house number *i*. Number the colors consecutively starting from 1. Any painting order is allowed. If there are several solutions to that problem, print any of them. If there's no such way of painting print the single number -1.
[ "8" ]
[ "1 2 2 1 1 1 1 2" ]
none
[ { "input": "8", "output": "1 1 1 1 2 1 1 1 " }, { "input": "2", "output": "1 1 " }, { "input": "3", "output": "1 1 2 " }, { "input": "4", "output": "1 1 2 1 " }, { "input": "5", "output": "1 2 1 1 1 " }, { "input": "6", "output": "1 2 1 1 1 1 " }...
154
11,468,800
0
51,354
215
Crosses
[ "brute force", "implementation" ]
null
null
There is a board with a grid consisting of *n* rows and *m* columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number *i* and column number *j* as (*i*,<=*j*). A group of six numbers (*a*,<=*b*,<=*c*,<=*d*,<=*x*0,<=*y*0), where 0<=≀<=*a*,<=*b*,<=*c*,<=*d*, is a cross, and there is a set of cells that are assigned to it. Cell (*x*,<=*y*) belongs to this set if at least one of two conditions are fulfilled: - |*x*0<=-<=*x*|<=≀<=*a* and |*y*0<=-<=*y*|<=≀<=*b* - |*x*0<=-<=*x*|<=≀<=*c* and |*y*0<=-<=*y*|<=≀<=*d* Your task is to find the number of different groups of six numbers, (*a*,<=*b*,<=*c*,<=*d*,<=*x*0,<=*y*0) that determine the crosses of an area equal to *s*, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell (*x*,<=*y*) of the cross 1<=≀<=*x*<=≀<=*n*;Β 1<=≀<=*y*<=≀<=*m* holds). The area of the cross is the number of cells it has. Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.
The input consists of a single line containing three integers *n*, *m* and *s* (1<=≀<=*n*,<=*m*<=≀<=500, 1<=≀<=*s*<=≀<=*n*Β·*m*). The integers are separated by a space.
Print a single integer β€” the number of distinct groups of six integers that denote crosses with area *s* and that are fully placed on the *n*<=Γ—<=*m* grid. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "2 2 1\n", "3 4 5\n" ]
[ "4\n", "4\n" ]
In the first sample the sought groups of six numbers are: (0, 0, 0, 0, 1, 1), (0, 0, 0, 0, 1, 2), (0, 0, 0, 0, 2, 1), (0, 0, 0, 0, 2, 2). In the second sample the sought groups of six numbers are: (0, 1, 1, 0, 2, 2), (0, 1, 1, 0, 2, 3), (1, 0, 0, 1, 2, 2), (1, 0, 0, 1, 2, 3).
[ { "input": "2 2 1", "output": "4" }, { "input": "3 4 5", "output": "4" }, { "input": "2 2 3", "output": "0" }, { "input": "5 1 3", "output": "9" }, { "input": "9 7 55", "output": "4" }, { "input": "5 10 25", "output": "102" }, { "input": "2...
122
0
0
51,366
903
Swapping Characters
[ "brute force", "hashing", "implementation", "strings" ]
null
null
We had a string *s* consisting of *n* lowercase Latin letters. We made *k* copies of this string, thus obtaining *k* identical strings *s*1,<=*s*2,<=...,<=*s**k*. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string). You are given *k* strings *s*1,<=*s*2,<=...,<=*s**k*, and you have to restore any string *s* so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, *k*Β·*n*<=≀<=5000).
The first line contains two integers *k* and *n* (1<=≀<=*k*<=≀<=2500,<=2<=≀<=*n*<=≀<=5000,<=*k*Β Β·Β *n*<=≀<=5000) β€” the number of strings we obtained, and the length of each of these strings. Next *k* lines contain the strings *s*1,<=*s*2,<=...,<=*s**k*, each consisting of exactly *n* lowercase Latin letters.
Print any suitable string *s*, or -1 if such string doesn't exist.
[ "3 4\nabac\ncaab\nacba\n", "3 4\nkbbu\nkbub\nubkb\n", "5 4\nabcd\ndcba\nacbd\ndbca\nzzzz\n" ]
[ "acab\n", "kbub\n", "-1\n" ]
In the first example *s*<sub class="lower-index">1</sub> is obtained by swapping the second and the fourth character in acab, *s*<sub class="lower-index">2</sub> is obtained by swapping the first and the second character, and to get *s*<sub class="lower-index">3</sub>, we swap the third and the fourth character. In the second example *s*<sub class="lower-index">1</sub> is obtained by swapping the third and the fourth character in kbub, *s*<sub class="lower-index">2</sub> β€” by swapping the second and the fourth, and *s*<sub class="lower-index">3</sub> β€” by swapping the first and the third. In the third example it's impossible to obtain given strings by aforementioned operations.
[ { "input": "3 4\nabac\ncaab\nacba", "output": "acab" }, { "input": "3 4\nkbbu\nkbub\nubkb", "output": "kbub" }, { "input": "5 4\nabcd\ndcba\nacbd\ndbca\nzzzz", "output": "-1" }, { "input": "3 2\nxh\nxh\nxh", "output": "hx" }, { "input": "3 4\nkbub\nkbbu\nubkb", ...
77
20,172,800
-1
51,369
19
Fairy
[ "dfs and similar", "divide and conquer", "dsu" ]
E. Fairy
1
256
Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper *n* points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.
The first input line contains two integer numbers: *n* β€” amount of the drawn points and *m* β€” amount of the drawn segments (1<=≀<=*n*<=≀<=104,<=0<=≀<=*m*<=≀<=104). The following *m* lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers *v*, *u* (1<=≀<=*v*<=≀<=*n*,<=1<=≀<=*u*<=≀<=*n*) β€” indexes of the points, joined by this segment. No segment is met in the description twice.
In the first line output number *k* β€” amount of the segments in the answer. In the second line output *k* space-separated numbers β€” indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order.
[ "4 4\n1 2\n1 3\n2 4\n3 4\n", "4 5\n1 2\n2 3\n3 4\n4 1\n1 3\n" ]
[ "4\n1 2 3 4 ", "1\n5 " ]
none
[]
60
0
0
51,374
618
Double Knapsack
[ "constructive algorithms", "two pointers" ]
null
null
You are given two multisets *A* and *B*. Each multiset has exactly *n* integers each between 1 and *n* inclusive. Multisets may contain multiple copies of the same number. You would like to find a nonempty subset of *A* and a nonempty subset of *B* such that the sum of elements in these subsets are equal. Subsets are also multisets, i.e. they can contain elements with equal values. If no solution exists, print <=-<=1. Otherwise, print the indices of elements in any such subsets of *A* and *B* that have the same sum.
The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=1<=000<=000)Β β€” the size of both multisets. The second line contains *n* integers, denoting the elements of *A*. Each element will be between 1 and *n* inclusive. The third line contains *n* integers, denoting the elements of *B*. Each element will be between 1 and *n* inclusive.
If there is no solution, print a single integer <=-<=1. Otherwise, your solution should be printed on four lines. The first line should contain a single integer *k**a*, the size of the corresponding subset of *A*. The second line should contain *k**a* distinct integers, the indices of the subset of *A*. The third line should contain a single integer *k**b*, the size of the corresponding subset of *B*. The fourth line should contain *k**b* distinct integers, the indices of the subset of *B*. Elements in both sets are numbered from 1 to *n*. If there are multiple possible solutions, print any of them.
[ "10\n10 10 10 10 10 10 10 10 10 10\n10 9 8 7 6 5 4 3 2 1\n", "5\n4 4 3 3 3\n2 2 2 2 5\n" ]
[ "1\n2\n3\n5 8 10\n", "2\n2 3\n2\n3 5\n" ]
none
[ { "input": "10\n10 10 10 10 10 10 10 10 10 10\n10 9 8 7 6 5 4 3 2 1", "output": "1\n2\n3\n5 8 10" }, { "input": "5\n4 4 3 3 3\n2 2 2 2 5", "output": "2\n2 3\n2\n3 5" } ]
2,500
198,553,600
0
51,466
135
Zero-One
[ "constructive algorithms", "games", "greedy" ]
null
null
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him. Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it. An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.
Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).
[ "????\n", "1010\n", "1?1\n" ]
[ "00\n01\n10\n11\n", "10\n", "01\n11\n" ]
In the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes. In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end.
[ { "input": "????", "output": "00\n01\n10\n11" }, { "input": "1010", "output": "10" }, { "input": "1?1", "output": "01\n11" }, { "input": "111?", "output": "11" }, { "input": "000?", "output": "00" }, { "input": "1??1?", "output": "00\n01\n10\n11" ...
186
0
0
51,477
796
Bank Hacking
[ "constructive algorithms", "data structures", "dp", "trees" ]
null
null
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are *n* banks, numbered from 1 to *n*. There are also *n*<=-<=1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank *i* has initial strength *a**i*. Let us define some keywords before we proceed. Bank *i* and bank *j* are neighboring if and only if there exists a wire directly connecting them. Bank *i* and bank *j* are semi-neighboring if and only if there exists an online bank *k* such that bank *i* and bank *k* are neighboring and bank *k* and bank *j* are neighboring. When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1. To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank *x* if and only if all these conditions are met: 1. Bank *x* is online. That is, bank *x* is not hacked yet. 1. Bank *x* is neighboring to some offline bank. 1. The strength of bank *x* is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
The first line contains one integer *n* (1<=≀<=*n*<=≀<=3Β·105)Β β€” the total number of banks. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≀<=*a**i*<=≀<=109)Β β€” the strengths of the banks. Each of the next *n*<=-<=1 lines contains two integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*, *u**i*<=β‰ <=*v**i*)Β β€” meaning that there is a wire directly connecting banks *u**i* and *v**i*. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
Print one integerΒ β€” the minimum strength of the computer Inzane needs to accomplish the goal.
[ "5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5\n", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6\n", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4\n" ]
[ "5", "93", "8" ]
In the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: - Initially, strengths of the banks are [1, 2, 3, 4, 5]. - He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. - He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. - He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. - He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. - He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
[ { "input": "5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "output": "5" }, { "input": "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "output": "93" }, { "input": "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4", "output": "8" }, { "input": "3\n2 2 2\n3 2\n1 2", "output": "3" }, { ...
62
0
0
51,632
110
Lucky String
[ "constructive algorithms", "strings" ]
B. Lucky String
2
256
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: - b: 2- c: 3,<=10- d: 4,<=8- e: 6- f: 7- z: 1,<=5,<=9- Lists of positions of letters a, g, h, ..., y are empty. This string is lucky as all differences are lucky numbers. For letters z: 5<=-<=1<==<=4, 9<=-<=5<==<=4, for letters c: 10<=-<=3<==<=7, for letters d: 8<=-<=4<==<=4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky. Find the lexicographically minimal lucky string whose length equals *n*.
The single line contains a positive integer *n* (1<=≀<=*n*<=≀<=105) β€” the length of the sought string.
Print on the single line the lexicographically minimal lucky string whose length equals *n*.
[ "5\n", "3\n" ]
[ "abcda\n", "abc\n" ]
The lexical comparison of strings is performed by the &lt; operator in modern programming languages. String *a* is lexicographically less than string *b* if exists such *i* (1 ≀ *i* ≀ *n*), that *a*<sub class="lower-index">*i*</sub> &lt; *b*<sub class="lower-index">*i*</sub>, and for any *j* (1 ≀ *j* &lt; *i*) *a*<sub class="lower-index">*j*</sub> = *b*<sub class="lower-index">*j*</sub>.
[ { "input": "5", "output": "abcda" }, { "input": "3", "output": "abc" }, { "input": "8", "output": "abcdabcd" }, { "input": "10", "output": "abcdabcdab" }, { "input": "16", "output": "abcdabcdabcdabcd" }, { "input": "64", "output": "abcdabcdabcdabcd...
124
819,200
3.967474
51,715
97
Leaders
[ "dfs and similar", "dsu", "graphs", "trees" ]
E. Leaders
2
256
After a revolution in Berland the new dictator faced an unexpected challenge: the country has to be somehow ruled. The dictator is a very efficient manager, yet he can't personally give orders to each and every citizen. That's why he decided to pick some set of leaders he would control. Those leaders will directly order the citizens. However, leadership efficiency turned out to vary from person to person (i.e. while person A makes an efficient leader, person B may not be that good at it). That's why the dictator asked world-famous berland scientists for help. The scientists suggested an innovatory technology β€” to make the leaders work in pairs. A relationship graph is some undirected graph whose vertices correspond to people. A simple path is a path with no repeated vertices. Long and frighteningly expensive research showed that a pair of people has maximum leadership qualities if a graph of relationships has a simple path between them with an odd number of edges. The scientists decided to call such pairs of different people leader pairs. Secret services provided the scientists with the relationship graph so that the task is simple β€” we have to learn to tell the dictator whether the given pairs are leader pairs or not. Help the scientists cope with the task.
The first line contains integers *n* and *m* (1<=≀<=*n*<=≀<=105,<=0<=≀<=*m*<=≀<=105) β€” the number of vertices and edges in the relationship graph correspondingly. Next *m* lines contain pairs of integers *a* and *b* which mean that there is an edge between the *a*-th and the *b*-th vertices (the vertices are numbered starting from 1, 1<=≀<=*a*,<=*b*<=≀<=*n*). It is guaranteed that the graph has no loops or multiple edges. Next line contains number *q* (1<=≀<=*q*<=≀<=105) β€” the number of pairs the scientists are interested in. Next *q* lines contain these pairs (in the same format as the edges, the queries can be repeated, a query can contain a pair of the identical vertices).
For each query print on a single line "Yes" if there's a simple odd path between the pair of people; otherwise, print "No".
[ "7 7\n1 3\n1 4\n2 3\n2 4\n5 6\n6 7\n7 5\n8\n1 2\n1 3\n1 4\n2 4\n1 5\n5 6\n5 7\n6 7\n" ]
[ "No\nYes\nYes\nYes\nNo\nYes\nYes\nYes\n" ]
Notes to the samples: 1) Between vertices 1 and 2 there are 2 different simple paths in total: 1-3-2 and 1-4-2. Both of them consist of an even number of edges. 2) Vertices 1 and 3 are connected by an edge, that's why a simple odd path for them is 1-3. 5) Vertices 1 and 5 are located in different connected components, there's no path between them.
[]
92
0
0
51,862
164
Variable, or There and Back Again
[ "dfs and similar", "graphs" ]
null
null
Life is not easy for the perfectly common variable named Vasya. Wherever it goes, it is either assigned a value, or simply ignored, or is being used! Vasya's life goes in states of a program. In each state, Vasya can either be used (for example, to calculate the value of another variable), or be assigned a value, or ignored. Between some states are directed (oriented) transitions. A path is a sequence of states *v*1,<=*v*2,<=...,<=*v**x*, where for any 1<=≀<=*i*<=&lt;<=*x* exists a transition from *v**i* to *v**i*<=+<=1. Vasya's value in state *v* is interesting to the world, if exists path *p*1,<=*p*2,<=...,<=*p**k* such, that *p**i*<==<=*v* for some *i* (1<=≀<=*i*<=≀<=*k*), in state *p*1 Vasya gets assigned a value, in state *p**k* Vasya is used and there is no state *p**i* (except for *p*1) where Vasya gets assigned a value. Help Vasya, find the states in which Vasya's value is interesting to the world.
The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=105) β€” the numbers of states and transitions, correspondingly. The second line contains space-separated *n* integers *f*1,<=*f*2,<=...,<=*f**n* (0<=≀<=*f**i*<=≀<=2), *f**i* described actions performed upon Vasya in state *i*: 0 represents ignoring, 1 β€” assigning a value, 2 β€” using. Next *m* lines contain space-separated pairs of integers *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, *a**i*<=β‰ <=*b**i*), each pair represents the transition from the state number *a**i* to the state number *b**i*. Between two states can be any number of transitions.
Print *n* integers *r*1,<=*r*2,<=...,<=*r**n*, separated by spaces or new lines. Number *r**i* should equal 1, if Vasya's value in state *i* is interesting to the world and otherwise, it should equal 0. The states are numbered from 1 to *n* in the order, in which they are described in the input.
[ "4 3\n1 0 0 2\n1 2\n2 3\n3 4\n", "3 1\n1 0 2\n1 3\n", "3 1\n2 0 1\n1 3\n" ]
[ "1\n1\n1\n1\n", "1\n0\n1\n", "0\n0\n0\n" ]
In the first sample the program states can be used to make the only path in which the value of Vasya interests the world, 1 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 2 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 4; it includes all the states, so in all of them Vasya's value is interesting to the world. The second sample the only path in which Vasya's value is interesting to the world is , β€” 1 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> 3; state 2 is not included there. In the third sample we cannot make from the states any path in which the value of Vasya would be interesting to the world, so the value of Vasya is never interesting to the world.
[ { "input": "4 3\n1 0 0 2\n1 2\n2 3\n3 4", "output": "1\n1\n1\n1" }, { "input": "3 1\n1 0 2\n1 3", "output": "1\n0\n1" }, { "input": "3 1\n2 0 1\n1 3", "output": "0\n0\n0" }, { "input": "4 4\n1 0 2 0\n1 2\n2 3\n3 4\n4 1", "output": "1\n1\n1\n0" }, { "input": "2 1\n...
248
614,400
0
51,874