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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
91 | Igloo Skyscraper | [
"data structures",
"geometry"
] | E. Igloo Skyscraper | 3 | 256 | Today the North Pole hosts an Olympiad in a sport called... toy igloo skyscrapers' building!
There are *n* walruses taking part in the contest. Each walrus is given a unique number from 1 to *n*. After start each walrus begins to build his own igloo skyscraper. Initially, at the moment of time equal to 0, the height of the skyscraper *i*-th walrus is equal to *a**i*. Each minute the *i*-th walrus finishes building *b**i* floors.
The journalists that are reporting from the spot where the Olympiad is taking place, make *q* queries to the organizers. Each query is characterized by a group of three numbers *l**i*, *r**i*, *t**i*. The organizers respond to each query with a number *x*, such that:
1. Number *x* lies on the interval from *l**i* to *r**i* inclusive (*l**i*<=β€<=*x*<=β€<=*r**i*).
2. The skyscraper of the walrus number *x* possesses the maximum height among the skyscrapers of all walruses from the interval [*l**i*,<=*r**i*] at the moment of time *t**i*.
For each journalists' query print the number of the walrus *x* that meets the above-given criteria. If there are several possible answers, print any of them. | The first line contains numbers *n* and *q* (1<=β€<=*n*,<=*q*<=β€<=105). Next *n* lines contain pairs of numbers *a**i*, *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=109). Then follow *q* queries i the following format *l**i*, *r**i*, *t**i*, one per each line (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*, 0<=β€<=*t**i*<=β€<=106). All input numbers are integers. | For each journalists' query print the number of the walrus *x* that meets the criteria, given in the statement. Print one number per line. | [
"5 4\n4 1\n3 5\n6 2\n3 5\n6 5\n1 5 2\n1 3 5\n1 1 0\n1 5 0\n",
"5 4\n6 1\n5 1\n2 5\n4 3\n6 1\n2 4 1\n3 4 5\n1 4 5\n1 2 0\n"
] | [
"5\n2\n1\n5\n",
"3\n3\n3\n1\n"
] | none | [] | 0 | 0 | -1 | 97,320 |
435 | Special Grid | [
"brute force",
"dp",
"greedy"
] | null | null | You are given an *n*<=Γ<=*m* grid, some of its nodes are black, the others are white. Moreover, it's not an ordinary grid β each unit square of the grid has painted diagonals.
The figure below is an example of such grid of size 3<=Γ<=5. Four nodes of this grid are black, the other 11 nodes are white.
Your task is to count the number of such triangles on the given grid that:
- the corners match the white nodes, and the area is positive; - all sides go along the grid lines (horizontal, vertical or diagonal); - no side contains black nodes. | The first line contains two integers *n* and *m* (2<=β€<=*n*,<=*m*<=β€<=400). Each of the following *n* lines contain *m* characters (zeros and ones) β the description of the grid. If the *j*-th character in the *i*-th line equals zero, then the node on the *i*-th horizontal line and on the *j*-th vertical line is painted white. Otherwise, the node is painted black.
The horizontal lines are numbered starting from one from top to bottom, the vertical lines are numbered starting from one from left to right. | Print a single integer β the number of required triangles. | [
"3 5\n10000\n10010\n00001\n",
"2 2\n00\n00\n",
"2 2\n11\n11\n"
] | [
"20\n",
"4\n",
"0\n"
] | The figure below shows red and blue triangles. They are the examples of the required triangles in the first sample. One of the invalid triangles is painted green. It is invalid because not all sides go along the grid lines. | [
{
"input": "3 5\n10000\n10010\n00001",
"output": "20"
},
{
"input": "2 2\n00\n00",
"output": "4"
},
{
"input": "2 2\n11\n11",
"output": "0"
},
{
"input": "10 10\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n000000... | 30 | 0 | 0 | 97,343 | |
593 | Happy Tree Party | [
"data structures",
"dfs and similar",
"graphs",
"math",
"trees"
] | null | null | Bogdan has a birthday today and mom gave him a tree consisting of *n* vertecies. For every edge of the tree *i*, some number *x**i* was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, *m* guests consecutively come to Bogdan's party. When the *i*-th guest comes, he performs exactly one of the two possible operations:
1. Chooses some number *y**i*, and two vertecies *a**i* and *b**i*. After that, he moves along the edges of the tree from vertex *a**i* to vertex *b**i* using the shortest path (of course, such a path is unique in the tree). Every time he moves along some edge *j*, he replaces his current number *y**i* by , that is, by the result of integer division *y**i* div *x**j*. 1. Chooses some edge *p**i* and replaces the value written in it *x**p**i* by some positive integer *c**i*<=<<=*x**p**i*.
As Bogdan cares about his guests, he decided to ease the process. Write a program that performs all the operations requested by guests and outputs the resulting value *y**i* for each *i* of the first type. | The first line of the input contains integers, *n* and *m* (2<=β€<=*n*<=β€<=200<=000, 1<=β€<=*m*<=β€<=200<=000)Β β the number of vertecies in the tree granted to Bogdan by his mom and the number of guests that came to the party respectively.
Next *n*<=-<=1 lines contain the description of the edges. The *i*-th of these lines contains three integers *u**i*, *v**i* and *x**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*, *u**i*<=β <=*v**i*, 1<=β€<=*x**i*<=β€<=1018), denoting an edge that connects vertecies *u**i* and *v**i*, with the number *x**i* initially written on it.
The following *m* lines describe operations, requested by Bogdan's guests. Each description contains three or four integers and has one of the two possible forms:
- 1 *a**i* *b**i* *y**i* corresponds to a guest, who chooses the operation of the first type. - 2 *p**i* *c**i* corresponds to a guests, who chooses the operation of the second type. | For each guest who chooses the operation of the first type, print the result of processing the value *y**i* through the path from *a**i* to *b**i*. | [
"6 6\n1 2 1\n1 3 7\n1 4 4\n2 5 5\n2 6 2\n1 4 6 17\n2 3 2\n1 4 6 17\n1 5 5 20\n2 4 1\n1 5 1 3\n",
"5 4\n1 2 7\n1 3 3\n3 4 2\n3 5 5\n1 4 2 100\n1 5 4 1\n2 2 2\n1 1 3 4\n"
] | [
"2\n4\n20\n3\n",
"2\n0\n2\n"
] | Initially the tree looks like this:
The response to the first query is: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5d118e070291dffa2524a35d044ed59aa2446202.png" style="max-width: 100.0%;max-height: 100.0%;"/> = 2
After the third edge is changed, the tree looks like this:
The response to the second query is: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e174ec48fc18590923a6011f38f9725ace276d6b.png" style="max-width: 100.0%;max-height: 100.0%;"/> = 4
In the third query the initial and final vertex coincide, that is, the answer will be the initial number 20.
After the change in the fourth edge the tree looks like this:
In the last query the answer will be: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9e2fd5e66c04846639323b74047d246292d6d487.png" style="max-width: 100.0%;max-height: 100.0%;"/> = 3 | [
{
"input": "6 6\n1 2 1\n1 3 7\n1 4 4\n2 5 5\n2 6 2\n1 4 6 17\n2 3 2\n1 4 6 17\n1 5 5 20\n2 4 1\n1 5 1 3",
"output": "2\n4\n20\n3"
},
{
"input": "5 4\n1 2 7\n1 3 3\n3 4 2\n3 5 5\n1 4 2 100\n1 5 4 1\n2 2 2\n1 1 3 4",
"output": "2\n0\n2"
},
{
"input": "2 1\n1 2 1\n1 2 1 1",
"output": "1... | 3,000 | 134,041,600 | 0 | 97,352 | |
212 | Polycarpus is Looking for Good Substrings | [
"bitmasks",
"hashing",
"implementation"
] | null | null | We'll call string *s*[*a*,<=*b*]<==<=*s**a**s**a*<=+<=1... *s**b* (1<=β€<=*a*<=β€<=*b*<=β€<=|*s*|) a substring of string *s*<==<=*s*1*s*2... *s*|*s*|, where |*s*| is the length of string *s*.
The trace of a non-empty string *t* is a set of characters that the string consists of. For example, the trace of string "aab" equals {'a', 'b'}.
Let's consider an arbitrary string *s* and the set of its substrings with trace equal to *C*. We will denote the number of substrings from this set that are maximal by inclusion by *r*(*C*,<=*s*). Substring *s*[*a*,<=*b*] of length *n*<==<=*b*<=-<=*a*<=+<=1 belonging to some set is called maximal by inclusion, if there is no substring *s*[*x*,<=*y*] in this set with length greater than *n*, such that 1<=β€<=*x*<=β€<=*a*<=β€<=*b*<=β€<=*y*<=β€<=|*s*|. Two substrings of string *s* are considered different even if they are equal but they are located at different positions of *s*.
Polycarpus got a challenging practical task on a stringology exam. He must do the following: given string *s* and non-empty sets of characters *C*1, *C*2, ..., *C**m*, find *r*(*C**i*,<=*s*) for each set *C**i*. Help Polycarpus to solve the problem as he really doesn't want to be expelled from the university and go to the army! | The first line contains a non-empty string *s* (1<=β€<=|*s*|<=β€<=106).
The second line contains a single integer *m* (1<=β€<=*m*<=β€<=104). Next *m* lines contain descriptions of sets *C**i*. The *i*-th line contains string *c**i* such that its trace equals *C**i*. It is guaranteed that all characters of each string *c**i* are different.
Note that *C**i* are not necessarily different. All given strings consist of lowercase English letters. | Print *m* integers β the *i*-th integer must equal *r*(*C**i*,<=*s*). | [
"aaaaa\n2\na\na\n",
"abacaba\n3\nac\nba\na\n"
] | [
"1\n1\n",
"1\n2\n4\n"
] | none | [] | 528 | 268,390,400 | 0 | 97,456 | |
290 | HQ | [
"*special",
"constructive algorithms"
] | null | null | The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset β a language called HQ... | The only line of the input is a string between 1 and 106 characters long. | Output "Yes" or "No". | [
"HHHH\n",
"HQHQH\n",
"HHQHHQH\n",
"HHQQHHQQHH\n"
] | [
"Yes\n",
"No\n",
"No\n",
"Yes\n"
] | The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience. | [
{
"input": "HHHH",
"output": "Yes"
},
{
"input": "HQHQH",
"output": "No"
},
{
"input": "HHQHHQH",
"output": "No"
},
{
"input": "HHQQHHQQHH",
"output": "Yes"
},
{
"input": "Q",
"output": "Yes"
},
{
"input": "HHHHHHHHHHQHHH",
"output": "No"
},
{
... | 60 | 204,800 | 0 | 97,517 | |
533 | Correcting Mistakes | [
"constructive algorithms",
"dp",
"greedy",
"hashing",
"strings",
"two pointers"
] | null | null | Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.
Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.
Implement a program that can, given two distinct words *S* and *T* of the same length *n* determine how many words *W* of length *n*<=+<=1 are there with such property that you can transform *W* into both *S*, and *T* by deleting exactly one character. Words *S* and *T* consist of lowercase English letters. Word *W* also should consist of lowercase English letters. | The first line contains integer *n* (1<=β€<=*n*<=β€<=100<=000) β the length of words *S* and *T*.
The second line contains word *S*.
The third line contains word *T*.
Words *S* and *T* consist of lowercase English letters. It is guaranteed that *S* and *T* are distinct words. | Print a single integer β the number of distinct words *W* that can be transformed to *S* and *T* due to a typo. | [
"7\nreading\ntrading\n",
"5\nsweet\nsheep\n",
"3\ntoy\ntry\n"
] | [
"1\n",
"0\n",
"2\n"
] | In the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).
In the second sample test the two given words couldn't be obtained from the same word by removing one letter.
In the third sample test the two given words could be obtained from either word "tory" or word "troy". | [
{
"input": "7\nreading\ntrading",
"output": "1"
},
{
"input": "5\nsweet\nsheep",
"output": "0"
},
{
"input": "3\ntoy\ntry",
"output": "2"
},
{
"input": "5\nspare\nspars",
"output": "2"
},
{
"input": "1\na\nb",
"output": "2"
},
{
"input": "1\nz\ny",
... | 108 | 16,793,600 | 3 | 97,601 | |
0 | none | [
"none"
] | null | null | How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: *d*-sorting. This sorting is applied to the strings of length at least *d*, where *d* is some positive integer. The characters of the string are sorted in following manner: first come all the 0-th characters of the initial string, then the 1-st ones, then the 2-nd ones and so on, in the end go all the (*d*<=-<=1)-th characters of the initial string. By the *i*-th characters we mean all the character whose positions are exactly *i* modulo *d*. If two characters stand on the positions with the same remainder of integer division by *d*, their relative order after the sorting shouldn't be changed. The string is zero-indexed. For example, for string 'qwerty':
Its 1-sorting is the string 'qwerty' (all characters stand on 0 positions),
Its 2-sorting is the string 'qetwry' (characters 'q', 'e' and 't' stand on 0 positions and characters 'w', 'r' and 'y' are on 1 positions),
Its 3-sorting is the string 'qrwtey' (characters 'q' and 'r' stand on 0 positions, characters 'w' and 't' stand on 1 positions and characters 'e' and 'y' stand on 2 positions),
Its 4-sorting is the string 'qtwyer',
Its 5-sorting is the string 'qywert'.
You are given string *S* of length *n* and *m* shuffling operations of this string. Each shuffling operation accepts two integer arguments *k* and *d* and transforms string *S* as follows. For each *i* from 0 to *n*<=-<=*k* in the increasing order we apply the operation of *d*-sorting to the substring *S*[*i*..*i*<=+<=*k*<=-<=1]. Here *S*[*a*..*b*] represents a substring that consists of characters on positions from *a* to *b* inclusive.
After each shuffling operation you need to print string *S*. | The first line of the input contains a non-empty string *S* of length *n*, consisting of lowercase and uppercase English letters and digits from 0 to 9.
The second line of the input contains integer *m*Β β the number of shuffling operations (1<=β€<=*m*Β·*n*<=β€<=106).
Following *m* lines contain the descriptions of the operations consisting of two integers *k* and *d* (1<=β€<=*d*<=β€<=*k*<=β€<=*n*). | After each operation print the current state of string *S*. | [
"qwerty\n3\n4 2\n6 3\n5 2\n"
] | [
"qertwy\nqtewry\nqetyrw\n"
] | Here is detailed explanation of the sample. The first modification is executed with arguments *k*β=β4, *d*β=β2. That means that you need to apply 2-sorting for each substring of length 4 one by one moving from the left to the right. The string will transform in the following manner:
qwerty βββ qewrty βββ qerwty βββ qertwy
Thus, string *S* equals 'qertwy' at the end of first query.
The second modification is executed with arguments *k*β=β6, *d*β=β3. As a result of this operation the whole string *S* is replaced by its 3-sorting:
qertwy βββ qtewry
The third modification is executed with arguments *k*β=β5, *d*β=β2.
qtewry βββ qertwy βββ qetyrw | [] | 2,000 | 87,040,000 | 0 | 97,603 | |
490 | Chocolate | [
"brute force",
"dfs and similar",
"math",
"meet-in-the-middle",
"number theory"
] | null | null | Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is *a*1<=Γ<=*b*1 segments large and the second one is *a*2<=Γ<=*b*2 segments large.
Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares.
To make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following:
- he either breaks one bar exactly in half (vertically or horizontally) and eats exactly a half of the bar, - or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar.
In the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar.
Both variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is 16<=Γ<=23, then Polycarpus can chip off a half, but not a third. If the bar is 20<=Γ<=18, then Polycarpus can chip off both a half and a third. If the bar is 5<=Γ<=7, then Polycarpus cannot chip off a half nor a third.
What is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process. | The first line of the input contains integers *a*1,<=*b*1 (1<=β€<=*a*1,<=*b*1<=β€<=109) β the initial sizes of the first chocolate bar. The second line of the input contains integers *a*2,<=*b*2 (1<=β€<=*a*2,<=*b*2<=β€<=109) β the initial sizes of the second bar.
You can use the data of type int64 (in Pascal), long long (in Π‘++), long (in Java) to process large integers (exceeding 231<=-<=1). | In the first line print *m* β the sought minimum number of minutes. In the second and third line print the possible sizes of the bars after they are leveled in *m* minutes. Print the sizes using the format identical to the input format. Print the sizes (the numbers in the printed pairs) in any order. The second line must correspond to the first bar and the third line must correspond to the second bar. If there are multiple solutions, print any of them.
If there is no solution, print a single line with integer -1. | [
"2 6\n2 3\n",
"36 5\n10 16\n",
"3 5\n2 1\n"
] | [
"1\n1 6\n2 3\n",
"3\n16 5\n5 16\n",
"-1\n"
] | none | [
{
"input": "2 6\n2 3",
"output": "1\n1 6\n2 3"
},
{
"input": "36 5\n10 16",
"output": "3\n16 5\n5 16"
},
{
"input": "3 5\n2 1",
"output": "-1"
},
{
"input": "36 5\n10 12",
"output": "1\n24 5\n10 12"
},
{
"input": "1 1\n1 1",
"output": "0\n1 1\n1 1"
},
{
... | 46 | 0 | 0 | 98,021 | |
901 | Weighting a Tree | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | null | null | You are given a connected undirected graph with *n* vertices and *m* edges. The vertices are enumerated from 1 to *n*.
You are given *n* integers *c*1,<=*c*2,<=...,<=*c**n*, each of them is between <=-<=*n* and *n*, inclusive. It is also guaranteed that the parity of *c**v* equals the parity of degree of vertex *v*. The degree of a vertex is the number of edges connected to it.
You are to write a weight between <=-<=2Β·*n*2 and 2Β·*n*2 (inclusive) on each edge in such a way, that for each vertex *v* the sum of weights on edges connected to this vertex is equal to *c**v*, or determine that this is impossible. | The first line contains two integers *n* and *m* (2<=β€<=*n*<=β€<=105, *n*<=-<=1<=β€<=*m*<=β€<=105)Β β the number of vertices and the number of edges.
The next line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (<=-<=*n*<=β€<=*c**i*<=β€<=*n*), where *c**i* is the required sum of weights of edges connected to vertex *i*. It is guaranteed that the parity of *c**i* equals the parity of degree of vertex *i*.
The next *m* lines describe edges of the graph. The *i*-th of these lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*; *a**i*<=β <=*b**i*), meaning that the *i*-th edge connects vertices *a**i* and *b**i*.
It is guaranteed that the given graph is connected and does not contain loops and multiple edges. | If there is no solution, print "NO".
Otherwise print "YES" and then *m* lines, the *i*-th of them is the weight of the *i*-th edge *w**i* (<=-<=2Β·*n*2<=β€<=*w**i*<=β€<=2Β·*n*2). | [
"3 3\n2 2 2\n1 2\n2 3\n1 3\n",
"4 3\n-1 0 2 1\n1 2\n2 3\n3 4\n",
"6 6\n3 5 5 5 1 5\n1 4\n3 2\n4 3\n4 5\n3 5\n5 6\n",
"4 4\n4 4 2 4\n1 2\n2 3\n3 4\n4 1\n"
] | [
"YES\n1\n1\n1\n",
"YES\n-1\n1\n1\n",
"YES\n3\n5\n3\n-1\n-3\n5\n",
"NO"
] | none | [
{
"input": "3 3\n2 2 2\n1 2\n2 3\n1 3",
"output": "YES\n1\n1\n1"
},
{
"input": "4 3\n-1 0 2 1\n1 2\n2 3\n3 4",
"output": "YES\n-1\n1\n1"
},
{
"input": "6 6\n3 5 5 5 1 5\n1 4\n3 2\n4 3\n4 5\n3 5\n5 6",
"output": "YES\n3\n5\n3\n-1\n-3\n5"
},
{
"input": "4 4\n4 4 2 4\n1 2\n2 3\n... | 0 | 0 | -1 | 98,196 | |
0 | none | [
"none"
] | null | null | Andrey's favourite number is *n*. Andrey's friends gave him two identical numbers *n* as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.
Given number *n*, can you find the two digit permutations that have this property? | The first line contains a positive integer *n* β the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes. | Print two permutations of digits of number *n*, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them. | [
"198\n",
"500\n"
] | [
"981\n819\n",
"500\n500\n"
] | none | [] | 30 | 0 | 0 | 98,352 | |
997 | Sky Full of Stars | [
"combinatorics",
"math"
] | null | null | On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game.
It is well known that one month on this planet consists of $n^2$ days, so calendars, represented as square matrix $n$ by $n$ are extremely popular.
Weather conditions are even more unusual. Due to the unique composition of the atmosphere, when interacting with sunlight, every day sky takes one of three colors: blue, green or red.
To play the bingo, you need to observe the sky for one monthΒ β after each day, its cell is painted with the color of the sky in that day, that is, blue, green or red.
At the end of the month, students examine the calendar. If at least one row or column contains only cells of one color, that month is called lucky.
Let's call two colorings of calendar different, if at least one cell has different colors in them. It is easy to see that there are $3^{n \cdot n}$ different colorings. How much of them are lucky? Since this number can be quite large, print it modulo $998244353$. | The first and only line of input contains a single integer $n$ ($1 \le n \le 1000\,000$)Β β the number of rows and columns in the calendar. | Print one numberΒ β number of lucky colorings of the calendar modulo $998244353$ | [
"1\n",
"2\n",
"3\n"
] | [
"3\n",
"63\n",
"9933\n"
] | In the first sample any coloring is lucky, since the only column contains cells of only one color.
In the second sample, there are a lot of lucky colorings, in particular, the following colorings are lucky:
While these colorings are not lucky: | [] | 358 | 716,800 | -1 | 98,386 | |
926 | Segments | [
"data structures"
] | null | null | There is a straight line colored in white. *n* black segments are added on it one by one.
After each segment is added, determine the number of connected components of black segments (i.Β e. the number of black segments in the union of the black segments).
In particular, if one segment ends in a point *x*, and another segment starts in the point *x*, these two segments belong to the same connected component. | The first line contains a single integer *n* (1<=β€<=*n*<=β€<=200<=000) β the number of segments.
The *i*-th of the next *n* lines contains two integers *l**i* and *r**i* (1<=β€<=*l**i*<=<<=*r**i*<=β€<=109) β the coordinates of the left and the right ends of the *i*-th segment. The segments are listed in the order they are added on the white line. | Print *n* integers β the number of connected components of black segments after each segment is added. | [
"3\n1 3\n4 5\n2 4\n",
"9\n10 20\n50 60\n30 40\n70 80\n90 100\n60 70\n10 40\n40 50\n80 90\n"
] | [
"1 2 1 \n",
"1 2 3 4 5 4 3 2 1 \n"
] | In the first example there are two components after the addition of the first two segments, because these segments do not intersect. The third added segment intersects the left segment and touches the right segment at the point 4 (these segments belong to the same component, according to the statements). Thus the number of connected components of black segments is equal to 1 after that. | [] | 46 | 0 | 0 | 98,572 | |
449 | Jzzhu and Numbers | [
"bitmasks",
"combinatorics",
"dp"
] | null | null | Jzzhu have *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. We will call a sequence of indexes *i*1,<=*i*2,<=...,<=*i**k* (1<=β€<=*i*1<=<<=*i*2<=<<=...<=<<=*i**k*<=β€<=*n*) a group of size *k*.
Jzzhu wonders, how many groups exists such that *a**i*1 & *a**i*2 & ... & *a**i**k*<==<=0 (1<=β€<=*k*<=β€<=*n*)? Help him and print this number modulo 1000000007 (109<=+<=7). Operation *x* & *y* denotes bitwise AND operation of two numbers. | The first line contains a single integer *n* (1<=β€<=*n*<=β€<=106). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=106). | Output a single integer representing the number of required groups modulo 1000000007 (109<=+<=7). | [
"3\n2 3 3\n",
"4\n0 1 2 3\n",
"6\n5 2 0 5 2 1\n"
] | [
"0\n",
"10\n",
"53\n"
] | none | [
{
"input": "3\n2 3 3",
"output": "0"
},
{
"input": "4\n0 1 2 3",
"output": "10"
},
{
"input": "6\n5 2 0 5 2 1",
"output": "53"
},
{
"input": "16\n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15",
"output": "64594"
},
{
"input": "10\n450661 128600 993228 725823 293549 33490 ... | 31 | 0 | -1 | 98,581 | |
0 | none | [
"none"
] | null | null | Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner.
Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislikes them; moreover, they often cause it indigestion! So, as a necessary precaution, Krakozyabra prefers to sort the digits of a number in non-descending order before proceeding to feast. Then, the leading zeros of the resulting number are eaten and the remaining part is discarded as an inedible tail.
For example, if Krakozyabra is to have the number 57040 for dinner, its inedible tail would be the number 457.
Slastyona is not really fond of the idea of Krakozyabra living in her castle. Hovewer, her natural hospitality prevents her from leaving her guest without food. Slastyona has a range of natural numbers from *L* to *R*, which she is going to feed the guest with. Help her determine how many distinct inedible tails are going to be discarded by Krakozyabra by the end of the dinner. | In the first and only string, the numbers *L* and *R* are givenΒ β the boundaries of the range (1<=β€<=*L*<=β€<=*R*<=β€<=1018). | Output the sole numberΒ β the answer for the problem. | [
"1 10\n",
"40 57\n",
"157 165\n"
] | [
"9\n",
"17\n",
"9\n"
] | In the first sample case, the inedible tails are the numbers from 1 to 9. Note that 10 and 1 have the same inedible tailΒ β the number 1.
In the second sample case, each number has a unique inedible tail, except for the pair 45,β54. The answer to this sample case is going to be (57β-β40β+β1)β-β1β=β17. | [] | 31 | 0 | 0 | 98,628 | |
732 | Exams | [
"binary search",
"greedy",
"sortings"
] | null | null | Vasiliy has an exam period which will continue for *n* days. He has to pass exams on *m* subjects. Subjects are numbered from 1 to *m*.
About every day we know exam for which one of *m* subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day.
On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest.
About each subject Vasiliy know a number *a**i*Β β the number of days he should prepare to pass the exam number *i*. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during *a**i* days for the exam number *i*. He can mix the order of preparation for exams in any way.
Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time. | The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=105)Β β the number of days in the exam period and the number of subjects.
The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (0<=β€<=*d**i*<=β€<=*m*), where *d**i* is the number of subject, the exam of which can be passed on the day number *i*. If *d**i* equals 0, it is not allowed to pass any exams on the day number *i*.
The third line contains *m* positive integers *a*1,<=*a*2,<=...,<=*a**m* (1<=β€<=*a**i*<=β€<=105), where *a**i* is the number of days that are needed to prepare before passing the exam on the subject *i*. | Print one integerΒ β the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1. | [
"7 2\n0 1 0 2 1 0 2\n2 1\n",
"10 3\n0 0 1 2 3 0 2 0 1 2\n1 1 4\n",
"5 1\n1 1 1 1 1\n5\n"
] | [
"5\n",
"9\n",
"-1\n"
] | In the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.
In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day.
In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it. | [
{
"input": "7 2\n0 1 0 2 1 0 2\n2 1",
"output": "5"
},
{
"input": "10 3\n0 0 1 2 3 0 2 0 1 2\n1 1 4",
"output": "9"
},
{
"input": "5 1\n1 1 1 1 1\n5",
"output": "-1"
},
{
"input": "100 10\n1 1 6 6 6 2 5 7 6 5 3 7 10 10 8 9 7 6 9 2 6 7 8 6 7 5 2 5 10 1 10 1 8 10 2 9 7 1 6 8 3 ... | 77 | 1,536,000 | 0 | 99,378 | |
936 | Sleepy Game | [
"dfs and similar",
"dp",
"games",
"graphs"
] | null | null | Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of *n* vertices and *m* edges. One of the vertices contains a chip. Initially the chip is located at vertex *s*. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced.
Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves.
Your task is to help Petya find out if he can win the game or at least draw a tie. | The first line of input contain two integers *n* and *m*Β β the number of vertices and the number of edges in the graph (2<=β€<=*n*<=β€<=105, 0<=β€<=*m*<=β€<=2Β·105).
The next *n* lines contain the information about edges of the graph. *i*-th line (1<=β€<=*i*<=β€<=*n*) contains nonnegative integer *c**i*Β β number of vertices such that there is an edge from *i* to these vertices and *c**i* distinct integers *a**i*,<=*j*Β β indices of these vertices (1<=β€<=*a**i*,<=*j*<=β€<=*n*, *a**i*,<=*j*<=β <=*i*).
It is guaranteed that the total sum of *c**i* equals to *m*.
The next line contains index of vertex *s*Β β the initial position of the chip (1<=β€<=*s*<=β€<=*n*). | If Petya can win print Β«WinΒ» in the first line. In the next line print numbers *v*1,<=*v*2,<=...,<=*v**k* (1<=β€<=*k*<=β€<=106)Β β the sequence of vertices Petya should visit for the winning. Vertex *v*1 should coincide with *s*. For *i*<==<=1... *k*<=-<=1 there should be an edge from *v**i* to *v**i*<=+<=1 in the graph. There must be no possible move from vertex *v**k*. The sequence should be such that Petya wins the game.
If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». | [
"5 6\n2 2 3\n2 4 5\n1 4\n1 5\n0\n1\n",
"3 2\n1 3\n1 1\n0\n2\n",
"2 2\n1 2\n1 1\n1\n"
] | [
"Win\n1 2 4 5 \n",
"Lose\n",
"Draw\n"
] | In the first example the graph is the following:
Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins.
In the second example the graph is the following:
Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses.
In the third example the graph is the following:
Petya can't win, but he can move along the cycle, so the players will draw a tie. | [
{
"input": "5 6\n2 2 3\n2 4 5\n1 4\n1 5\n0\n1",
"output": "Win\n1 2 4 5 "
},
{
"input": "3 2\n1 3\n1 1\n0\n2",
"output": "Lose"
},
{
"input": "2 2\n1 2\n1 1\n1",
"output": "Draw"
},
{
"input": "92 69\n1 76\n1 14\n1 9\n0\n1 46\n1 80\n0\n0\n1 77\n0\n1 53\n1 81\n1 61\n1 40\n0\n1... | 62 | 0 | 0 | 99,527 | |
838 | Expected Earnings | [] | null | null | You are playing a game with a bag of red and black balls. Initially, you are told that the bag has *n* balls total. In addition, you are also told that the bag has probability *p**i*<=/<=106 of containing exactly *i* red balls.
You now would like to buy balls from this bag. You really like the color red, so red balls are worth a unit of 1, while black balls are worth nothing. To buy a ball, if there are still balls in the bag, you pay a cost *c* with 0<=β€<=*c*<=β€<=1, and draw a ball randomly from the bag. You can choose to stop buying at any point (and you can even choose to not buy anything at all).
Given that you buy optimally to maximize the expected profit (i.e. # red balls - cost needed to obtain them), print the maximum expected profit. | The first line of input will contain two integers *n*,<=*X* (1<=β€<=*n*<=β€<=10<=000, 0<=β€<=*X*<=β€<=106).
The next line of input will contain *n*<=+<=1 integers *p*0,<=*p*1,<=... *p**n* (0<=β€<=*p**i*<=β€<=106, )
The value of *c* can be computed as . | Print a single floating point number representing the optimal expected value.
Your answer will be accepted if it has absolute or relative error at most 10<=-<=9. More specifically, if your answer is *a* and the jury answer is *b*, your answer will be accepted if . | [
"3 200000\n250000 250000 250000 250000\n"
] | [
"0.9000000000\n"
] | Here, there is equal probability for the bag to contain 0,1,2,3 red balls. Also, it costs 0.2 to draw a ball from the bag. | [] | 483 | 4,505,600 | 0 | 99,685 | |
390 | Inna and Candy Boxes | [
"data structures"
] | null | null | Inna loves sweets very much. She has *n* closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to *n*, from left to right.
As the boxes are closed, Inna doesn't know which boxes contain candies and which boxes contain nothing. Inna chose number *k* and asked *w* questions to Dima to find that out. Each question is characterised by two integers *l**i*,<=*r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*; *r*<=-<=*l*<=+<=1 is divisible by *k*), the *i*-th question is: "Dima, is that true that among the boxes with numbers from *l**i* to *r**i*, inclusive, the candies lie only in boxes with numbers *l**i*<=+<=*k*<=-<=1, *l**i*<=+<=2*k*<=-<=1, *l**i*<=+<=3*k*<=-<=1, ..., *r**i*?"
Dima hates to say "no" to Inna. That's why he wonders, what number of actions he will have to make for each question to make the answer to the question positive. In one action, Dima can either secretly take the candy from any box or put a candy to any box (Dima has infinitely many candies). Help Dima count the number of actions for each Inna's question.
Please note that Dima doesn't change the array during Inna's questions. That's why when you calculate the number of operations for the current question, please assume that the sequence of boxes didn't change. | The first line of the input contains three integers *n*, *k* and *w* (1<=β€<=*k*<=β€<=*min*(*n*,<=10),<=1<=β€<=*n*,<=*w*<=β€<=105). The second line contains *n* characters. If the *i*-th box contains a candy, the *i*-th character of the line equals 1, otherwise it equals 0.
Each of the following *w* lines contains two integers *l**i* and *r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*) β the description of the *i*-th question. It is guaranteed that *r**i*<=-<=*l**i*<=+<=1 is divisible by *k*. | For each question, print a single number on a single line β the minimum number of operations Dima needs to make the answer to the question positive. | [
"10 3 3\n1010100011\n1 3\n1 6\n4 9\n"
] | [
"1\n3\n2\n"
] | For the first question, you need to take a candy from the first box to make the answer positive. So the answer is 1.
For the second question, you need to take a candy from the first box, take a candy from the fifth box and put a candy to the sixth box. The answer is 3.
For the third question, you need to take a candy from the fifth box and put it to the sixth box. The answer is 2. | [] | 78 | 0 | 0 | 99,953 | |
741 | Arpaβs letter-marked tree and Mehrdadβs Dokhtar-kosh paths | [
"data structures",
"dfs and similar",
"trees"
] | null | null | Just in case somebody missed it: we have wonderful girls in Arpaβs land.
Arpa has a rooted tree (connected acyclic graph) consisting of *n* vertices. The vertices are numbered 1 through *n*, the vertex 1 is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He call a string Dokhtar-kosh, if we can shuffle the characters in string such that it becomes palindrome.
He asks Arpa, for each vertex *v*, what is the length of the longest simple path in subtree of *v* that form a Dokhtar-kosh string. | The first line contains integer *n* (1<=<=β€<=<=*n*<=<=β€<=<=5Β·105)Β β the number of vertices in the tree.
(*n*<=<=-<=<=1) lines follow, the *i*-th of them contain an integer *p**i*<=+<=1 and a letter *c**i*<=+<=1 (1<=<=β€<=<=*p**i*<=+<=1<=<=β€<=<=*i*, *c**i*<=+<=1 is lowercase English letter, between a and v, inclusively), that mean that there is an edge between nodes *p**i*<=+<=1 and *i*<=+<=1 and there is a letter *c**i*<=+<=1 written on this edge. | Print *n* integers. The *i*-th of them should be the length of the longest simple path in subtree of the *i*-th vertex that form a Dokhtar-kosh string. | [
"4\n1 s\n2 a\n3 s\n",
"5\n1 a\n2 h\n1 a\n4 h\n"
] | [
"3 1 1 0 ",
"4 1 0 1 0 "
] | none | [] | 93 | 20,172,800 | 0 | 99,954 | |
808 | Card Game | [
"binary search",
"flows",
"graphs"
] | null | null | Digital collectible card games have become very popular recently. So Vova decided to try one of these.
Vova has *n* cards in his collection. Each of these cards is characterised by its power *p**i*, magic number *c**i* and level *l**i*. Vova wants to build a deck with total power not less than *k*, but magic numbers may not allow him to do so β Vova can't place two cards in a deck if the sum of the magic numbers written on these cards is a prime number. Also Vova cannot use a card if its level is greater than the level of Vova's character.
At the moment Vova's character's level is 1. Help Vova to determine the minimum level he needs to reach in order to build a deck with the required total power. | The first line contains two integers *n* and *k* (1<=β€<=*n*<=β€<=100, 1<=β€<=*k*<=β€<=100000).
Then *n* lines follow, each of these lines contains three numbers that represent the corresponding card: *p**i*, *c**i* and *l**i* (1<=β€<=*p**i*<=β€<=1000, 1<=β€<=*c**i*<=β€<=100000, 1<=β€<=*l**i*<=β€<=*n*). | If Vova won't be able to build a deck with required power, print <=-<=1. Otherwise print the minimum level Vova has to reach in order to build a deck. | [
"5 8\n5 5 1\n1 5 4\n4 6 3\n1 12 4\n3 12 1\n",
"3 7\n4 4 1\n5 8 2\n5 3 3\n"
] | [
"4\n",
"2\n"
] | none | [
{
"input": "5 8\n5 5 1\n1 5 4\n4 6 3\n1 12 4\n3 12 1",
"output": "4"
},
{
"input": "3 7\n4 4 1\n5 8 2\n5 3 3",
"output": "2"
},
{
"input": "10 10\n3 3 6\n5 10 4\n4 7 9\n4 9 7\n1 9 4\n1 6 10\n4 10 1\n4 4 6\n2 7 2\n1 5 4",
"output": "4"
},
{
"input": "10 20\n9 4 10\n2 8 9\n9 1 ... | 187 | 10,444,800 | 3 | 100,031 | |
995 | Cowmpany Cowmpensation | [
"combinatorics",
"dp",
"math",
"trees"
] | null | null | Allen, having graduated from the MOO Institute of Techcowlogy (MIT), has started a startup! Allen is the president of his startup. He also hires $n-1$ other employees, each of which is assigned a direct superior. If $u$ is a superior of $v$ and $v$ is a superior of $w$ then also $u$ is a superior of $w$. Additionally, there are no $u$ and $v$ such that $u$ is the superior of $v$ and $v$ is the superior of $u$. Allen himself has no superior. Allen is employee number $1$, and the others are employee numbers $2$ through $n$.
Finally, Allen must assign salaries to each employee in the company including himself. Due to budget constraints, each employee's salary is an integer between $1$ and $D$. Additionally, no employee can make strictly more than his superior.
Help Allen find the number of ways to assign salaries. As this number may be large, output it modulo $10^9 + 7$. | The first line of the input contains two integers $n$ and $D$ ($1 \le n \le 3000$, $1 \le D \le 10^9$).
The remaining $n-1$ lines each contain a single positive integer, where the $i$-th line contains the integer $p_i$ ($1 \le p_i \le i$). $p_i$ denotes the direct superior of employee $i+1$. | Output a single integer: the number of ways to assign salaries modulo $10^9 + 7$. | [
"3 2\n1\n1\n",
"3 3\n1\n2\n",
"2 5\n1\n"
] | [
"5\n",
"10\n",
"15\n"
] | In the first sample case, employee 2 and 3 report directly to Allen. The three salaries, in order, can be $(1,1,1)$, $(2,1,1)$, $(2,1,2)$, $(2,2,1)$ or $(2,2,2)$.
In the second sample case, employee 2 reports to Allen and employee 3 reports to employee 2. In order, the possible salaries are $(1,1,1)$, $(2,1,1)$, $(2,2,1)$, $(2,2,2)$, $(3,1,1)$, $(3,2,1)$, $(3,2,2)$, $(3,3,1)$, $(3,3,2)$, $(3,3,3)$. | [] | 2,000 | 256,819,200 | 0 | 100,086 | |
954 | Castle Defense | [
"binary search",
"data structures",
"greedy",
"two pointers"
] | null | null | Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into *n* sections. At this moment there are exactly *a**i* archers located at the *i*-th section of this wall. You know that archer who stands at section *i* can shoot orcs that attack section located at distance not exceeding *r*, that is all such sections *j* that |*i*<=-<=*j*|<=β€<=*r*. In particular, *r*<==<=0 means that archers are only capable of shooting at orcs who attack section *i*.
Denote as defense level of section *i* the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of *k* archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan. | The first line of the input contains three integers *n*, *r* and *k* (1<=β€<=*n*<=β€<=500<=000, 0<=β€<=*r*<=β€<=*n*, 0<=β€<=*k*<=β€<=1018)Β β the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=109)Β β the current number of archers at each section. | Print one integerΒ β the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute *k* additional archers optimally. | [
"5 0 6\n5 4 3 4 9\n",
"4 2 0\n1 2 3 4\n",
"5 1 1\n2 1 2 1 2\n"
] | [
"5\n",
"6\n",
"3\n"
] | none | [
{
"input": "5 0 6\n5 4 3 4 9",
"output": "5"
},
{
"input": "4 2 0\n1 2 3 4",
"output": "6"
},
{
"input": "5 1 1\n2 1 2 1 2",
"output": "3"
},
{
"input": "1 0 0\n0",
"output": "0"
},
{
"input": "1 0 1000000000000000000\n1000000000",
"output": "10000000010000000... | 1,500 | 80,998,400 | 0 | 100,198 | |
178 | Magic Squares | [] | null | null | The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size *n*<=Γ<=*n*. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number *s*. The sum of numbers in each column of the matrix is also equal to *s*. In addition, the sum of the elements on the main diagonal is equal to *s* and the sum of elements on the secondary diagonal is equal to *s*. Examples of magic squares are given in the following figure:
You are given a set of *n*2 integers *a**i*. It is required to place these numbers into a square matrix of size *n*<=Γ<=*n* so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.
It is guaranteed that a solution exists! | The first input line contains a single integer *n*. The next line contains *n*2 integers *a**i* (<=-<=108<=β€<=*a**i*<=β€<=108), separated by single spaces.
The input limitations for getting 20 points are:
- 1<=β€<=*n*<=β€<=3
The input limitations for getting 50 points are:
- 1<=β€<=*n*<=β€<=4 - It is guaranteed that there are no more than 9 distinct numbers among *a**i*.
The input limitations for getting 100 points are:
- 1<=β€<=*n*<=β€<=4 | The first line of the output should contain a single integer *s*. In each of the following *n* lines print *n* integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to *s*. If there are multiple solutions, you are allowed to print any of them. | [
"3\n1 2 3 4 5 6 7 8 9\n",
"3\n1 0 -1 0 2 -1 -2 0 1\n",
"2\n5 5 5 5\n"
] | [
"15\n2 7 6\n9 5 1\n4 3 8\n",
"0\n1 0 -1\n-2 0 2\n1 0 -1\n",
"10\n5 5\n5 5\n"
] | none | [
{
"input": "3\n1 2 3 4 5 6 7 8 9",
"output": "15\n2 7 6\n9 5 1\n4 3 8"
},
{
"input": "3\n1 0 -1 0 2 -1 -2 0 1",
"output": "0\n1 0 -1\n-2 0 2\n1 0 -1"
},
{
"input": "2\n5 5 5 5",
"output": "10\n5 5\n5 5"
},
{
"input": "2\n-1 -1 -1 -1",
"output": "-2\n-1 -1\n-1 -1"
},
{... | 1,090 | 13,516,800 | 3 | 100,317 | |
660 | Bear and Bowling 4 | [
"binary search",
"data structures",
"divide and conquer",
"geometry",
"ternary search"
] | null | null | Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record!
For rolling a ball one gets a score β an integer (maybe negative) number of points. Score for the *i*-th roll is multiplied by *i* and scores are summed up. So, for *k* rolls with scores *s*1,<=*s*2,<=...,<=*s**k*, the total score is . The total score is 0 if there were no rolls.
Limak made *n* rolls and got score *a**i* for the *i*-th of them. He wants to maximize his total score and he came up with an interesting idea. He can say that some first rolls were only a warm-up, and that he wasn't focused during the last rolls. More formally, he can cancel any prefix and any suffix of the sequence *a*1,<=*a*2,<=...,<=*a**n*. It is allowed to cancel all rolls, or to cancel none of them.
The total score is calculated as if there were only non-canceled rolls. So, the first non-canceled roll has score multiplied by 1, the second one has score multiplied by 2, and so on, till the last non-canceled roll.
What maximum total score can Limak get? | The first line contains a single integer *n* (1<=β€<=*n*<=β€<=2Β·105) β the total number of rolls made by Limak.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=β€<=107) β scores for Limak's rolls. | Print the maximum possible total score after cancelling rolls. | [
"6\n5 -1000 1 -3 7 -8\n",
"5\n1000 1000 1001 1000 1000\n",
"3\n-60 -70 -80\n"
] | [
"16\n",
"15003\n",
"0\n"
] | In the first sample test, Limak should cancel the first two rolls, and one last roll. He will be left with rolls 1,ββ-β3,β7 what gives him the total score 1Β·1β+β2Β·(β-β3)β+β3Β·7β=β1β-β6β+β21β=β16. | [
{
"input": "6\n5 -1000 1 -3 7 -8",
"output": "16"
},
{
"input": "5\n1000 1000 1001 1000 1000",
"output": "15003"
},
{
"input": "3\n-60 -70 -80",
"output": "0"
},
{
"input": "1\n-4",
"output": "0"
},
{
"input": "2\n-3 6",
"output": "9"
},
{
"input": "3\... | 2,000 | 5,529,600 | 0 | 100,523 | |
491 | New York Hotel | [
"greedy",
"math"
] | null | null | Think of New York as a rectangular grid consisting of *N* vertical avenues numerated from 1 to *N* and *M* horizontal streets numerated 1 to *M*. *C* friends are staying at *C* hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of *H* restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer. | The first line contains two integers *N* ΠΈ *M*Β β size of the city (1<=β€<=*N*,<=*M*<=β€<=109). In the next line there is a single integer *C* (1<=β€<=*C*<=β€<=105)Β β the number of hotels friends stayed at. Following *C* lines contain descriptions of hotels, each consisting of two coordinates *x* and *y* (1<=β€<=*x*<=β€<=*N*, 1<=β€<=*y*<=β€<=*M*). The next line contains an integer *H*Β β the number of restaurants (1<=β€<=*H*<=β€<=105). Following *H* lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing. | In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them. | [
"10 10\n2\n1 1\n3 3\n2\n1 10\n4 4\n"
] | [
"6\n2\n"
] | none | [
{
"input": "10 10\n2\n1 1\n3 3\n2\n1 10\n4 4",
"output": "6\n2"
},
{
"input": "100 100\n10\n53 20\n97 6\n12 74\n48 92\n97 13\n47 96\n75 32\n69 21\n95 75\n1 54\n10\n36 97\n41 1\n1 87\n39 23\n27 44\n73 97\n1 1\n6 26\n48 3\n5 69",
"output": "108\n4"
},
{
"input": "100 100\n10\n86 72\n25 73\... | 46 | 0 | 0 | 100,640 | |
607 | Power Tree | [
"data structures",
"trees"
] | null | null | Genos and Saitama went shopping for Christmas trees. However, a different type of tree caught their attention, the exalted Power Tree.
A Power Tree starts out as a single root vertex indexed 1. A Power Tree grows through a magical phenomenon known as an update. In an update, a single vertex is added to the tree as a child of some other vertex.
Every vertex in the tree (the root and all the added vertices) has some value *v**i* associated with it. The power of a vertex is defined as the strength of the multiset composed of the value associated with this vertex (*v**i*) and the powers of its direct children. The strength of a multiset is defined as the sum of all elements in the multiset multiplied by the number of elements in it. Or in other words for some multiset *S*:
Saitama knows the updates that will be performed on the tree, so he decided to test Genos by asking him queries about the tree during its growth cycle.
An update is of the form 1Β *p*Β *v*, and adds a new vertex with value *v* as a child of vertex *p*.
A query is of the form 2Β *u*, and asks for the power of vertex *u*.
Please help Genos respond to these queries modulo 109<=+<=7. | The first line of the input contains two space separated integers *v*1 and *q* (1<=β€<=*v*1<=<<=109, 1<=β€<=*q*<=β€<=200<=000) β the value of vertex 1 and the total number of updates and queries respectively.
The next *q* lines contain the updates and queries. Each of them has one of the following forms:
- 1Β *p**i*Β *v**i*, if these line describes an update. The index of the added vertex is equal to the smallest positive integer not yet used as an index in the tree. It is guaranteed that *p**i* is some already existing vertex and 1<=β€<=*v**i*<=<<=109. - 2Β *u**i*, if these line describes a query. It is guaranteed *u**i* will exist in the tree.
It is guaranteed that the input will contain at least one query. | For each query, print out the power of the given vertex modulo 109<=+<=7. | [
"2 5\n1 1 3\n1 2 5\n1 3 7\n1 4 11\n2 1\n",
"5 5\n1 1 4\n1 2 3\n2 2\n1 2 7\n2 1\n"
] | [
"344\n",
"14\n94\n"
] | For the first sample case, after all the updates the graph will have vertices labelled in the following manner: 1 β 2 β 3 β 4 β 5
These vertices will have corresponding values: 2 β 3 β 5 β 7 β 11
And corresponding powers: 344 β 170 β 82 β 36 β 11 | [] | 31 | 0 | 0 | 100,908 | |
817 | MEX Queries | [
"binary search",
"data structures",
"trees"
] | null | null | You are given a set of integer numbers, initially it is empty. You should perform *n* queries.
There are three different types of queries:
- 1 *l* *r* β Add all missing numbers from the interval [*l*,<=*r*] - 2 *l* *r* β Remove all present numbers from the interval [*l*,<=*r*] - 3 *l* *r* β Invert the interval [*l*,<=*r*] β add all missing and remove all present numbers from the interval [*l*,<=*r*]
After each query you should output MEX of the set β the smallest positive (MEX <=β₯<=1) integer number which is not presented in the set. | The first line contains one integer number *n* (1<=β€<=*n*<=β€<=105).
Next *n* lines contain three integer numbers *t*,<=*l*,<=*r* (1<=β€<=*t*<=β€<=3,<=1<=β€<=*l*<=β€<=*r*<=β€<=1018) β type of the query, left and right bounds. | Print MEX of the set after each query. | [
"3\n1 3 4\n3 1 6\n2 1 3\n",
"4\n1 1 3\n3 5 6\n2 4 4\n3 1 6\n"
] | [
"1\n3\n1\n",
"4\n4\n4\n1\n"
] | Here are contents of the set after each query in the first example:
1. {3,β4} β the interval [3,β4] is added 1. {1,β2,β5,β6} β numbers {3,β4} from the interval [1,β6] got deleted and all the others are added 1. {5,β6} β numbers {1,β2} got deleted | [
{
"input": "3\n1 3 4\n3 1 6\n2 1 3",
"output": "1\n3\n1"
},
{
"input": "4\n1 1 3\n3 5 6\n2 4 4\n3 1 6",
"output": "4\n4\n4\n1"
},
{
"input": "1\n1 1 89",
"output": "90"
},
{
"input": "10\n1 1 9\n2 2 10\n2 1 10\n1 8 10\n3 8 10\n2 1 8\n3 9 10\n1 7 10\n1 4 10\n3 10 10",
"out... | 1,481 | 138,137,600 | 0 | 101,338 | |
613 | Kingdom and its Cities | [
"dfs and similar",
"divide and conquer",
"dp",
"graphs",
"sortings",
"trees"
] | null | null | Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom currently consists of *n* cities. Cities are connected by *n*<=-<=1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.
What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.
Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.
Help the King to calculate this characteristic for each of his plan. | The first line of the input contains integer *n* (1<=β€<=*n*<=β€<=100<=000)Β β the number of cities in the kingdom.
Each of the next *n*<=-<=1 lines contains two distinct integers *u**i*, *v**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*)Β β the indices of the cities connected by the *i*-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.
The next line contains a single integer *q* (1<=β€<=*q*<=β€<=100<=000)Β β the number of King's plans.
Each of the next *q* lines looks as follows: first goes number *k**i*Β β the number of important cities in the King's plan, (1<=β€<=*k**i*<=β€<=*n*), then follow exactly *k**i* space-separated pairwise distinct numbers from 1 to *n*Β β the numbers of important cities in this plan.
The sum of all *k**i*'s does't exceed 100<=000. | For each plan print a single integer β the minimum number of cities that the barbarians need to capture, or print <=-<=1 if all the barbarians' attempts to isolate important cities will not be effective. | [
"4\n1 3\n2 3\n4 3\n4\n2 1 2\n3 2 3 4\n3 1 2 4\n4 1 2 3 4\n",
"7\n1 2\n2 3\n3 4\n1 5\n5 6\n5 7\n1\n4 2 4 6 7\n"
] | [
"1\n-1\n1\n-1\n",
"2\n"
] | In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.
In the second sample the cities to capture are 3 and 5. | [
{
"input": "4\n1 3\n2 3\n4 3\n4\n2 1 2\n3 2 3 4\n3 1 2 4\n4 1 2 3 4",
"output": "1\n-1\n1\n-1"
},
{
"input": "7\n1 2\n2 3\n3 4\n1 5\n5 6\n5 7\n1\n4 2 4 6 7",
"output": "2"
},
{
"input": "7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n5\n4 1 3 5 7\n3 2 4 6\n2 1 7\n2 3 4\n3 1 6 7",
"output": "3\n2\n... | 124 | 0 | 0 | 101,432 | |
746 | Tram | [
"constructive algorithms",
"implementation",
"math"
] | null | null | The tram in Berland goes along a straight line from the point 0 to the point *s* and back, passing 1 meter per *t*1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points *x*<==<=0 and *x*<==<=*s*.
Igor is at the point *x*1. He should reach the point *x*2. Igor passes 1 meter per *t*2 seconds.
Your task is to determine the minimum time Igor needs to get from the point *x*1 to the point *x*2, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point *x*1.
Igor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is not obligatory that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than 1 meter per *t*2 seconds). He can also stand at some point for some time. | The first line contains three integers *s*, *x*1 and *x*2 (2<=β€<=*s*<=β€<=1000, 0<=β€<=*x*1,<=*x*2<=β€<=*s*, *x*1<=β <=*x*2)Β β the maximum coordinate of the point to which the tram goes, the point Igor is at, and the point he should come to.
The second line contains two integers *t*1 and *t*2 (1<=β€<=*t*1,<=*t*2<=β€<=1000)Β β the time in seconds in which the tram passes 1 meter and the time in seconds in which Igor passes 1 meter.
The third line contains two integers *p* and *d* (1<=β€<=*p*<=β€<=*s*<=-<=1, *d* is either 1 or )Β β the position of the tram in the moment Igor came to the point *x*1 and the direction of the tram at this moment. If , the tram goes in the direction from the point *s* to the point 0. If *d*<==<=1, the tram goes in the direction from the point 0 to the point *s*. | Print the minimum time in seconds which Igor needs to get from the point *x*1 to the point *x*2. | [
"4 2 4\n3 4\n1 1\n",
"5 4 0\n1 2\n3 1\n"
] | [
"8\n",
"7\n"
] | In the first example it is profitable for Igor to go by foot and not to wait the tram. Thus, he has to pass 2 meters and it takes 8 seconds in total, because he passes 1 meter per 4 seconds.
In the second example Igor can, for example, go towards the point *x*<sub class="lower-index">2</sub> and get to the point 1 in 6 seconds (because he has to pass 3 meters, but he passes 1 meters per 2 seconds). At that moment the tram will be at the point 1, so Igor can enter the tram and pass 1 meter in 1 second. Thus, Igor will reach the point *x*<sub class="lower-index">2</sub> in 7 seconds in total. | [
{
"input": "4 2 4\n3 4\n1 1",
"output": "8"
},
{
"input": "5 4 0\n1 2\n3 1",
"output": "7"
},
{
"input": "5 4 0\n5 14\n1 -1",
"output": "55"
},
{
"input": "10 7 2\n7 9\n9 -1",
"output": "45"
},
{
"input": "20 5 19\n163 174\n4 1",
"output": "2436"
},
{
... | 78 | 0 | 3 | 102,011 | |
940 | Cashback | [
"data structures",
"dp",
"greedy",
"math"
] | null | null | Since you are the best Wraith King, Nizhniy Magazin Β«MirΒ» at the centre of Vinnytsia is offering you a discount.
You are given an array *a* of length *n* and an integer *c*.
The value of some array *b* of length *k* is the sum of its elements except for the smallest. For example, the value of the array [3,<=1,<=6,<=5,<=2] with *c*<==<=2 is 3<=+<=6<=+<=5<==<=14.
Among all possible partitions of *a* into contiguous subarrays output the smallest possible sum of the values of these subarrays. | The first line contains integers *n* and *c* (1<=β€<=*n*,<=*c*<=β€<=100<=000).
The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=109)Β β elements of *a*. | Output a single integer Β β the smallest possible sum of values of these subarrays of some partition of *a*. | [
"3 5\n1 2 3\n",
"12 10\n1 1 10 10 10 10 10 10 9 10 10 10\n",
"7 2\n2 3 6 4 5 7 1\n",
"8 4\n1 3 4 5 5 3 4 1\n"
] | [
"6\n",
"92\n",
"17\n",
"23\n"
] | In the first example any partition yields 6 as the sum.
In the second example one of the optimal partitions is [1,β1],β[10,β10,β10,β10,β10,β10,β9,β10,β10,β10] with the values 2 and 90 respectively.
In the third example one of the optimal partitions is [2,β3],β[6,β4,β5,β7],β[1] with the values 3, 13 and 1 respectively.
In the fourth example one of the optimal partitions is [1],β[3,β4,β5,β5,β3,β4],β[1] with the values 1, 21 and 1 respectively. | [
{
"input": "3 5\n1 2 3",
"output": "6"
},
{
"input": "12 10\n1 1 10 10 10 10 10 10 9 10 10 10",
"output": "92"
},
{
"input": "7 2\n2 3 6 4 5 7 1",
"output": "17"
},
{
"input": "8 4\n1 3 4 5 5 3 4 1",
"output": "23"
},
{
"input": "15 5\n11 15 16 24 24 28 36 40 49 4... | 0 | 0 | -1 | 102,252 | |
406 | Hill Climbing | [
"dfs and similar",
"geometry",
"trees"
] | null | null | This problem has nothing to do with Little Chris. It is about hill climbers instead (and Chris definitely isn't one).
There are *n* hills arranged on a line, each in the form of a vertical line segment with one endpoint on the ground. The hills are numbered with numbers from 1 to *n* from left to right. The *i*-th hill stands at position *x**i* with its top at height *y**i*. For every two hills *a* and *b*, if the top of hill *a* can be seen from the top of hill *b*, their tops are connected by a rope. Formally, the tops of two hills are connected if the segment connecting their top points does not intersect or touch any of the other hill segments. Using these ropes, the hill climbers can move from hill to hill.
There are *m* teams of climbers, each composed of exactly two members. The first and the second climbers of the *i*-th team are located at the top of the *a**i*-th and *b**i*-th hills, respectively. They want to meet together at the top of some hill. Now, each of two climbers move according to the following process:
1. if a climber is at the top of the hill where the other climber is already located or will come eventually, the former climber stays at this hill; 1. otherwise, the climber picks a hill to the right of his current hill that is reachable by a rope and is the rightmost possible, climbs this hill and continues the process (the climber can also climb a hill whose top is lower than the top of his current hill).
For each team of climbers, determine the number of the meeting hill for this pair! | The first line of input contains a single integer *n* (1<=β€<=*n*<=β€<=105), the number of hills. The next *n* lines describe the hills. The *i*-th of them contains two space-separated integers *x**i*, *y**i* (1<=β€<=*x**i*<=β€<=107; 1<=β€<=*y**i*<=β€<=1011), the position and the height of the *i*-th hill. The hills are given in the ascending order of *x**i*, i.e., *x**i*<=<<=*x**j* for *i*<=<<=*j*.
The next line of input contains a single integer *m* (1<=β€<=*m*<=β€<=105), the number of teams. The next *m* lines describe the teams. The *i*-th of them contains two space-separated integers *a**i*, *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*), the numbers of the hills where the climbers of the *i*-th team are located. It is possible that *a**i*<==<=*b**i*. | In a single line output *m* space-separated integers, where the *i*-th integer is the number of the meeting hill for the members of the *i*-th team. | [
"6\n1 4\n2 1\n3 2\n4 3\n6 4\n7 4\n3\n3 1\n5 6\n2 3\n"
] | [
"5 6 3 \n"
] | none | [] | 1,000 | 25,190,400 | 0 | 102,486 | |
703 | Mishka and Divisors | [
"dp",
"number theory"
] | null | null | After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem.
You are given integer *k* and array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers. You are to find non-empty subsequence of array elements such that the product of its elements is divisible by *k* and it contains minimum possible number of elements.
Formally, you are to find a sequence of indices 1<=β€<=*i*1<=<<=*i*2<=<<=...<=<<=*i**m*<=β€<=*n* such that is divisible by *k* while *m* is minimum possible among all such variants.
If there are more than one such subsequences, you should choose one among them, such that sum of its elements is minimum possible.
Mishka quickly solved this problem. Will you do so? | The first line of the input contains two integers *n* and *k* (1<=β€<=*n*<=β€<=1<=000, 1<=β€<=*k*<=β€<=1012).
The second line of the input contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=1012)Β β array elements. | Print single positive integer *m* in the first lineΒ β the number of elements in desired sequence.
In the second line print *m* distinct integersΒ β the sequence of indices of given array elements, which should be taken into the desired sequence.
If there are more than one such subsequence (e.g. subsequence of minimum possible number of elements and with minimum possible sum of elements), you can print any of them.
If there are no such subsequences, print <=-<=1 in the only line. | [
"5 60\n2 4 6 5 2\n"
] | [
"3\n4 3 1 "
] | none | [
{
"input": "5 60\n2 4 6 5 2",
"output": "3\n4 3 1 "
},
{
"input": "10 66\n93 799 19 143 1739 1403 19 1681 8513 1457",
"output": "-1"
},
{
"input": "10 78\n2473 7234 317 3793 6638 6 7789 753 1117 8243",
"output": "-1"
},
{
"input": "10 78\n19 1081 143 5 31 61 1363 319 39 589",... | 30 | 0 | 0 | 102,616 | |
809 | Find a car | [
"combinatorics",
"divide and conquer",
"dp"
] | null | null | After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.
Formally the parking can be represented as a matrix 109<=Γ<=109. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from 1 to 109 from left to right and the rows by integers from 1 to 109 from top to bottom. By coincidence it turned out, that for every cell (*x*,<=*y*) the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells (*i*,<=*y*) and (*x*,<=*j*), 1<=β€<=*i*<=<<=*x*,<=1<=β€<=*j*<=<<=*y*.
Leha wants to ask the watchman *q* requests, which can help him to find his car. Every request is represented as five integers *x*1,<=*y*1,<=*x*2,<=*y*2,<=*k*. The watchman have to consider all cells (*x*,<=*y*) of the matrix, such that *x*1<=β€<=*x*<=β€<=*x*2 and *y*1<=β€<=*y*<=β€<=*y*2, and if the number of the car in cell (*x*,<=*y*) does not exceed *k*, increase the answer to the request by the number of the car in cell (*x*,<=*y*). For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo 109<=+<=7.
However the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests. | The first line contains one integer *q* (1<=β€<=*q*<=β€<=104)Β β the number of Leha's requests.
The next *q* lines contain five integers *x*1,<=*y*1,<=*x*2,<=*y*2,<=*k* (1<=β€<=*x*1<=β€<=*x*2<=β€<=109,<=1<=β€<=*y*1<=β€<=*y*2<=β€<=109,<=1<=β€<=*k*<=β€<=2Β·109)Β β parameters of Leha's requests. | Print exactly *q* linesΒ β in the first line print the answer to the first request, in the secondΒ β the answer to the second request and so on. | [
"4\n1 1 1 1 1\n3 2 5 4 5\n1 1 5 5 10000\n1 4 2 5 2\n"
] | [
"1\n13\n93\n0\n"
] | Let's analyze all the requests. In each case the requested submatrix is highlighted in blue.
In the first request (*k*β=β1) Leha asks only about the upper left parking cell. In this cell the car's number is 1. Consequentally the answer is 1.
<img class="tex-graphics" src="https://espresso.codeforces.com/76839e22308c8bf65bf6a862f4c9bc49b50ec2f4.png" style="max-width: 100.0%;max-height: 100.0%;"/>
In the second request (*k*β=β5) suitable numbers are 4,β1,β2,β3,β2,β1. Consequentally the answer is 4β+β1β+β2β+β3β+β2β+β1β=β13.
<img class="tex-graphics" src="https://espresso.codeforces.com/f86466a8ccbb4825331662353153b686b40ab62f.png" style="max-width: 100.0%;max-height: 100.0%;"/>
In the third request (*k*β=β10000) Leha asks about the upper left frament 5βΓβ5 of the parking. Since *k* is big enough, the answer is equal to 93.
<img class="tex-graphics" src="https://espresso.codeforces.com/f3fae55460e5237c800c229f19113cd1f4181f3c.png" style="max-width: 100.0%;max-height: 100.0%;"/>
In the last request (*k*β=β2) none of the cur's numbers are suitable, so the answer is 0.
<img class="tex-graphics" src="https://espresso.codeforces.com/59bf21e74f30e2f3cdbdd55d300500e3e3f9b632.png" style="max-width: 100.0%;max-height: 100.0%;"/> | [
{
"input": "4\n1 1 1 1 1\n3 2 5 4 5\n1 1 5 5 10000\n1 4 2 5 2",
"output": "1\n13\n93\n0"
},
{
"input": "10\n3 7 4 10 7\n6 1 7 10 18\n9 6 10 8 3\n1 8 3 10 3\n10 4 10 5 19\n8 9 9 10 10\n10 1 10 5 4\n8 1 9 4 18\n6 3 9 5 1\n6 6 9 6 16",
"output": "22\n130\n0\n0\n25\n3\n0\n68\n0\n22"
},
{
"in... | 4,000 | 0 | 0 | 103,514 | |
442 | Artem and Array | [
"data structures",
"greedy"
] | null | null | Artem has an array of *n* positive integers. Artem decided to play with it. The game consists of *n* moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets *min*(*a*,<=*b*) points, where *a* and *b* are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.
After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game. | The first line contains a single integer *n* (1<=β€<=*n*<=β€<=5Β·105) β the number of elements in the array. The next line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=106) β the values of the array elements. | In a single line print a single integer β the maximum number of points Artem can get. | [
"5\n3 1 5 2 6\n",
"5\n1 2 3 4 5\n",
"5\n1 100 101 100 1\n"
] | [
"11\n",
"6\n",
"102\n"
] | none | [
{
"input": "5\n3 1 5 2 6",
"output": "11"
},
{
"input": "5\n1 2 3 4 5",
"output": "6"
},
{
"input": "5\n1 100 101 100 1",
"output": "102"
},
{
"input": "10\n96 66 8 18 30 48 34 11 37 42",
"output": "299"
},
{
"input": "1\n87",
"output": "0"
},
{
"input... | 93 | 0 | 0 | 103,563 | |
249 | Donkey and Stars | [
"data structures",
"dp",
"geometry",
"math",
"sortings"
] | null | null | In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly *n*. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the *OX* axis to the left along the roof and the *OY* axis β up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles Ξ±1 and Ξ±2 to the *OX* axis.
Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles Ξ±1 and Ξ±2 to the *OX* axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star.
As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules.
Your task is to find the maximum number of stars *m* that the Donkey's chain can contain.
Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number *m* of stars in the chain. | The first line contains an integer *n* (1<=β€<=*n*<=β€<=105) β the number of stars. The second line contains simple fractions representing relationships "*a*/*b* *c*/*d*", such that and (0<=β€<=*a*,<=*b*,<=*c*,<=*d*<=β€<=105; ; ; ). The given numbers *a*, *b*, *c*, *d* are integers.
Next *n* lines contain pairs of integers *x**i*, *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=105)β the stars' coordinates.
It is guaranteed that all stars have distinct coordinates. | In a single line print number *m* β the answer to the problem. | [
"15\n1/3 2/1\n3 1\n6 2\n4 2\n2 5\n4 5\n6 6\n3 4\n1 6\n2 1\n7 4\n9 3\n5 3\n1 3\n15 5\n12 4\n"
] | [
"4\n"
] | In the sample the longest chain the Donkey can build consists of four stars. Note that the Donkey can't choose the stars that lie on the rays he imagines. | [
{
"input": "15\n1/3 2/1\n3 1\n6 2\n4 2\n2 5\n4 5\n6 6\n3 4\n1 6\n2 1\n7 4\n9 3\n5 3\n1 3\n15 5\n12 4",
"output": "4"
},
{
"input": "15\n2/1 2/0\n3 1\n6 2\n9 3\n12 4\n15 5\n2 1\n4 2\n5 3\n7 4\n1 3\n3 4\n2 5\n4 5\n1 6\n6 6",
"output": "1"
},
{
"input": "15\n2/1 2/0\n3 1\n6 2\n9 3\n12 4\n15... | 2,000 | 4,710,400 | 0 | 103,637 | |
306 | White, Black and White Again | [
"combinatorics",
"number theory"
] | null | null | Polycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next *n* days. Polycarpus knows that he is in for *w* good events and *b* not-so-good events. At least one event is going to take place during each day. As each day is unequivocally characterizes as a part of a white or a black stripe, then each day is going to have events of the same type only (ether good or not-so-good).
What is the number of distinct ways this scenario can develop over the next *n* days if Polycarpus is in for a white stripe (a stripe that has good events only, the stripe's length is at least 1 day), the a black stripe (a stripe that has not-so-good events only, the stripe's length is at least 1 day) and a white stripe again (a stripe that has good events only, the stripe's length is at least 1 day). Each of *n* days will belong to one of the three stripes only.
Note that even the events of the same type are distinct from each other. Even if some events occur on the same day, they go in some order (there are no simultaneous events).
Write a code that prints the number of possible configurations to sort the events into days. See the samples for clarifications on which scenarios should be considered distinct. Print the answer modulo 1000000009 (109<=+<=9). | The single line of the input contains integers *n*, *w* and *b* (3<=β€<=*n*<=β€<=4000, 2<=β€<=*w*<=β€<=4000, 1<=β€<=*b*<=β€<=4000) β the number of days, the number of good events and the number of not-so-good events. It is guaranteed that *w*<=+<=*b*<=β₯<=*n*. | Print the required number of ways modulo 1000000009 (109<=+<=9). | [
"3 2 1\n",
"4 2 2\n",
"3 2 2\n"
] | [
"2\n",
"4\n",
"4\n"
] | We'll represent the good events by numbers starting from 1 and the not-so-good events β by letters starting from 'a'. Vertical lines separate days.
In the first sample the possible ways are: "1|a|2" and "2|a|1". In the second sample the possible ways are: "1|a|b|2", "2|a|b|1", "1|b|a|2" and "2|b|a|1". In the third sample the possible ways are: "1|ab|2", "2|ab|1", "1|ba|2" and "2|ba|1". | [
{
"input": "3 2 1",
"output": "2"
},
{
"input": "4 2 2",
"output": "4"
},
{
"input": "3 2 2",
"output": "4"
},
{
"input": "3 3 1",
"output": "12"
},
{
"input": "3 2 2",
"output": "4"
},
{
"input": "3 3 3",
"output": "72"
},
{
"input": "4 2 ... | 92 | 0 | 0 | 103,649 | |
240 | TorCoder | [
"data structures"
] | null | null | A boy named Leo doesn't miss a single TorCoder contest round. On the last TorCoder round number 100666 Leo stumbled over the following problem. He was given a string *s*, consisting of *n* lowercase English letters, and *m* queries. Each query is characterised by a pair of integers *l**i*,<=*r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*).
We'll consider the letters in the string numbered from 1 to *n* from left to right, that is, *s*<==<=*s*1*s*2... *s**n*.
After each query he must swap letters with indexes from *l**i* to *r**i* inclusive in string *s* so as to make substring (*l**i*,<=*r**i*) a palindrome. If there are multiple such letter permutations, you should choose the one where string (*l**i*,<=*r**i*) will be lexicographically minimum. If no such permutation exists, you should ignore the query (that is, not change string *s*).
Everybody knows that on TorCoder rounds input line and array size limits never exceed 60, so Leo solved this problem easily. Your task is to solve the problem on a little bit larger limits. Given string *s* and *m* queries, print the string that results after applying all *m* queries to string *s*. | The first input line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=105) β the string length and the number of the queries.
The second line contains string *s*, consisting of *n* lowercase Latin letters.
Each of the next *m* lines contains a pair of integers *l**i*,<=*r**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*) β a query to apply to the string. | In a single line print the result of applying *m* queries to string *s*. Print the queries in the order in which they are given in the input. | [
"7 2\naabcbaa\n1 3\n5 7\n",
"3 2\nabc\n1 2\n2 3\n"
] | [
"abacaba\n",
"abc\n"
] | A substring (*l*<sub class="lower-index">*i*</sub>,β*r*<sub class="lower-index">*i*</sub>) 1ββ€β*l*<sub class="lower-index">*i*</sub>ββ€β*r*<sub class="lower-index">*i*</sub>ββ€β*n*) of string *s*β=β*s*<sub class="lower-index">1</sub>*s*<sub class="lower-index">2</sub>... *s*<sub class="lower-index">*n*</sub> of length *n* is a sequence of characters *s*<sub class="lower-index">*l*<sub class="lower-index">*i*</sub></sub>*s*<sub class="lower-index">*l*<sub class="lower-index">*i*β+β1</sub></sub>...*s*<sub class="lower-index">*r*<sub class="lower-index">*i*</sub></sub>.
A string is a palindrome, if it reads the same from left to right and from right to left.
String *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*<sub class="lower-index">1</sub>*y*<sub class="lower-index">2</sub>... *y*<sub class="lower-index">*q*</sub>, if either *p*β<β*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 exists such number *r* (*r*β<β*p*,β*r*β<β*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>β<β*y*<sub class="lower-index">*r*β+β1</sub>. | [] | 31 | 0 | -1 | 103,661 | |
200 | Football Championship | [
"brute force",
"implementation"
] | null | null | Any resemblance to any real championship and sport is accidental.
The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship:
- the team that kicked most balls in the enemy's goal area wins the game; - the victory gives 3 point to the team, the draw gives 1 point and the defeat gives 0 points; - a group consists of four teams, the teams are ranked by the results of six games: each team plays exactly once with each other team; - the teams that get places 1 and 2 in the group stage results, go to the next stage of the championship.
In the group stage the team's place is defined by the total number of scored points: the more points, the higher the place is. If two or more teams have the same number of points, then the following criteria are used (the criteria are listed in the order of falling priority, starting from the most important one):
- the difference between the total number of scored goals and the total number of missed goals in the championship: the team with a higher value gets a higher place; - the total number of scored goals in the championship: the team with a higher value gets a higher place; - the lexicographical order of the name of the teams' countries: the country with the lexicographically smaller name gets a higher place.
The Berland team plays in the group where the results of 5 out of 6 games are already known. To be exact, there is the last game left. There the Berand national team plays with some other team. The coach asks you to find such score *X*:*Y* (where *X* is the number of goals Berland scored and *Y* is the number of goals the opponent scored in the game), that fulfills the following conditions:
- *X* > *Y*, that is, Berland is going to win this game; - after the game Berland gets the 1st or the 2nd place in the group; - if there are multiple variants, you should choose such score *X*:*Y*, where value *X*<=-<=*Y* is minimum; - if it is still impossible to come up with one score, you should choose the score where value *Y* (the number of goals Berland misses) is minimum. | The input has five lines.
Each line describes a game as "*team*1 *team*2 *goals*1:*goals*2" (without the quotes), what means that team *team*1 played a game with team *team*2, besides, *team*1 scored *goals*1 goals and *team*2 scored *goals*2 goals. The names of teams *team*1 and *team*2 are non-empty strings, consisting of uppercase English letters, with length of no more than 20 characters; *goals*1,<=*goals*2 are integers from 0 to 9.
The Berland team is called "BERLAND". It is guaranteed that the Berland team and one more team played exactly 2 games and the the other teams played exactly 3 games. | Print the required score in the last game as *X*:*Y*, where *X* is the number of goals Berland scored and *Y* is the number of goals the opponent scored. If the Berland team does not get the first or the second place in the group, whatever this game's score is, then print on a single line "IMPOSSIBLE" (without the quotes).
Note, that the result score can be very huge, 10:0 for example. | [
"AERLAND DERLAND 2:1\nDERLAND CERLAND 0:3\nCERLAND AERLAND 0:1\nAERLAND BERLAND 2:0\nDERLAND BERLAND 4:0\n",
"AERLAND DERLAND 2:2\nDERLAND CERLAND 2:3\nCERLAND AERLAND 1:3\nAERLAND BERLAND 2:1\nDERLAND BERLAND 4:1\n"
] | [
"6:0\n",
"IMPOSSIBLE\n"
] | In the first sample "BERLAND" plays the last game with team "CERLAND". If Berland wins with score 6:0, the results' table looks like that in the end:
1. AERLAND (points: 9, the difference between scored and missed goals: 4, scored goals: 5) 1. BERLAND (points: 3, the difference between scored and missed goals: 0, scored goals: 6) 1. DERLAND (points: 3, the difference between scored and missed goals: 0, scored goals: 5) 1. CERLAND (points: 3, the difference between scored and missed goals: -4, scored goals: 3)
In the second sample teams "AERLAND" and "DERLAND" have already won 7 and 4 points, respectively. The Berland team wins only 3 points, which is not enough to advance to the next championship stage. | [] | 122 | 0 | 0 | 103,831 | |
727 | Polycarp's problems | [
"binary search",
"dp",
"greedy"
] | null | null | Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.
He sent to the coordinator a set of *n* problems. Each problem has it's quality, the quality of the *i*-th problem is *a**i* (*a**i* can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index 1, the hardest problem has index *n*.
The coordinator's mood is equal to *q* now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality *b*, the value *b* is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.
If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.
Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has *m* guesses "the current coordinator's mood *q*<==<=*b**i*".
For each of *m* guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to 0 while he reads problems from the easiest of the remaining problems to the hardest. | The first line of input contains two integers *n* and *m* (1<=β€<=*n*<=β€<=750, 1<=β€<=*m*<=β€<=200<=000)Β β the number of problems in the problemset and the number of guesses about the current coordinator's mood.
The second line of input contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=β€<=*a**i*<=β€<=109)Β β the qualities of the problems in order of increasing difficulty.
The third line of input contains *m* integers *b*1,<=*b*2,<=...,<=*b**m* (0<=β€<=*b**i*<=β€<=1015)Β β the guesses of the current coordinator's mood *q*. | Print *m* lines, in *i*-th line print single integerΒ β the answer to the problem with *q*<==<=*b**i*. | [
"6 3\n8 -5 -4 1 -7 4\n0 7 3\n"
] | [
"2\n0\n1\n"
] | none | [
{
"input": "6 3\n8 -5 -4 1 -7 4\n0 7 3",
"output": "2\n0\n1"
},
{
"input": "10 5\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n0 1 2 3 4",
"output": "10\n9\n8\n7\n6"
},
{
"input": "10 5\n1 -1 1 -2 1 -1 1 -2 1 -1\n0 1 2 3 4",
"output": "1\n1\n0\n0\n0"
},
{
"input": "1 5\n7\n1 3 5 7 9",
... | 2,000 | 4,300,800 | 0 | 103,964 | |
730 | Minimum and Maximum | [
"constructive algorithms",
"interactive"
] | null | null | This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use function fflush(stdout), in Java β System.out.flush(), in Pascal β flush(output) and in Python β sys.stdout.flush().
In this problem, you need to find maximal and minimal elements of an array. What could be simpler?
You can imagine that the jury has an array, and initially you know the only number *n* β array's length.
Array's elements are numbered from 1 to *n*. You are allowed to compare two elements of the array by using their indices *i* and *j*. There are three possible responses to this query: '<' (if *a**i* is less than *a**j*), '=' (if *a**i* is equal to *a**j*) and finally '>' (if *a**i* is greater than *a**j*).
It's known that it's always possible to find both maximal and minimal elements of the array by using no more than comparisons, where β *x*β is the result of rounding *x* up.
Write the program that will find positions of the minimum and the maximum in the jury's array of length *n*, by using no more than *f*(*n*) comparisons. | none | none | [
"2\n2\nΒ \n>\nΒ \n3\nΒ \n=\nΒ \n=\nΒ "
] | [
"? 1 2\nΒ \n! 2 1\nΒ \n? 3 1\nΒ \n? 2 1\nΒ \n! 2 3"
] | none | [
{
"input": "2\n2\n2 1\n3\n1 1 1",
"output": "1 out of 1\n3 out of 3\n2 queries processed [sumn=5]"
},
{
"input": "1\n4\n1 1 2 2",
"output": "4 out of 4\n1 queries processed [sumn=4]"
},
{
"input": "2\n5\n1 1 2 1 1\n3\n3 2 1",
"output": "6 out of 6\n3 out of 3\n2 queries processed [su... | 77 | 2,867,200 | 0 | 104,058 | |
581 | Three Logos | [
"bitmasks",
"brute force",
"constructive algorithms",
"geometry",
"implementation",
"math"
] | null | null | Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules. | The first line of the input contains six positive integers *x*1,<=*y*1,<=*x*2,<=*y*2,<=*x*3,<=*y*3 (1<=β€<=*x*1,<=*y*1,<=*x*2,<=*y*2,<=*x*3,<=*y*3<=β€<=100), where *x**i* and *y**i* determine the length and width of the logo of the *i*-th company respectively. | If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square *n*, where you can place all the three logos. Each of the next *n* lines should contain *n* uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
- the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, - the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, - the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement. | [
"5 1 2 5 5 2\n",
"4 4 2 6 4 2\n"
] | [
"5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC\n",
"6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC\n"
] | none | [
{
"input": "5 1 2 5 5 2",
"output": "5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC"
},
{
"input": "4 4 2 6 4 2",
"output": "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"
},
{
"input": "1 3 1 3 3 1",
"output": "3\nAAA\nBBB\nCCC"
},
{
"input": "2 4 1 4 1 4",
"output": "4\nAAAA\... | 31 | 307,200 | 0 | 104,213 | |
0 | none | [
"none"
] | null | null | Pieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it.
On his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of their values with their parent, that now became a leaf (the player decides which of the two values to associate). The game ends when only one node (the one that was the root of the tree) is left.
Pieguy goes first, and his goal is to maximize the value that will be associated with the root when the game ends. Piegirl wants to minimize that value. Assuming that both players are playing optimally, what number will be associated with the root when the game ends? | First line contains a single integer *t* (1<=β€<=*t*<=β€<=100) β number of test cases. Then *t* test cases follow. Each test case begins with an empty line, followed by a line with a single integer *n* (1<=β€<=*n*<=β€<=250), followed by *n* lines describing *n* nodes of the tree. Each of those *n* lines either contains a non-negative number *a**i*, indicating a leaf node with value *a**i* (0<=β€<=*a**i*<=β€<=1000) associated with it, or <=-<=1 followed by integers *l* and *r*, indicating a non-leaf node with children *l* and *r* (0<=β€<=*l*,<=*r*<=β€<=*n*<=-<=1). Nodes are numbered from 0 to *n*<=-<=1. The root is always node 0. | For each test case print one line with one integer on it β the number that will be associated with the root when the game ends. | [
"4\n\n3\n-1 1 2\n10\n5\n\n5\n-1 1 2\n-1 3 4\n10\n5\n20\n\n7\n-1 1 2\n-1 3 4\n-1 5 6\n1\n2\n3\n4\n\n11\n-1 1 2\n-1 3 4\n-1 5 6\n-1 7 8\n15\n7\n-1 9 10\n7\n8\n9\n11\n"
] | [
"10\n10\n4\n8\n"
] | none | [] | 46 | 0 | 0 | 104,331 | |
57 | Chess | [
"math",
"shortest paths"
] | E. Chess | 2 | 256 | Brian the Rabbit adores chess. Not long ago he argued with Stewie the Rabbit that a knight is better than a king. To prove his point he tries to show that the knight is very fast but Stewie doesn't accept statements without evidence. He constructed an infinite chessboard for Brian, where he deleted several squares to add some more interest to the game. Brian only needs to count how many different board squares a knight standing on a square with coordinates of (0,<=0) can reach in no more than *k* moves. Naturally, it is forbidden to move to the deleted squares.
Brian doesn't very much like exact sciences himself and is not acquainted with programming, that's why he will hardly be able to get ahead of Stewie who has already started solving the problem. Help Brian to solve the problem faster than Stewie. | The first line contains two integers *k* and *n* (0<=β€<=*k*<=β€<=1018,<=0<=β€<=*n*<=β€<=440) which are correspondingly the maximal number of moves a knight can make and the number of deleted cells. Then follow *n* lines, each giving the coordinates of a deleted square in the form (*x**i*,<=*y**i*) (|*x**i*|<=β€<=10,<=|*y**i*|<=β€<=10). All the numbers are integer, the deleted squares are different and it is guaranteed that the square (0,<=0) is not deleted.
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). | You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007. | [
"1 0\n",
"2 7\n-1 2\n1 2\n2 1\n2 -1\n1 -2\n-1 -2\n-2 -1\n"
] | [
"9\n",
"9\n"
] | none | [] | 92 | 0 | 0 | 104,717 |
266 | Below the Diagonal | [
"constructive algorithms",
"greedy",
"math"
] | null | null | You are given a square matrix consisting of *n* rows and *n* columns. We assume that the rows are numbered from 1 to *n* from top to bottom and the columns are numbered from 1 to *n* from left to right. Some cells (*n*<=-<=1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap *i*-th and *j*-th rows of the matrix; 1. Swap *i*-th and *j*-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the *i*-th row and of the *j*-th column, lies below the main diagonal if *i*<=><=*j*. | The first line contains an integer *n* (2<=β€<=*n*<=β€<=1000) β the number of rows and columns. Then follow *n*<=-<=1 lines that contain one's positions, one per line. Each position is described by two integers *x**k*,<=*y**k* (1<=β€<=*x**k*,<=*y**k*<=β€<=*n*), separated by a space. A pair (*x**k*,<=*y**k*) means that the cell, which is located on the intersection of the *x**k*-th row and of the *y**k*-th column, contains one.
It is guaranteed that all positions are distinct. | Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer *m* (*m*<=β€<=105) β the number of actions. In each of the next *m* lines print three space-separated integers *t*,<=*i*,<=*j* (1<=β€<=*t*<=β€<=2,<=1<=β€<=*i*,<=*j*<=β€<=*n*,<=*i*<=β <=*j*), where *t*<==<=1 if you want to swap rows, *t*<==<=2 if you want to swap columns, and *i* and *j* denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them. | [
"2\n1 2\n",
"3\n3 1\n1 3\n",
"3\n2 1\n3 2\n"
] | [
"2\n2 1 2\n1 1 2\n",
"3\n2 2 3\n1 1 3\n1 1 2\n",
"0\n"
] | none | [] | 62 | 0 | 0 | 104,936 | |
0 | none | [
"none"
] | null | null | Copying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string, nor the length of the string, but may have permuted the digits arbitrarily. For example, if the original string was 0*abc* they may have changed it to *a*0*cb* or 0*bca*, but not *abc* or 0*abb*.
Unfortunately you don't have access to the original string nor the copied string, but you do know the length of the strings and their numerical absolute difference. You will be given this difference as a hexadecimal string *S*, which has been zero-extended to be equal in length to the original and copied strings. Determine the smallest possible numerical value of the original string. | Input will contain a hexadecimal string *S* consisting only of digits 0 to 9 and lowercase English letters from *a* to *f*, with length at most 14. At least one of the characters is non-zero. | If it is not possible, print "NO" (without quotes).
Otherwise, print the lowercase hexadecimal string corresponding to the smallest possible numerical value, including any necessary leading zeros for the length to be correct. | [
"f1e\n",
"0f1e\n",
"12d2c\n"
] | [
"NO\n",
"00f1\n",
"00314\n"
] | The numerical value of a hexadecimal string is computed by multiplying each digit by successive powers of 16, starting with the rightmost digit, which is multiplied by 16<sup class="upper-index">0</sup>. Hexadecimal digits representing values greater than 9 are represented by letters: *a*β=β10,β*b*β=β11,β*c*β=β12,β*d*β=β13,β*e*β=β14,β*f*β=β15.
For example, the numerical value of 0*f*1*e* is 0Β·16<sup class="upper-index">3</sup>β+β15Β·16<sup class="upper-index">2</sup>β+β1Β·16<sup class="upper-index">1</sup>β+β14Β·16<sup class="upper-index">0</sup>β=β3870, the numerical value of 00*f*1 is 0Β·16<sup class="upper-index">3</sup>β+β0Β·16<sup class="upper-index">2</sup>β+β15Β·16<sup class="upper-index">1</sup>β+β1Β·16<sup class="upper-index">0</sup>β=β241, and the numerical value of 100*f* is 1Β·16<sup class="upper-index">3</sup>β+β0Β·16<sup class="upper-index">2</sup>β+β0Β·16<sup class="upper-index">1</sup>β+β15Β·16<sup class="upper-index">0</sup>β=β4111. Since 3870β+β241β=β4111 and 00*f*1 is a permutation of 100*f*, 00*f*1 is a valid answer to the second test case. | [] | 46 | 0 | 0 | 105,024 | |
852 | Bob and stages | [
"dp",
"geometry"
] | null | null | The citizens of BubbleLand are celebrating their 10th anniversary so they decided to organize a big music festival. Bob got a task to invite *N* famous singers who would sing on the fest. He was too busy placing stages for their performances that he totally forgot to write the invitation e-mails on time, and unfortunately he only found *K* available singers. Now there are more stages than singers, leaving some of the stages empty. Bob would not like if citizens of BubbleLand noticed empty stages and found out that he was irresponsible.
Because of that he decided to choose exactly *K* stages that form a convex set, make large posters as edges of that convex set and hold festival inside. While those large posters will make it impossible for citizens to see empty stages outside Bob still needs to make sure they don't see any of the empty stages inside that area.
Since lots of people are coming, he would like that the festival area is as large as possible. Help him calculate the maximum area that he could obtain respecting the conditions. If there is no such area, the festival cannot be organized and the answer is 0.00. | The first line of input contains two integers *N* (3<=β€<=*N*<=β€<=200) and *K* (3<=β€<=*K*<=β€<=*min*(*N*,<=50)), separated with one empty space, representing number of stages and number of singers, respectively.
Each of the next *N* lines contains two integers *X**i* and *Y**i* (0<=β€<=*X**i*,<=*Y**i*<=β€<=106) representing the coordinates of the stages. There are no three or more collinear stages. | Output contains only one line with one number, rounded to exactly two decimal places: the maximal festival area. Rounding is performed so that 0.5 and more rounds up and everything else rounds down. | [
"5 4\n0 0\n3 0\n2 1\n4 4\n1 5\n"
] | [
"10.00\n"
] | Example explanation: From all possible convex polygon with 4 vertices and no other vertex inside, the largest is one with points (0,β0), (2,β1), (4,β4) and (1,β5). | [] | 30 | 0 | 0 | 105,113 | |
91 | Ski Base | [
"combinatorics",
"dsu",
"graphs"
] | C. Ski Base | 2 | 256 | A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains *n* ski junctions, numbered from 1 to *n*. Initially the junctions aren't connected in any way.
In the constructing process *m* bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The *i*-th road connects the junctions with numbers *a**i* and *b**i*.
Track is the route with the following properties:
- The route is closed, that is, it begins and ends in one and the same junction.- The route contains at least one road. - The route doesn't go on one road more than once, however it can visit any junction any number of times.
Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.
Two ski bases are considered different if they consist of different road sets.
After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem. | The first line contains two integers *n* and *m* (2<=β€<=*n*<=β€<=105,<=1<=β€<=*m*<=β€<=105). They represent the number of junctions and the number of roads correspondingly. Then on *m* lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*,<=*a**i*<=β <=*b**i*) β the numbers of the connected junctions. There could be more than one road between a pair of junctions. | Print *m* lines: the *i*-th line should represent the number of ways to build a ski base after the end of construction of the road number *i*. The numbers should be printed modulo 1000000009 (109<=+<=9). | [
"3 4\n1 3\n2 3\n1 2\n1 2\n"
] | [
"0\n0\n1\n3\n"
] | Let us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this:
The land lot for the construction will look in the following way:
We can choose a subset of roads in three ways:
In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1. | [
{
"input": "3 4\n1 3\n2 3\n1 2\n1 2",
"output": "0\n0\n1\n3"
},
{
"input": "15 29\n6 11\n14 3\n10 4\n14 7\n6 14\n7 15\n13 8\n10 13\n4 14\n15 8\n12 7\n3 5\n6 7\n8 1\n4 5\n11 5\n10 6\n11 3\n13 14\n7 10\n3 12\n7 14\n8 11\n7 15\n15 8\n12 7\n4 3\n9 4\n8 10",
"output": "0\n0\n0\n0\n0\n0\n0\n0\n0\n1\n1... | 46 | 0 | 0 | 105,192 |
359 | Neatness | [
"constructive algorithms",
"dfs and similar"
] | null | null | Simon loves neatness. So before he goes to bed, Simon wants to complete all chores in the house.
Simon's house looks like a rectangular table consisting of *n* rows and *n* columns from above. All rows of the table are numbered from 1 to *n* from top to bottom. All columns of the table are numbered from 1 to *n* from left to right. Each cell of the table is a room. Pair (*x*,<=*y*) denotes the room, located at the intersection of the *x*-th row and the *y*-th column. For each room we know if the light is on or not there.
Initially Simon is in room (*x*0,<=*y*0). He wants to turn off the lights in all the rooms in the house, and then return to room (*x*0,<=*y*0). Suppose that at the current moment Simon is in the room (*x*,<=*y*). To reach the desired result, he can perform the following steps:
1. The format of the action is "1". The action is to turn on the light in room (*x*,<=*y*). Simon cannot do it if the room already has light on. 1. The format of the action is "2". The action is to turn off the light in room (*x*,<=*y*). Simon cannot do it if the room already has light off. 1. The format of the action is "dir" (*dir* is a character). The action is to move to a side-adjacent room in direction *dir*. The direction can be left, right, up or down (the corresponding dir is L, R, U or D). Additionally, Simon can move only if he see a light in the direction *dir*. More formally, if we represent the room, Simon wants to go, as (*nx*,<=*ny*), there shold be an integer *k* (*k*<=><=0), that room (*x*<=+<=(*nx*<=-<=*x*)*k*,<=*y*<=+<=(*ny*<=-<=*y*)*k*) has a light. Of course, Simon cannot move out of his house.
Help Simon, find the sequence of actions that lets him achieve the desired result. | The first line contains three positive integers *n*,<=*x*0,<=*y*0 (2<=β€<=*n*<=β€<=500,<=1<=β€<=*x*0,<=*y*0<=β€<=*n*).
Next *n* lines contain the description of rooms in the house. The *i*-th line contains *n* space-separated integers *a**i*1,<=*a**i*2,<=...,<=*a**in*. If number *a**ij* equals zero, then room (*i*,<=*j*) has light off, and if number *a**ij* equals one, then room (*i*,<=*j*) has light on. It is guaranteed that at least one room has light on. | If there is no desired sequence of actions, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes) and the description of the required sequence of actions as a string. Note that you do not have to minimize the length of the sequence of actions but you shouldn't use more than 3Β·106 actions. | [
"3 1 1\n1 0 0\n0 1 0\n1 0 0\n",
"3 1 1\n1 0 0\n0 1 0\n0 0 1\n"
] | [
"YES\nD1R2L2D2UU2\n",
"NO\n"
] | none | [] | 46 | 0 | 0 | 105,232 | |
242 | Dispute | [
"dfs and similar",
"graphs",
"greedy"
] | null | null | Valera has *n* counters numbered from 1 to *n*. Some of them are connected by wires, and each of the counters has a special button.
Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.
Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number *i*, which has value *a**i*, then Valera loses the dispute, otherwise he wins the dispute.
Help Valera to determine on which counters he needs to press a button to win the dispute. | The first line contains two space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=105), that denote the number of counters Valera has and the number of pairs of counters connected by wires.
Each of the following *m* lines contains two space-separated integers *u**i* and *v**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*,<=*u**i*<=β <=*v**i*), that mean that counters with numbers *u**i* and *v**i* are connected by a wire. It is guaranteed that each pair of connected counters occurs exactly once in the input.
The last line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=105), where *a**i* is the value that Ignat choose for the *i*-th counter. | If Valera can't win the dispute print in the first line -1.
Otherwise, print in the first line integer *k* (0<=β€<=*k*<=β€<=*n*). In the second line print *k* distinct space-separated integers β the numbers of the counters, where Valera should push buttons to win the dispute, in arbitrary order.
If there exists multiple answers, you are allowed to print any of them. | [
"5 5\n2 3\n4 1\n1 5\n5 3\n2 1\n1 1 2 0 2\n",
"4 2\n1 2\n3 4\n0 0 0 0\n"
] | [
"2\n1 2\n",
"3\n1 3 4\n"
] | none | [
{
"input": "5 5\n2 3\n4 1\n1 5\n5 3\n2 1\n1 1 2 0 2",
"output": "2\n1 2"
},
{
"input": "4 2\n1 2\n3 4\n0 0 0 0",
"output": "3\n1 3 4"
},
{
"input": "3 3\n2 3\n1 3\n1 2\n1 1 3",
"output": "0"
},
{
"input": "4 6\n3 4\n2 3\n2 4\n1 2\n1 3\n4 1\n4 0 2 3",
"output": "1\n2 "
}... | 1,246 | 40,652,800 | 3 | 105,344 | |
898 | Restoring the Expression | [
"brute force",
"hashing",
"math"
] | null | null | A correct expression of the form a+b=c was written; *a*, *b* and *c* are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that:
- character'+' is placed on the left of character '=', - characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle partΒ β b and the right partΒ β c), - all the three parts a, b and c do not contain leading zeros, - it is true that a+b=c.
It is guaranteed that in given tests answer always exists. | The first line contains a non-empty string consisting of digits. The length of the string does not exceed 106. | Output the restored expression. If there are several solutions, you can print any of them.
Note that the answer at first should contain two terms (divided with symbol '+'), and then the result of their addition, before which symbol'=' should be.
Do not separate numbers and operation signs with spaces. Strictly follow the output format given in the examples.
If you remove symbol '+' and symbol '=' from answer string you should get a string, same as string from the input data. | [
"12345168\n",
"099\n",
"199100\n",
"123123123456456456579579579\n"
] | [
"123+45=168\n",
"0+9=9\n",
"1+99=100\n",
"123123123+456456456=579579579\n"
] | none | [
{
"input": "12345168",
"output": "123+45=168"
},
{
"input": "099",
"output": "0+9=9"
},
{
"input": "199100",
"output": "1+99=100"
},
{
"input": "123123123456456456579579579",
"output": "123123123+456456456=579579579"
},
{
"input": "112",
"output": "1+1=2"
},... | 2,000 | 268,390,400 | 0 | 105,529 | |
979 | Kuro and Topological Parity | [
"dp"
] | null | null | Kuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games.
Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot of arrows (you can assume that the number of arrows is infinite). Immediately, Katie came up with the game called Topological Parity.
The paper is divided into $n$ pieces enumerated from $1$ to $n$. Shiro has painted some pieces with some color. Specifically, the $i$-th piece has color $c_{i}$ where $c_{i} = 0$ defines black color, $c_{i} = 1$ defines white color and $c_{i} = -1$ means that the piece hasn't been colored yet.
The rules of the game is simple. Players must put some arrows between some pairs of different pieces in such a way that for each arrow, the number in the piece it starts from is less than the number of the piece it ends at. Also, two different pieces can only be connected by at most one arrow. After that the players must choose the color ($0$ or $1$) for each of the unpainted pieces. The score of a valid way of putting the arrows and coloring pieces is defined as the number of paths of pieces of alternating colors. For example, $[1 \to 0 \to 1 \to 0]$, $[0 \to 1 \to 0 \to 1]$, $[1]$, $[0]$ are valid paths and will be counted. You can only travel from piece $x$ to piece $y$ if and only if there is an arrow from $x$ to $y$.
But Kuro is not fun yet. He loves parity. Let's call his favorite parity $p$ where $p = 0$ stands for "even" and $p = 1$ stands for "odd". He wants to put the arrows and choose colors in such a way that the score has the parity of $p$.
It seems like there will be so many ways which satisfy Kuro. He wants to count the number of them but this could be a very large number. Let's help him with his problem, but print it modulo $10^{9} + 7$. | The first line contains two integers $n$ and $p$ ($1 \leq n \leq 50$, $0 \leq p \leq 1$) β the number of pieces and Kuro's wanted parity.
The second line contains $n$ integers $c_{1}, c_{2}, ..., c_{n}$ ($-1 \leq c_{i} \leq 1$) β the colors of the pieces. | Print a single integer β the number of ways to put the arrows and choose colors so the number of valid paths of alternating colors has the parity of $p$. | [
"3 1\n-1 0 1\n",
"2 1\n1 0\n",
"1 1\n-1\n"
] | [
"6",
"1",
"2"
] | In the first example, there are $6$ ways to color the pieces and add the arrows, as are shown in the figure below. The scores are $3, 3, 5$ for the first row and $5, 3, 3$ for the second row, both from left to right. | [
{
"input": "3 1\n-1 0 1",
"output": "6"
},
{
"input": "2 1\n1 0",
"output": "1"
},
{
"input": "1 1\n-1",
"output": "2"
},
{
"input": "1 0\n-1",
"output": "0"
},
{
"input": "1 1\n0",
"output": "1"
},
{
"input": "5 1\n-1 -1 -1 -1 -1",
"output": "1651... | 46 | 0 | 0 | 105,595 | |
757 | Bash Plays with Functions | [
"brute force",
"combinatorics",
"dp",
"number theory"
] | null | null | Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions.
Bash defines a function *f*0(*n*), which denotes the number of ways of factoring *n* into two factors *p* and *q* such that *gcd*(*p*,<=*q*)<==<=1. In other words, *f*0(*n*) is the number of ordered pairs of positive integers (*p*,<=*q*) such that *p*Β·*q*<==<=*n* and *gcd*(*p*,<=*q*)<==<=1.
But Bash felt that it was too easy to calculate this function. So he defined a series of functions, where *f**r*<=+<=1 is defined as:
Where (*u*,<=*v*) is any ordered pair of positive integers, they need not to be co-prime.
Now Bash wants to know the value of *f**r*(*n*) for different *r* and *n*. Since the value could be huge, he would like to know the value modulo 109<=+<=7. Help him! | The first line contains an integer *q* (1<=β€<=*q*<=β€<=106)Β β the number of values Bash wants to know.
Each of the next *q* lines contain two integers *r* and *n* (0<=β€<=*r*<=β€<=106, 1<=β€<=*n*<=β€<=106), which denote Bash wants to know the value *f**r*(*n*). | Print *q* integers. For each pair of *r* and *n* given, print *f**r*(*n*) modulo 109<=+<=7 on a separate line. | [
"5\n0 30\n1 25\n3 65\n2 5\n4 48\n"
] | [
"8\n5\n25\n4\n630\n"
] | none | [
{
"input": "5\n0 30\n1 25\n3 65\n2 5\n4 48",
"output": "8\n5\n25\n4\n630"
},
{
"input": "10\n788320 679319\n530483 595211\n563388 996394\n781948 542877\n651049 580717\n932449 999004\n869373 900380\n892578 818546\n786482 603289\n867938 792888",
"output": "788322\n414333258\n434446408\n445798223\n... | 2,932 | 268,390,400 | 0 | 105,673 | |
909 | AND-permutations | [
"constructive algorithms"
] | null | null | Given an integer *N*, find two permutations:
1. Permutation *p* of numbers from 1 to *N* such that *p**i*<=β <=*i* and *p**i*<=&<=*i*<==<=0 for all *i*<==<=1,<=2,<=...,<=*N*. 1. Permutation *q* of numbers from 1 to *N* such that *q**i*<=β <=*i* and *q**i*<=&<=*i*<=β <=0 for all *i*<==<=1,<=2,<=...,<=*N*.
& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). | The input consists of one line containing a single integer *N* (1<=β€<=*N*<=β€<=105). | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and *N* elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | [
"3\n",
"6\n"
] | [
"NO\nNO\n",
"YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4\n"
] | none | [
{
"input": "3",
"output": "NO\nNO"
},
{
"input": "6",
"output": "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"
},
{
"input": "100000",
"output": "YES\n30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 32 31 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 7... | 483 | 268,390,400 | 0 | 105,709 | |
277 | Set of Points | [
"constructive algorithms",
"geometry"
] | null | null | Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of *n* points with the convexity of exactly *m*. Your set of points should not contain three points that lie on a straight line. | The single line contains two integers *n* and *m* (3<=β€<=*m*<=β€<=100,<=*m*<=β€<=*n*<=β€<=2*m*). | If there is no solution, print "-1". Otherwise, print *n* pairs of integers β the coordinates of points of any set with the convexity of *m*. The coordinates shouldn't exceed 108 in their absolute value. | [
"4 3\n",
"6 3\n",
"6 6\n",
"7 4\n"
] | [
"0 0\n3 0\n0 3\n1 1\n",
"-1\n",
"10 0\n-10 0\n10 1\n9 1\n9 -1\n0 -2\n",
"176166 6377\n709276 539564\n654734 174109\n910147 434207\n790497 366519\n606663 21061\n859328 886001\n"
] | none | [
{
"input": "4 3",
"output": "0 0\n3 0\n0 3\n1 1"
},
{
"input": "6 3",
"output": "-1"
},
{
"input": "6 6",
"output": "10 0\n-10 0\n10 1\n9 1\n9 -1\n0 -2"
},
{
"input": "7 4",
"output": "176166 6377\n709276 539564\n654734 174109\n910147 434207\n790497 366519\n606663 21061\n... | 60 | 0 | 0 | 105,962 | |
38 | The Great Marathon | [
"dp"
] | H. The Great Marathon | 4 | 256 | On the Berland Dependence Day it was decided to organize a great marathon. Berland consists of *n* cities, some of which are linked by two-way roads. Each road has a certain length. The cities are numbered from 1 to *n*. It is known that one can get from any city to any other one by the roads.
*n* runners take part in the competition, one from each city. But Berland runners are talkative by nature and that's why the juries took measures to avoid large crowds of marathon participants. The jury decided that every runner should start the marathon from their hometown. Before the start every sportsman will get a piece of paper containing the name of the city where the sportsman's finishing line is. The finish is chosen randomly for every sportsman but it can't coincide with the sportsman's starting point. Several sportsmen are allowed to finish in one and the same city. All the sportsmen start simultaneously and everyone runs the shortest route from the starting point to the finishing one. All the sportsmen run at one speed which equals to 1.
After the competition a follow-up table of the results will be composed where the sportsmen will be sorted according to the nondecrease of time they spent to cover the distance. The first *g* sportsmen in the table will get golden medals, the next *s* sportsmen will get silver medals and the rest will get bronze medals. Besides, if two or more sportsmen spend the same amount of time to cover the distance, they are sorted according to the number of the city where a sportsman started to run in the ascending order. That means no two sportsmen share one and the same place.
According to the rules of the competition the number of gold medals *g* must satisfy the inequation *g*1<=β€<=*g*<=β€<=*g*2, where *g*1 and *g*2 are values formed historically. In a similar way, the number of silver medals *s* must satisfy the inequation *s*1<=β€<=*s*<=β€<=*s*2, where *s*1 and *s*2 are also values formed historically.
At present, before the start of the competition, the destination points of every sportsman are unknown. However, the press demands details and that's why you are given the task of counting the number of the ways to distribute the medals. Two ways to distribute the medals are considered different if at least one sportsman could have received during those distributions different kinds of medals. | The first input line contains given integers *n* and *m* (3<=β€<=*n*<=β€<=50, *n*<=-<=1<=β€<=*m*<=β€<=1000), where *n* is the number of Berland towns and *m* is the number of roads.
Next in *m* lines road descriptions are given as groups of three integers *v*, *u*, *c*, which are the numbers of linked towns and its length (1<=β€<=*v*,<=*u*<=β€<=*n*, *v*<=β <=*u*, 1<=β€<=*c*<=β€<=1000). Every pair of cities have no more than one road between them.
The last line contains integers *g*1, *g*2, *s*1, *s*2 (1<=β€<=*g*1<=β€<=*g*2, 1<=β€<=*s*1<=β€<=*s*2, *g*2<=+<=*s*2<=<<=*n*). The input data numbers, located on one line, are space-separated. | Print the single number β the number of ways to distribute the medals. It is guaranteed that the number fits in the standard 64-bit signed data type. | [
"3 2\n1 2 1\n2 3 1\n1 1 1 1\n",
"4 5\n1 2 2\n2 3 1\n3 4 2\n4 1 2\n1 3 3\n1 2 1 1\n",
"3 3\n1 2 2\n2 3 1\n3 1 2\n1 1 1 1\n"
] | [
"3\n",
"19\n",
"4\n"
] | none | [] | 154 | 2,969,600 | -1 | 105,990 |
44 | Triminoes | [
"constructive algorithms",
"greedy"
] | J. Triminoes | 2 | 256 | There are many interesting tasks on domino tilings. For example, an interesting fact is known. Let us take a standard chessboard (8<=Γ<=8) and cut exactly two squares out of it. It turns out that the resulting board can always be tiled using dominoes 1<=Γ<=2, if the two cut out squares are of the same color, otherwise it is impossible.
Petya grew bored with dominoes, that's why he took a chessboard (not necessarily 8<=Γ<=8), cut some squares out of it and tries to tile it using triminoes. Triminoes are reactangles 1<=Γ<=3 (or 3<=Γ<=1, because triminoes can be rotated freely), also the two extreme squares of a trimino are necessarily white and the square in the middle is black. The triminoes are allowed to put on the chessboard so that their squares matched the colors of the uncut squares of the chessboard, and also the colors must match: the black squares must be matched with the black ones only and the white ones β with the white squares. The triminoes must not protrude above the chessboard or overlap each other. All the uncut squares of the board must be covered with triminoes.
Help Petya find out if it is possible to tile his board using triminos in the described way and print one of the variants of tiling. | The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=1000) β the board size. Next *n* lines contain *m* symbols each and represent the board description. If some position contains ".", then the square in this position has been cut out. Symbol "w" stands for a white square, "b" stands for a black square. It is guaranteed that through adding the cut squares can result in a correct chessboard (i.e. with alternating black and white squares), thought, perhaps, of a non-standard size. | If at least one correct tiling exists, in the first line print "YES" (without quotes), and then β the tiling description. The description must contain *n* lines, *m* symbols in each. The cut out squares, as well as in the input data, are marked by ".". To denote triminoes symbols "a", "b", "c", "d" can be used, and all the three squares of each trimino must be denoted by the same symbol. If two triminoes share a side, than they must be denoted by different symbols. Two triminoes not sharing a common side can be denoted by one and the same symbol (c.f. sample).
If there are multiple correct ways of tiling, it is allowed to print any. If it is impossible to tile the board using triminoes or the correct tiling, for which four symbols "a", "b", "c", "d" would be enough, doesn't exist, print "NO" (without quotes) in the first line. | [
"6 10\n.w.wbw.wbw\nwbwbw.w.w.\nbw.wbwbwbw\nw.wbw.wbwb\n...wbw.w.w\n..wbw.wbw.\n",
"2 2\nwb\nbw\n",
"1 3\nwbw\n",
"1 3\n...\n"
] | [
"YES\n.a.aaa.ccc\nbaccc.c.a.\nba.dddcbab\nb.aaa.cbab\n...bbb.b.b\n..ccc.ddd.",
"NO\n",
"YES\nbbb\n",
"YES\n...\n"
] | none | [
{
"input": "6 10\n.w.wbw.wbw\nwbwbw.w.w.\nbw.wbwbwbw\nw.wbw.wbwb\n...wbw.w.w\n..wbw.wbw.",
"output": "YES\n.a.aaa.aaa\nbabbb.a.b.\nba.cccacba\nb.aaa.acba\n...bbb.c.a\n..aaa.aaa."
},
{
"input": "2 2\nwb\nbw",
"output": "NO"
},
{
"input": "1 3\nwbw",
"output": "YES\naaa"
},
{
"... | 92 | 0 | 0 | 106,041 |
195 | Building Forest | [
"data structures",
"dsu",
"graphs"
] | null | null | An oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.
The root of vertex *v* of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex *v* moving along the edges of the weighted oriented forest. We denote the root of vertex *v* as *root*(*v*).
The depth of vertex *v* is the sum of weights of paths passing from the vertex *v* to its root. Let's denote the depth of the vertex *v* as *depth*(*v*).
Let's consider the process of constructing a weighted directed forest. Initially, the forest does not contain vertices. Vertices are added sequentially one by one. Overall, there are *n* performed operations of adding. The *i*-th (*i*<=><=0) adding operation is described by a set of numbers (*k*,<=<=*v*1,<=<=*x*1,<=<=*v*2,<=<=*x*2,<=<=... ,<=<=*v**k*,<=<=*x**k*) and means that we should add vertex number *i* and *k* edges to the graph: an edge from vertex *root*(*v*1) to vertex *i* with weight *depth*(*v*1)<=+<=*x*1, an edge from vertex *root*(*v*2) to vertex *i* with weight *depth*(*v*2)<=+<=*x*2 and so on. If *k*<==<=0, then only vertex *i* is added to the graph, there are no added edges.
Your task is like this: given the operations of adding vertices, calculate the sum of the weights of all edges of the forest, resulting after the application of all defined operations, modulo 1000000007 (109<=+<=7). | The first line contains a single integer *n* (1<=β€<=*n*<=β€<=105) β the number of operations of adding a vertex.
Next *n* lines contain descriptions of the operations, the *i*-th line contains the description of the operation of adding the *i*-th vertex in the following format: the first number of a line is an integer *k* (0<=β€<=*k*<=β€<=*i*<=-<=1), then follow 2*k* space-separated integers: *v*1,<=*x*1,<=*v*2,<=*x*2,<=... ,<=*v**k*,<=*x**k* (1<=β€<=*v**j*<=β€<=*i*<=-<=1,<=|*x**j*|<=β€<=109).
The operations are given in the order, in which they should be applied to the graph. It is guaranteed that sum *k* of all operations does not exceed 105, also that applying operations of adding vertexes does not result in loops and multiple edges. | Print a single number β the sum of weights of all edges of the resulting graph modulo 1000000007 (109<=+<=7). | [
"6\n0\n0\n1 2 1\n2 1 5 2 2\n1 1 2\n1 3 4\n",
"5\n0\n1 1 5\n0\n0\n2 3 1 4 3\n"
] | [
"30\n",
"9\n"
] | Conside the first sample:
1. Vertex 1 is added. *k*β=β0, thus no edges are added.1. Vertex 2 is added. *k*β=β0, thus no edges are added.1. Vertex 3 is added. *k*β=β1. *v*<sub class="lower-index">1</sub>β=β2, *x*<sub class="lower-index">1</sub>β=β1. Edge from vertex *root*(2)β=β2 to vertex 3 with weight *depth*(2)β+β*x*<sub class="lower-index">1</sub>β=β0β+β1β=β1 is added. 1. Vertex 4 is added. *k*β=β2. *v*<sub class="lower-index">1</sub>β=β1, *x*<sub class="lower-index">1</sub>β=β5. Edge from vertex *root*(1)β=β1 to vertex 4 with weight *depth*(1)β+β*x*<sub class="lower-index">1</sub>β=β0β+β5β=β5 is added. *v*<sub class="lower-index">2</sub>β=β2, *x*<sub class="lower-index">2</sub>β=β2. Edge from vertex *root*(2)β=β3 to vertex 4 with weight *depth*(2)β+β*x*<sub class="lower-index">1</sub>β=β1β+β2β=β3 is added.1. Vertex 5 is added. *k*β=β1. *v*<sub class="lower-index">1</sub>β=β1, *x*<sub class="lower-index">1</sub>β=β2. Edge from vertex *root*(1)β=β4 to vertex 5 with weight *depth*(1)β+β*x*<sub class="lower-index">1</sub>β=β5β+β2β=β7 is added.1. Vertex 6 is added. *k*β=β1. *v*<sub class="lower-index">1</sub>β=β3, *x*<sub class="lower-index">1</sub>β=β4. Edge from vertex *root*(3)β=β5 to vertex 6 with weight *depth*(3)β+β*x*<sub class="lower-index">1</sub>β=β10β+β4β=β14 is added.
The resulting graph is shown on the pictore below: <img class="tex-graphics" src="https://espresso.codeforces.com/0e06fef96694f14d20fdca3e3e44623b8e0c4bf1.png" style="max-width: 100.0%;max-height: 100.0%;"/> | [] | 2,000 | 12,800,000 | 0 | 106,728 | |
979 | Kuro and GCD and XOR and SUM | [
"binary search",
"bitmasks",
"brute force",
"data structures",
"dp",
"dsu",
"greedy",
"math",
"number theory",
"strings",
"trees"
] | null | null | Kuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day.
Sadly, he's going on a vacation for a day, and he isn't able to continue his solving streak on his own. As Katie is a reliable person, Kuro kindly asked her to come to his house on this day to play the game for him.
Initally, there is an empty array $a$. The game consists of $q$ tasks of two types. The first type asks Katie to add a number $u_i$ to $a$. The second type asks Katie to find a number $v$ existing in $a$ such that $k_i \mid GCD(x_i, v)$, $x_i + v \leq s_i$, and $x_i \oplus v$ is maximized, where $\oplus$ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), $GCD(c, d)$ denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers $c$ and $d$, and $y \mid x$ means $x$ is divisible by $y$, or report -1 if no such numbers are found.
Since you are a programmer, Katie needs you to automatically and accurately perform the tasks in the game to satisfy her dear friend Kuro. Let's help her! | The first line contains one integer $q$ ($2 \leq q \leq 10^{5}$) β the number of tasks the game wants you to perform.
$q$ lines follow, each line begins with an integer $t_i$ β the type of the task:
- If $t_i = 1$, an integer $u_i$ follow ($1 \leq u_i \leq 10^{5}$) β you have to add $u_i$ to the array $a$. - If $t_i = 2$, three integers $x_i$, $k_i$, and $s_i$ follow ($1 \leq x_i, k_i, s_i \leq 10^{5}$) β you must find a number $v$ existing in the array $a$ such that $k_i \mid GCD(x_i, v)$, $x_i + v \leq s_i$, and $x_i \oplus v$ is maximized, where $\oplus$ denotes the XOR operation, or report -1 if no such numbers are found.
It is guaranteed that the type of the first task is type $1$, and there exists at least one task of type $2$. | For each task of type $2$, output on one line the desired number $v$, or -1 if no such numbers are found. | [
"5\n1 1\n1 2\n2 1 1 3\n2 1 1 2\n2 1 1 1\n",
"10\n1 9\n2 9 9 22\n2 3 3 18\n1 25\n2 9 9 20\n2 25 25 14\n1 20\n2 26 26 3\n1 14\n2 20 20 9\n"
] | [
"2\n1\n-1\n",
"9\n9\n9\n-1\n-1\n-1\n"
] | In the first example, there are 5 tasks:
- The first task requires you to add $1$ into $a$. $a$ is now $\left\{1\right\}$. - The second task requires you to add $2$ into $a$. $a$ is now $\left\{1, 2\right\}$. - The third task asks you a question with $x = 1$, $k = 1$ and $s = 3$. Taking both $1$ and $2$ as $v$ satisfies $1 \mid GCD(1, v)$ and $1 + v \leq 3$. Because $2 \oplus 1 = 3 > 1 \oplus 1 = 0$, $2$ is the answer to this task. - The fourth task asks you a question with $x = 1$, $k = 1$ and $s = 2$. Only $v = 1$ satisfies $1 \mid GCD(1, v)$ and $1 + v \leq 2$, so $1$ is the answer to this task. - The fifth task asks you a question with $x = 1$, $k = 1$ and $s = 1$. There are no elements in $a$ that satisfy the conditions, so we report -1 as the answer to this task. | [] | 0 | 0 | -1 | 106,813 | |
332 | Students' Revenge | [
"data structures",
"greedy",
"sortings"
] | null | null | A student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banning automatic passes and other mean deeds. At last the students decided that she just can't get away with all this anymore...
The students pulled some strings on the higher levels and learned that the next University directors' meeting is going to discuss *n* orders about the chairperson and accept exactly *p* of them. There are two values assigned to each order: *a**i* is the number of the chairperson's hairs that turn grey if she obeys the order and *b**i* β the displeasement of the directors if the order isn't obeyed. The students may make the directors pass any *p* orders chosen by them. The students know that the chairperson will obey exactly *k* out of these *p* orders. She will pick the orders to obey in the way that minimizes first, the directors' displeasement and second, the number of hairs on her head that turn grey.
The students want to choose *p* orders in the way that maximizes the number of hairs on the chairperson's head that turn grey. If there are multiple ways to accept the orders, then the students are keen on maximizing the directors' displeasement with the chairperson's actions. Help them. | The first line contains three integers *n* (1<=β€<=*n*<=β€<=105), *p* (1<=β€<=*p*<=β€<=*n*), *k* (1<=β€<=*k*<=β€<=*p*) β the number of orders the directors are going to discuss, the number of orders to pass and the number of orders to be obeyed by the chairperson, correspondingly. Each of the following *n* lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=109), describing the corresponding order. | Print in an arbitrary order *p* distinct integers β the numbers of the orders to accept so that the students could carry out the revenge. The orders are indexed from 1 to *n* in the order they occur in the input. If there are multiple solutions, you can print any of them. | [
"5 3 2\n5 6\n5 8\n1 3\n4 3\n4 11\n",
"5 3 3\n10 18\n18 17\n10 20\n20 18\n20 18\n"
] | [
"3 1 2 ",
"2 4 5 "
] | In the first sample one of optimal solutions is to pass orders 1, 2, 3. In this case the chairperson obeys orders number 1 and 2. She gets 10 new grey hairs in the head and the directors' displeasement will equal 3. Note that the same result can be achieved with order 4 instead of order 3.
In the second sample, the chairperson can obey all the orders, so the best strategy for the students is to pick the orders with the maximum sum of *a*<sub class="lower-index">*i*</sub> values. The chairperson gets 58 new gray hairs and the directors' displeasement will equal 0. | [
{
"input": "5 3 2\n5 6\n5 8\n1 3\n4 3\n4 11",
"output": "3 1 2 "
},
{
"input": "5 3 3\n10 18\n18 17\n10 20\n20 18\n20 18",
"output": "2 4 5 "
},
{
"input": "10 7 4\n4 3\n5 3\n5 5\n4 3\n4 5\n3 5\n4 5\n4 4\n3 5\n4 5",
"output": "1 4 8 3 5 7 10 "
},
{
"input": "20 15 10\n79 84\n... | 30 | 0 | 0 | 107,799 | |
0 | none | [
"none"
] | null | null | Limak is a little grizzly bear. He will once attack Deerland but now he can only destroy trees in role-playing games. Limak starts with a tree with one vertex. The only vertex has index 1 and is a root of the tree.
Sometimes, a game chooses a subtree and allows Limak to attack it. When a subtree is attacked then each of its edges is destroyed with probability , independently of other edges. Then, Limak gets the penaltyΒ β an integer equal to the height of the subtree after the attack. The height is defined as the maximum number of edges on the path between the root of the subtree and any vertex in the subtree.
You must handle queries of two types.
- 1 v denotes a query of the first type. A new vertex appears and its parent is *v*. A new vertex has the next available index (so, new vertices will be numbered 2,<=3,<=...). - 2 v denotes a query of the second type. For a moment let's assume that the game allows Limak to attack a subtree rooted in *v*. Then, what would be the expected value of the penalty Limak gets after the attack?
In a query of the second type, Limak doesn't actually attack the subtree and thus the query doesn't affect next queries. | The first line of the input contains one integer *q* (1<=β€<=*q*<=β€<=500<=000)Β β the number of queries.
Then, *q* lines follow. The *i*-th of them contains two integers *type**i* and *v**i* (1<=β€<=*type**i*<=β€<=2). If *type**i*<==<=1 then *v**i* denotes a parent of a new vertex, while if *type**i*<==<=2 then you should print the answer for a subtree rooted in *v**i*.
It's guaranteed that there will be at least 1 query of the second type, that is, the output won't be empty.
It's guaranteed that just before the *i*-th query a vertex *v**i* already exists. | For each query of the second type print one real numberΒ βthe expected value of the penalty if Limak attacks the given subtree. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct if . | [
"7\n1 1\n1 1\n2 1\n1 2\n1 3\n2 2\n2 1\n",
"8\n2 1\n1 1\n1 2\n1 3\n1 4\n2 1\n1 4\n2 1\n"
] | [
"0.7500000000\n0.5000000000\n1.1875000000\n",
"0.0000000000\n0.9375000000\n0.9687500000\n"
] | Below, you can see the drawing for the first sample. Red circles denote queries of the second type. | [] | 30 | 0 | 0 | 108,460 | |
734 | Anton and Chess | [
"implementation"
] | null | null | Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.
The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.
Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move.
Help Anton and write the program that for the given position determines whether the white king is in check.
Remainder, on how do chess pieces move:
- Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells. - Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells. - Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap". | The first line of the input contains a single integer *n* (1<=β€<=*n*<=β€<=500<=000)Β β the number of black pieces.
The second line contains two integers *x*0 and *y*0 (<=-<=109<=β€<=*x*0,<=*y*0<=β€<=109)Β β coordinates of the white king.
Then follow *n* lines, each of them contains a character and two integers *x**i* and *y**i* (<=-<=109<=β€<=*x**i*,<=*y**i*<=β€<=109)Β β type of the *i*-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position. | The only line of the output should contains "YES" (without quotes) if the white king is in check and "NO" (without quotes) otherwise. | [
"2\n4 2\nR 1 1\nB 1 5\n",
"2\n4 2\nR 3 3\nB 1 5\n"
] | [
"YES\n",
"NO\n"
] | Picture for the first sample:
Picture for the second sample: | [
{
"input": "2\n4 2\nR 1 1\nB 1 5",
"output": "YES"
},
{
"input": "2\n4 2\nR 3 3\nB 1 5",
"output": "NO"
},
{
"input": "5\n-1 1\nR -10 10\nQ -9 9\nQ -2 -8\nB -6 10\nB -10 1",
"output": "YES"
},
{
"input": "20\n-321 454\nQ 967 -89\nR -811 454\nQ -404 454\nR -734 454\nQ -804 454... | 1,278 | 0 | 3 | 108,466 | |
883 | Berland.Taxi | [
"data structures"
] | null | null | Berland.Taxi is a new taxi company with *k* cars which started operating in the capital of Berland just recently. The capital has *n* houses on a straight line numbered from 1 (leftmost) to *n* (rightmost), and the distance between any two neighboring houses is the same.
You have to help the company schedule all the taxi rides which come throughout the day according to the following rules:
- All cars are available for picking up passengers. Initially the *j*-th car is located next to the house with the number *x**j* at time 0. - All cars have the same speed. It takes exactly 1 minute for any car to travel between neighboring houses *i* and *i*<=+<=1. - The *i*-th request for taxi ride comes at the time *t**i*, asking for a passenger to be picked up at the house *a**i* and dropped off at the house *b**i*. All requests for taxi rides are given in the increasing order of *t**i*. All *t**i* are distinct.
When a request for taxi ride is received at time *t**i*, Berland.Taxi operator assigns a car to it as follows:
- Out of cars which are currently available, operator assigns the car which is the closest to the pick up spot *a**i*. Needless to say, if a car is already on a ride with a passenger, it won't be available for any rides until that passenger is dropped off at the corresponding destination. - If there are several such cars, operator will pick one of them which has been waiting the most since it became available. - If there are several such cars, operator will pick one of them which has the lowest number.
After a car gets assigned to the taxi ride request:
- The driver immediately starts driving from current position to the house *a**i*. - Once the car reaches house *a**i*, the passenger is immediately picked up and the driver starts driving to house *b**i*. - Once house *b**i* is reached, the passenger gets dropped off and the car becomes available for new rides staying next to the house *b**i*. - It is allowed for multiple cars to be located next to the same house at the same point in time, while waiting for ride requests or just passing by.
If there are no available cars at time *t**i* when a request for taxi ride comes, then:
- The *i*-th passenger will have to wait for a car to become available. - When a car becomes available, operator will immediately assign it to this taxi ride request. - If multiple cars become available at once while the passenger is waiting, operator will pick a car out of them according to the rules described above.
Operator processes taxi ride requests one by one. So if multiple passengers are waiting for the cars to become available, operator will not move on to processing the (*i*<=+<=1)-th ride request until the car gets assigned to the *i*-th ride request.
Your task is to write a program that will process the given list of *m* taxi ride requests. For each request you have to find out which car will get assigned to it, and how long the passenger will have to wait for a car to arrive. Note, if there is already car located at the house *a**i*, then the corresponding wait time will be 0. | The first line of input contains integers *n*, *k* and *m* (2<=β€<=*n*<=β€<=2Β·105, 1<=β€<=*k*,<=*m*<=β€<=2Β·105) β number of houses, number of cars, and number of taxi ride requests. The second line contains integers *x*1,<=*x*2,<=...,<=*x**k* (1<=β€<=*x**i*<=β€<=*n*) β initial positions of cars. *x**i* is a house number at which the *i*-th car is located initially. It's allowed for more than one car to be located next to the same house.
The following *m* lines contain information about ride requests. Each ride request is represented by integers *t**j*, *a**j* and *b**j* (1<=β€<=*t**j*<=β€<=1012, 1<=β€<=*a**j*,<=*b**j*<=β€<=*n*, *a**j*<=β <=*b**j*), where *t**j* is time in minutes when a request is made, *a**j* is a house where passenger needs to be picked up, and *b**j* is a house where passenger needs to be dropped off. All taxi ride requests are given in the increasing order of *t**j*. All *t**j* are distinct. | Print *m* lines: the *j*-th line should contain two integer numbers, the answer for the *j*-th ride request β car number assigned by the operator and passenger wait time. | [
"10 1 2\n3\n5 2 8\n9 10 3\n",
"5 2 1\n1 5\n10 3 5\n",
"5 2 2\n1 5\n10 3 5\n20 4 1\n"
] | [
"1 1\n1 5\n",
"1 2\n",
"1 2\n2 1\n"
] | In the first sample test, a request comes in at time 5 and the car needs to get from house 3 to house 2 to pick up the passenger. Therefore wait time will be 1 and the ride will be completed at time 5β+β1β+β6β=β12. The second request comes in at time 9, so the passenger will have to wait for the car to become available at time 12, and then the car needs another 2 minutes to get from house 8 to house 10. So the total wait time is 3β+β2β=β5.
In the second sample test, cars 1 and 2 are located at the same distance from the first passenger and have the same "wait time since it became available". Car 1 wins a tiebreaker according to the rules because it has the lowest number. It will come to house 3 at time 3, so the wait time will be 2. | [] | 30 | 0 | 0 | 108,486 | |
542 | Playing on Graph | [
"graphs",
"shortest paths"
] | null | null | Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.
Vova has a non-directed graph consisting of *n* vertices and *m* edges without loops and multiple edges. Let's define the operation of contraction two vertices *a* and *b* that are not connected by an edge. As a result of this operation vertices *a* and *b* are deleted and instead of them a new vertex *x* is added into the graph, and also edges are drawn from it to all vertices that were connected with *a* or with *b* (specifically, if the vertex was connected with both *a* and *b*, then also exactly one edge is added from *x* to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (*n*<=-<=1) vertices.
Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length *k* (*k*<=β₯<=0) is a connected graph whose vertices can be numbered with integers from 1 to *k*<=+<=1 so that the edges of the graph connect all pairs of vertices (*i*,<=*i*<=+<=1) (1<=β€<=*i*<=β€<=*k*) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction.
Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. | The first line contains two integers *n*,<=*m* (1<=β€<=*n*<=β€<=1000, 0<=β€<=*m*<=β€<=100<=000) β the number of vertices and the number of edges in the original graph.
Next *m* lines contain the descriptions of edges in the format *a**i*,<=*b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*, *a**i*<=β <=*b**i*), which means that there is an edge between vertices *a**i* and *b**i*. It is guaranteed that there is at most one edge between each pair of vertexes. | If it is impossible to obtain a chain from the given graph, print <=-<=1. Otherwise, print the maximum possible number of edges in the resulting chain. | [
"5 4\n1 2\n2 3\n3 4\n3 5\n",
"4 6\n1 2\n2 3\n1 3\n3 4\n2 4\n1 4\n",
"4 2\n1 3\n2 4\n"
] | [
"3\n",
"-1\n",
"2\n"
] | In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3.
In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result.
In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. | [
{
"input": "5 4\n1 2\n2 3\n3 4\n3 5",
"output": "3"
},
{
"input": "4 6\n1 2\n2 3\n1 3\n3 4\n2 4\n1 4",
"output": "-1"
},
{
"input": "4 2\n1 3\n2 4",
"output": "2"
},
{
"input": "1 0",
"output": "0"
},
{
"input": "1000 0",
"output": "0"
},
{
"input": "1... | 0 | 0 | -1 | 108,730 | |
56 | Corporation Mail | [
"data structures",
"expression parsing",
"implementation"
] | C. Corporation Mail | 2 | 256 | The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
- *employee* ::= *name*. | *name*:*employee*1,*employee*2, ... ,*employee**k*. - *name* ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is *s* writes a letter to another person whose name is also *s*. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it. | The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length. | Print a single number β the number of uncomfortable situations in the company. | [
"MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...\n",
"A:A..\n",
"A:C:C:C:C.....\n"
] | [
"3\n",
"1\n",
"6\n"
] | none | [
{
"input": "A:A..",
"output": "1"
},
{
"input": "CK:CK.,CK.,CK..",
"output": "3"
},
{
"input": "RHLGWEVBJ:KAWUINWEI:KAWUINWEI..,ZQATMW.,KAWUINWEI.,RSWN..",
"output": "1"
},
{
"input": "GIRRY.",
"output": "0"
},
{
"input": "XGB:QJNGARRAZV:DWGDCCU:ARDKJV:P:MXBLZKLPY... | 218 | 0 | 0 | 109,211 |
40 | Number Table | [
"combinatorics"
] | E. Number Table | 2 | 216 | As it has been found out recently, all the Berland's current economical state can be described using a simple table *n*<=Γ<=*m* in size. *n* β the number of days in each Berland month, *m* β the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than *max*(*n*,<=*m*). However, there is additional information β the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo *p*. | The first line contains integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=1000). The second line contains the integer *k* (0<=β€<=*k*<=<<=*max*(*n*,<=*m*)) β the number of cells in which the data had been preserved. The next *k* lines contain the data on the state of the table in the preserved cells. Each line is of the form "*a* *b* *c*", where *a* (1<=β€<=*a*<=β€<=*n*) β the number of the table row, *b* (1<=β€<=*b*<=β€<=*m*) β the number of the column, *c* β the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same *a* and *b* values exist. The last line contains an integer *p* (2<=β€<=*p*<=β€<=109<=+<=7). | Print the number of different tables that could conform to the preserved data modulo *p*. | [
"2 2\n0\n100\n",
"2 2\n1\n1 1 -1\n100\n"
] | [
"2\n",
"1\n"
] | none | [
{
"input": "2 2\n0\n100",
"output": "2"
},
{
"input": "2 2\n1\n1 1 -1\n100",
"output": "1"
},
{
"input": "7 6\n4\n3 2 -1\n7 1 1\n2 1 1\n3 4 -1\n179460773",
"output": "0"
},
{
"input": "6 2\n3\n5 1 -1\n4 2 1\n1 2 -1\n958300150",
"output": "4"
},
{
"input": "6 9\n3\... | 92 | 0 | 0 | 109,296 |
933 | A Creative Cutout | [
"brute force",
"combinatorics",
"math"
] | null | null | Everything red frightens Nian the monster. So do red paper and... you, red on Codeforces, potential or real.
Big Banban has got a piece of paper with endless lattice points, where lattice points form squares with the same area. His most favorite closed shape is the circle because of its beauty and simplicity. Once he had obtained this piece of paper, he prepares it for paper-cutting.
He drew *n* concentric circles on it and numbered these circles from 1 to *n* such that the center of each circle is the same lattice point and the radius of the *k*-th circle is times the length of a lattice edge.
Define the degree of beauty of a lattice point as the summation of the indices of circles such that this lattice point is inside them, or on their bounds. Banban wanted to ask you the total degree of beauty of all the lattice points, but changed his mind.
Defining the total degree of beauty of all the lattice points on a piece of paper with *n* circles as *f*(*n*), you are asked to figure out . | The first line contains one integer *m* (1<=β€<=*m*<=β€<=1012). | In the first line print one integer representing . | [
"5\n",
"233\n"
] | [
"387\n",
"788243189\n"
] | A piece of paper with 5 circles is shown in the following.
There are 5 types of lattice points where the degree of beauty of each red point is 1β+β2β+β3β+β4β+β5β=β15, the degree of beauty of each orange point is 2β+β3β+β4β+β5β=β14, the degree of beauty of each green point is 4β+β5β=β9, the degree of beauty of each blue point is 5 and the degree of beauty of each gray point is 0. Therefore, *f*(5)β=β5Β·15β+β4Β·14β+β4Β·9β+β8Β·5β=β207.
Similarly, *f*(1)β=β5,β*f*(2)β=β23,β*f*(3)β=β50,β*f*(4)β=β102 and consequently <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/57bd086c10ae597f8cbd2785a92ae473165e1141.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | [] | 1,668 | 268,390,400 | 0 | 109,442 | |
990 | Flow Control | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | null | null | You have to handle a very complex water distribution system. The system consists of $n$ junctions and $m$ pipes, $i$-th pipe connects junctions $x_i$ and $y_i$.
The only thing you can do is adjusting the pipes. You have to choose $m$ integer numbers $f_1$, $f_2$, ..., $f_m$ and use them as pipe settings. $i$-th pipe will distribute $f_i$ units of water per second from junction $x_i$ to junction $y_i$ (if $f_i$ is negative, then the pipe will distribute $|f_i|$ units of water per second from junction $y_i$ to junction $x_i$). It is allowed to set $f_i$ to any integer from $-2 \cdot 10^9$ to $2 \cdot 10^9$.
In order for the system to work properly, there are some constraints: for every $i \in [1, n]$, $i$-th junction has a number $s_i$ associated with it meaning that the difference between incoming and outcoming flow for $i$-th junction must be exactly $s_i$ (if $s_i$ is not negative, then $i$-th junction must receive $s_i$ units of water per second; if it is negative, then $i$-th junction must transfer $|s_i|$ units of water per second to other junctions).
Can you choose the integers $f_1$, $f_2$, ..., $f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied? | The first line contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of junctions.
The second line contains $n$ integers $s_1, s_2, \dots, s_n$ ($-10^4 \le s_i \le 10^4$) β constraints for the junctions.
The third line contains an integer $m$ ($0 \le m \le 2 \cdot 10^5$) β the number of pipes.
$i$-th of the next $m$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$) β the description of $i$-th pipe. It is guaranteed that each unordered pair $(x, y)$ will appear no more than once in the input (it means that there won't be any pairs $(x, y)$ or $(y, x)$ after the first occurrence of $(x, y)$). It is guaranteed that for each pair of junctions there exists a path along the pipes connecting them. | If you can choose such integer numbers $f_1, f_2, \dots, f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied, then output "Possible" in the first line. Then output $m$ lines, $i$-th line should contain $f_i$ β the chosen setting numbers for the pipes. Pipes are numbered in order they appear in the input.
Otherwise output "Impossible" in the only line. | [
"4\n3 -10 6 1\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n",
"4\n3 -10 6 4\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n"
] | [
"Possible\n4\n-6\n8\n-7\n7\n",
"Impossible\n"
] | none | [
{
"input": "4\n3 -10 6 1\n5\n1 2\n3 2\n2 4\n3 4\n3 1",
"output": "Possible\n-3\n-6\n1\n0\n0"
},
{
"input": "4\n3 -10 6 4\n5\n1 2\n3 2\n2 4\n3 4\n3 1",
"output": "Impossible"
},
{
"input": "1\n0\n0",
"output": "Possible"
},
{
"input": "1\n123\n0",
"output": "Impossible"
... | 1,388 | 80,486,400 | 3 | 109,736 | |
765 | Souvenirs | [
"data structures"
] | null | null | Artsem is on vacation and wants to buy souvenirs for his two teammates. There are *n* souvenir shops along the street. In *i*-th shop Artsem can buy one souvenir for *a**i* dollars, and he cannot buy more than one souvenir in one shop. He doesn't want to introduce envy in his team, so he wants to buy two souvenirs with least possible difference in price.
Artsem has visited the shopping street *m* times. For some strange reason on the *i*-th day only shops with numbers from *l**i* to *r**i* were operating (weird? yes it is, but have you ever tried to come up with a reasonable legend for a range query problem?). For each visit, Artsem wants to know the minimum possible difference in prices of two different souvenirs he can buy in the opened shops.
In other words, for each Artsem's visit you should find the minimum possible value of |*a**s*<=-<=*a**t*| where *l**i*<=β€<=*s*,<=*t*<=β€<=*r**i*, *s*<=β <=*t*. | The first line contains an integer *n* (2<=β€<=*n*<=β€<=105).
The second line contains *n* space-separated integers *a*1, ..., *a**n* (0<=β€<=*a**i*<=β€<=109).
The third line contains the number of queries *m* (1<=β€<=*m*<=β€<=3Β·105).
Next *m* lines describe the queries. *i*-th of these lines contains two space-separated integers *l**i* and *r**i* denoting the range of shops working on *i*-th day (1<=β€<=*l**i*<=<<=*r**i*<=β€<=*n*). | Print the answer to each query in a separate line. | [
"8\n3 1 4 1 5 9 2 6\n4\n1 8\n1 3\n4 8\n5 7\n"
] | [
"0\n1\n1\n3\n"
] | none | [] | 3,000 | 921,600 | 0 | 109,861 | |
0 | none | [
"none"
] | null | null | Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium.
The digital board is *n* pixels in height and *m* pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The *j*-th pixel of the *i*-th line is pixel (*i*,<=*j*). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light.
Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (*i*,<=*j*) belongs to a side of sub-rectangle with (*x*1,<=*y*1) and (*x*2,<=*y*2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition:
Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them? | The first line contains three space-separated integers *n*, *m* and *q*Β (1<=β€<=*n*,<=*m*,<=*q*<=β€<=1000) β the height and width of the digital board, and the number of operations.
Then follow *n* lines, each line containing *m* space-separated integers. The *j*-th integer of the *i*-th line is *a**i*,<=*j* β the initial state of pixel (*i*,<=*j*).
- If *a**i*,<=*j*<==<=0, pixel (*i*,<=*j*) is initially dark. - If *a**i*,<=*j*<==<=1, pixel (*i*,<=*j*) is initially light.
Then follow *q* lines, each line containing three space-separated integers *op*, *x*, and *y*Β (1<=β€<=*op*<=β€<=2;Β 1<=β€<=*x*<=β€<=*n*;Β 1<=β€<=*y*<=β€<=*m*), describing an operation.
- If *op*<==<=1, the pixel at (*x*,<=*y*) changes its state (from light to dark or from dark to light). - If *op*<==<=2, Nanami queries the biggest light block with pixel (*x*,<=*y*) on its side. | For each query, print a single line containing one integer β the answer to Nanami's query. | [
"3 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n2 2 2\n2 1 2\n1 2 2\n1 2 3\n2 2 2\n",
"3 3 4\n1 1 1\n1 1 1\n1 1 1\n2 2 2\n1 2 2\n2 1 1\n2 2 1\n"
] | [
"0\n2\n6\n",
"6\n3\n3\n"
] | Consider the first sample.
The first query specifies pixel (2,β2), which is dark itself, so there are no valid light blocks, thus the answer is 0.
The second query specifies pixel (1,β2). The biggest light block is the block with (1,β2) as its upper-left vertex and (1,β3) as its lower-right vertex.
The last query specifies pixel (2,β2), which became light in the third operation. The biggest light block is the block with (1,β2) as its upper-left vertex and (3,β3) as its lower-right vertex. | [] | 77 | 0 | 0 | 109,904 | |
182 | Optimal Sum | [
"data structures",
"greedy"
] | null | null | And here goes another problem on arrays. You are given positive integer *len* and array *a* which consists of *n* integers *a*1, *a*2, ..., *a**n*. Let's introduce two characteristics for the given array.
- Let's consider an arbitrary interval of the array with length *len*, starting in position *i*. Value , is the modular sum on the chosen interval. In other words, the modular sum is the sum of integers on the chosen interval with length *len*, taken in its absolute value.- Value is the optimal sum of the array. In other words, the optimal sum of an array is the maximum of all modular sums on various intervals of array with length *len*.
Your task is to calculate the optimal sum of the given array *a*. However, before you do the calculations, you are allowed to produce no more than *k* consecutive operations of the following form with this array: one operation means taking an arbitrary number from array *a**i* and multiply it by -1. In other words, no more than *k* times you are allowed to take an arbitrary number *a**i* from the array and replace it with <=-<=*a**i*. Each number of the array is allowed to choose an arbitrary number of times.
Your task is to calculate the maximum possible optimal sum of the array after at most *k* operations described above are completed. | The first line contains two integers *n*, *len* (1<=β€<=*len*<=β€<=*n*<=β€<=105) β the number of elements in the array and the length of the chosen subinterval of the array, correspondingly.
The second line contains a sequence consisting of *n* integers *a*1, *a*2, ..., *a**n* (|*a**i*|<=β€<=109) β the original array.
The third line contains a single integer *k* (0<=β€<=*k*<=β€<=*n*) β the maximum allowed number of operations.
All numbers in lines are separated by a single space. | In a single line print the maximum possible optimal sum after no more than *k* acceptable operations are fulfilled.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. | [
"5 3\n0 -2 3 -5 1\n2\n",
"5 2\n1 -3 -10 4 1\n3\n",
"3 3\n-2 -5 4\n1\n"
] | [
"10\n",
"14\n",
"11\n"
] | none | [] | 0 | 0 | -1 | 110,069 | |
575 | Bribes | [
"dfs and similar",
"graphs",
"trees"
] | null | null | Ruritania is a country with a very badly maintained road network, which is not exactly good news for lorry drivers that constantly have to do deliveries. In fact, when roads are maintained, they become one-way. It turns out that it is sometimes impossible to get from one town to another in a legal way β however, we know that all towns are reachable, though illegally!
Fortunately for us, the police tend to be very corrupt and they will allow a lorry driver to break the rules and drive in the wrong direction provided they receive βa small giftβ. There is one patrol car for every road and they will request 1000 Ruritanian dinars when a driver drives in the wrong direction. However, being greedy, every time a patrol car notices the same driver breaking the rule, they will charge double the amount of money they requested the previous time on that particular road.
Borna is a lorry driver that managed to figure out this bribing pattern. As part of his job, he has to make *K* stops in some towns all over Ruritania and he has to make these stops in a certain order. There are *N* towns (enumerated from 1 to *N*) in Ruritania and Bornaβs initial location is the capital city i.e. town 1. He happens to know which ones out of the *N*<=-<=1 roads in Ruritania are currently unidirectional, but he is unable to compute the least amount of money he needs to prepare for bribing the police. Help Borna by providing him with an answer and you will be richly rewarded. | The first line contains *N*, the number of towns in Ruritania. The following *N*<=-<=1 lines contain information regarding individual roads between towns. A road is represented by a tuple of integers (*a*,*b*,*x*), which are separated with a single whitespace character. The numbers *a* and *b* represent the cities connected by this particular road, and x is either 0 or 1: 0 means that the road is bidirectional, 1 means that only the *a*<=β<=*b* direction is legal. The next line contains *K*, the number of stops Borna has to make. The final line of input contains K positive integers *s*1,<=β¦,<=*s**K*: the towns Borna has to visit.
- 1<=β€<=*N*<=β€<=105 - 1<=β€<=*K*<=β€<=106 - 1<=β€<=*a*,<=*b*<=β€<=*N* for all roads - for all roads - 1<=β€<=*s**i*<=β€<=*N* for all 1<=β€<=*i*<=β€<=*K* | The output should contain a single number: the least amount of thousands of Ruritanian dinars Borna should allocate for bribes, modulo 109<=+<=7. | [
"5\n1 2 0\n2 3 0\n5 1 1\n3 4 1\n5\n5 4 5 2 2\n"
] | [
"4\n"
] | Borna first takes the route 1βββ5 and has to pay 1000 dinars. After that, he takes the route 5βββ1βββ2βββ3βββ4 and pays nothing this time. However, when he has to return via 4βββ3βββ2βββ1βββ5, he needs to prepare 3000 (1000+2000) dinars. Afterwards, getting to 2 via 5βββ1βββ2 will cost him nothing. Finally, he doesn't even have to leave town 2 to get to 2, so there is no need to prepare any additional bribe money. Hence he has to prepare 4000 dinars in total. | [] | 62 | 0 | 0 | 110,072 | |
0 | none | [
"none"
] | null | null | You play the game with your friend. The description of this game is listed below.
Your friend creates *n* distinct strings of the same length *m* and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the *n* strings equals . You want to guess which string was chosen by your friend.
In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position *pos* in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions.
You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend. | The first line contains a single integer *n* (1<=β€<=*n*<=β€<=50)Β β the number of strings your friend came up with.
The next *n* lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive. | Print the single number β the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=9. | [
"2\naab\naac\n",
"3\naaA\naBa\nCaa\n",
"3\naca\nvac\nwqq\n"
] | [
"2.000000000000000\n",
"1.666666666666667\n",
"1.000000000000000\n"
] | In the first sample the strings only differ in the character in the third position. So only the following situations are possible:
- you guess the string in one question. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/>; - you guess the string in two questions. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/caddcdaf0d707d9e4ffa41e63e462a3c90474546.png" style="max-width: 100.0%;max-height: 100.0%;"/> Β· <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6bb1686dc4a3e6a10e00b92d434455668cb330a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/> (as in this case the first question should ask about the position that is other than the third one); - you guess the string in three questions. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/caddcdaf0d707d9e4ffa41e63e462a3c90474546.png" style="max-width: 100.0%;max-height: 100.0%;"/> Β· <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6bb1686dc4a3e6a10e00b92d434455668cb330a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> Β· <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a53d50910d43b79b6602f97f9fde950c9d1bdf77.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/>;
Thus, the expected value is equal to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5f789afab0601bacf9123c73584184ef358740fb.png" style="max-width: 100.0%;max-height: 100.0%;"/>
In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/208df5d4b6316ba263eede5d4cf4b844075718f1.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the third sample whatever position we ask about in the first question, we immediately identify the string. | [] | 46 | 0 | 0 | 110,241 | |
34 | Collisions | [
"brute force",
"implementation",
"math"
] | E. Collisions | 2 | 256 | On a number line there are *n* balls. At time moment 0 for each ball the following data is known: its coordinate *x**i*, speed *v**i* (possibly, negative) and weight *m**i*. The radius of the balls can be ignored.
The balls collide elastically, i.e. if two balls weighing *m*1 and *m*2 and with speeds *v*1 and *v*2 collide, their new speeds will be:
Your task is to find out, where each ball will be *t* seconds after. | The first line contains two integers *n* and *t* (1<=β€<=*n*<=β€<=10,<=0<=β€<=*t*<=β€<=100) β amount of balls and duration of the process. Then follow *n* lines, each containing three integers: *x**i*, *v**i*, *m**i* (1<=β€<=|*v**i*|,<=*m**i*<=β€<=100,<=|*x**i*|<=β€<=100) β coordinate, speed and weight of the ball with index *i* at time moment 0.
It is guaranteed that no two balls have the same coordinate initially. Also each collision will be a collision of not more than two balls (that is, three or more balls never collide at the same point in all times from segment [0;*t*]). | Output *n* numbers β coordinates of the balls *t* seconds after. Output the numbers accurate to at least 4 digits after the decimal point. | [
"2 9\n3 4 5\n0 7 8\n",
"3 10\n1 2 3\n4 -5 6\n7 -8 9\n"
] | [
"68.538461538\n44.538461538\n",
"-93.666666667\n-74.666666667\n-15.666666667\n"
] | none | [
{
"input": "2 9\n3 4 5\n0 7 8",
"output": "68.538461538\n44.538461538"
},
{
"input": "3 10\n1 2 3\n4 -5 6\n7 -8 9",
"output": "-93.666666667\n-74.666666667\n-15.666666667"
},
{
"input": "6 76\n-35 -79 86\n-76 -20 64\n-91 79 10\n12 25 51\n62 6 30\n8 -14 65",
"output": "-980.877658851\... | 92 | 0 | 0 | 110,446 |
0 | none | [
"none"
] | null | null | Petya likes horse racing very much. Horses numbered from *l* to *r* take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance between which does not exceed *k*. Petya learned from some of his mates from Lviv that lucky digits are digits 4 and 7. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if *k*<==<=2, then numbers 412395497, 404, 4070400000070004007 are nearly lucky and numbers 4, 4123954997, 4007000040070004007 are not.
Petya prepared *t* intervals [*l**i*,<=*r**i*] and invented number *k*, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo 1000000007 (109<=+<=7). | The first line contains two integers *t* and *k* (1<=β€<=*t*,<=*k*<=β€<=1000) β the number of segments and the distance between the numbers correspondingly. Next *t* lines contain pairs of integers *l**i* and *r**i* (1<=β€<=*l*<=β€<=*r*<=β€<=101000). All numbers are given without the leading zeroes. Numbers in each line are separated by exactly one space character. | Output *t* lines. In each line print one integer β the answer for the corresponding segment modulo 1000000007 (109<=+<=7). | [
"1 2\n1 100\n",
"1 2\n70 77\n",
"2 1\n1 20\n80 100\n"
] | [
"4\n",
"2\n",
"0\n0\n"
] | In the first sample, the four nearly lucky numbers are 44, 47, 74, 77.
In the second sample, only 74 and 77 are in the given segment. | [] | 60 | 0 | 0 | 110,598 | |
303 | Minimum Modular | [
"brute force",
"graphs",
"math",
"number theory"
] | null | null | You have been given *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n*. You can remove at most *k* of them. Find the minimum modular *m* (*m*<=><=0), so that for every pair of the remaining integers (*a**i*,<=*a**j*), the following unequality holds: . | The first line contains two integers *n* and *k* (1<=<=β€<=*n*<=<=β€<=5000,<=0<=β€<=*k*<=β€<=4), which we have mentioned above.
The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=106). | Print a single positive integer β the minimum *m*. | [
"7 0\n0 2 3 6 7 12 18\n",
"7 1\n0 2 3 6 7 12 18\n"
] | [
"13\n",
"7\n"
] | none | [] | 2,000 | 67,072,000 | 0 | 110,805 | |
459 | Pashmak and Graph | [
"dp",
"sortings"
] | null | null | Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.
You are given a weighted directed graph with *n* vertices and *m* edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.
Help Pashmak, print the number of edges in the required path. | The first line contains two integers *n*, *m* (2<=β€<=*n*<=β€<=3Β·105;Β 1<=β€<=*m*<=β€<=*min*(*n*Β·(*n*<=-<=1),<=3Β·105)). Then, *m* lines follows. The *i*-th line contains three space separated integers: *u**i*, *v**i*, *w**i* (1<=β€<=*u**i*,<=*v**i*<=β€<=*n*;Β 1<=β€<=*w**i*<=β€<=105) which indicates that there's a directed edge with weight *w**i* from vertex *u**i* to vertex *v**i*.
It's guaranteed that the graph doesn't contain self-loops and multiple edges. | Print a single integer β the answer to the problem. | [
"3 3\n1 2 1\n2 3 1\n3 1 1\n",
"3 3\n1 2 1\n2 3 2\n3 1 3\n",
"6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4\n"
] | [
"1\n",
"3\n",
"6\n"
] | In the first sample the maximum trail can be any of this trails: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1534088dd4d998a9bcc7e17dba96f7c213c54fc6.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second sample the maximum trail is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9b1d1f66686c43090329870c208942499764a73b.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the third sample the maximum trail is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1db1cef44580d43663d6896f0190e5ccee9502c9.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | [
{
"input": "3 3\n1 2 1\n2 3 1\n3 1 1",
"output": "1"
},
{
"input": "3 3\n1 2 1\n2 3 2\n3 1 3",
"output": "3"
},
{
"input": "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4",
"output": "6"
},
{
"input": "2 2\n1 2 1\n2 1 2",
"output": "2"
},
{
"input": "4 3\n1 ... | 1,000 | 22,220,800 | 0 | 111,627 | |
486 | Valid Sets | [
"dfs and similar",
"dp",
"math",
"trees"
] | null | null | As you know, an undirected connected graph with *n* nodes and *n*<=-<=1 edges is called a tree. You are given an integer *d* and a tree consisting of *n* nodes. Each node *i* has a value *a**i* associated with it.
We call a set *S* of tree nodes valid if following conditions are satisfied:
1. *S* is non-empty.1. *S* is connected. In other words, if nodes *u* and *v* are in *S*, then all nodes lying on the simple path between *u* and *v* should also be presented in *S*.1. .
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109<=+<=7). | The first line contains two space-separated integers *d* (0<=β€<=*d*<=β€<=2000) and *n* (1<=β€<=*n*<=β€<=2000).
The second line contains *n* space-separated positive integers *a*1,<=*a*2,<=...,<=*a**n*(1<=β€<=*a**i*<=β€<=2000).
Then the next *n*<=-<=1 line each contain pair of integers *u* and *v* (1<=β€<=*u*,<=*v*<=β€<=*n*) denoting that there is an edge between *u* and *v*. It is guaranteed that these edges form a tree. | Print the number of valid sets modulo 1000000007. | [
"1 4\n2 1 3 2\n1 2\n1 3\n3 4\n",
"0 3\n1 2 3\n1 2\n2 3\n",
"4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4\n"
] | [
"8\n",
"3\n",
"41\n"
] | In the first sample, there are exactly 8 valid sets: {1},β{2},β{3},β{4},β{1,β2},β{1,β3},β{3,β4} and {1,β3,β4}. Set {1,β2,β3,β4} is not valid, because the third condition isn't satisfied. Set {1,β4} satisfies the third condition, but conflicts with the second condition. | [] | 30 | 0 | 0 | 111,843 | |
0 | none | [
"none"
] | null | null | In the country of Never, there are *n* cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered by Neverians.
An independent committee has evaluated each road of Never with a positive integer called the perishability of the road. The lower the road's perishability is, the more pleasant it is to drive through this road.
It's the year of transport in Never. It has been decided to build a museum of transport in one of the cities, and to set a single signpost directing to some city (not necessarily the one with the museum) in each of the other cities. The signposts must satisfy the following important condition: if any Neverian living in a city without the museum starts travelling from that city following the directions of the signposts, then this person will eventually arrive in the city with the museum.
Neverians are incredibly positive-minded. If a Neverian travels by a route consisting of several roads, he considers the perishability of the route to be equal to the smallest perishability of all the roads in this route.
The government of Never has not yet decided where to build the museum, so they consider all *n* possible options. The most important is the sum of perishabilities of the routes to the museum city from all the other cities of Never, if the travelers strictly follow the directions of the signposts. The government of Never cares about their citizens, so they want to set the signposts in a way which minimizes this sum. Help them determine the minimum possible sum for all *n* possible options of the city where the museum can be built. | The first line contains a single integer *n* (2<=β€<=*n*<=β€<=2000)Β β the number of cities in Never.
The following *n*<=-<=1 lines contain the description of the road network. The *i*-th of these lines contains *n*<=-<=*i* integers. The *j*-th integer in the *i*-th line denotes the perishability of the road between cities *i* and *i*<=+<=*j*.
All road perishabilities are between 1 and 109, inclusive. | For each city in order from 1 to *n*, output the minimum possible sum of perishabilities of the routes to this city from all the other cities of Never if the signposts are set in a way which minimizes this sum. | [
"3\n1 2\n3\n",
"6\n2 9 9 6 6\n7 1 9 10\n9 2 5\n4 10\n8\n"
] | [
"2\n2\n3\n",
"6\n5\n7\n5\n7\n11\n"
] | The first example is explained by the picture below. From left to right, there is the initial road network and the optimal directions of the signposts in case the museum is built in city 1, 2 and 3, respectively. The museum city is represented by a blue circle, the directions of the signposts are represented by green arrows.
For instance, if the museum is built in city 3, then the signpost in city 1 must be directed to city 3, while the signpost in city 2 must be directed to city 1. Then the route from city 1 to city 3 will have perishability 2, while the route from city 2 to city 3 will have perishability 1. The sum of perishabilities of these routes is 3. | [] | 3,000 | 46,489,600 | 0 | 112,165 | |
756 | Long number | [
"expression parsing",
"math",
"number theory"
] | null | null | Consider the following grammar:
- <expression> ::= <term> | <expression> '+' <term>- <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')'- <number> ::= <pos_digit> | <number> <digit>- <digit> ::= '0' | <pos_digit>- <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
This grammar describes a number in decimal system using the following rules:
- <number> describes itself,- <number>-<number> (l-r, *l*<=β€<=*r*) describes integer which is concatenation of all integers from *l* to *r*, written without leading zeros. For example, 8-11 describes 891011,- <number>(<expression>) describes integer which is concatenation of <number> copies of integer described by <expression>,- <expression>+<term> describes integer which is concatenation of integers described by <expression> and <term>.
For example, 2(2-4+1)+2(2(17)) describes the integer 2341234117171717.
You are given an expression in the given grammar. Print the integer described by it modulo 109<=+<=7. | The only line contains a non-empty string at most 105 characters long which is valid according to the given grammar. In particular, it means that in terms l-r *l*<=β€<=*r* holds. | Print single integerΒ β the number described by the expression modulo 109<=+<=7. | [
"8-11\n",
"2(2-4+1)+2(2(17))\n",
"1234-5678\n",
"1+2+3+4-5+6+7-9\n"
] | [
"891011\n",
"100783079\n",
"745428774\n",
"123456789\n"
] | none | [
{
"input": "8-11",
"output": "891011"
},
{
"input": "2(2-4+1)+2(2(17))",
"output": "100783079"
},
{
"input": "1234-5678",
"output": "745428774"
},
{
"input": "1+2+3+4-5+6+7-9",
"output": "123456789"
},
{
"input": "598777",
"output": "598777"
},
{
"inpu... | 2,000 | 13,414,400 | 0 | 112,175 | |
643 | Choosing Ads | [
"data structures"
] | null | null | One social network developer recently suggested a new algorithm of choosing ads for users.
There are *n* slots which advertisers can buy. It is possible to buy a segment of consecutive slots at once. The more slots you own, the bigger are the chances your ad will be shown to users.
Every time it is needed to choose ads to show, some segment of slots is picked by a secret algorithm. Then some advertisers are chosen. The only restriction is that it should be guaranteed for advertisers which own at least *p*% of slots composing this segment that their ad will be shown.
From the other side, users don't like ads. So it was decided to show no more than ads at once. You are asked to develop a system to sell segments of slots and choose ads in accordance with the rules described above. | The first line of the input contains three integers *n*, *m* and *p* (1<=β€<=*n*,<=*m*<=β€<=150<=000,<=20<=β€<=*p*<=β€<=100)Β β the number of slots, the number of queries to your system and threshold for which display of the ad is guaranteed.
Next line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=150<=000), where the *i*-th number means id of advertiser who currently owns the *i*-th slot.
Next *m* lines contain queries descriptions. Each description is of one of the following forms:
- 1 l r id (1<=β€<=*l*<=β€<=*r*<=β€<=*n*,<=1<=β€<=*id*<=β€<=150 000)Β β advertiser *id* bought all slots in a range from *l* to *r* inclusive; - 2 l r (1<=β€<=*l*<=β€<=*r*)Β β you need to choose advertisers for segment [*l*,<=*r*]. | For each query of the second type answer should be printed in a separate line. First integer of the answer should be the number of advertisements that will be shown . Next *cnt* integers should be advertisers' ids.
It is allowed to print one advertiser more than once, but each advertiser that owns at least slots of the segment from *l* to *r* should be in your answer. | [
"5 9 33\n1 2 1 3 3\n2 1 5\n2 1 5\n2 1 3\n2 3 3\n1 2 4 5\n2 1 5\n2 3 5\n1 4 5 1\n2 1 5\n"
] | [
"3 1 2 3\n2 1 3\n2 2 1\n3 1 1000 1000\n1 5\n2 5 3\n2 1 5"
] | Samples demonstrate that you actually have quite a lot of freedom in choosing advertisers. | [] | 46 | 0 | 0 | 112,676 | |
598 | Cut Length | [
"geometry"
] | null | null | Given simple (without self-intersections) *n*-gon. It is not necessary convex. Also you are given *m* lines. For each line find the length of common part of the line and the *n*-gon.
The boundary of *n*-gon belongs to polygon. It is possible that *n*-gon contains 180-degree angles. | The first line contains integers *n* and *m* (3<=β€<=*n*<=β€<=1000;1<=β€<=*m*<=β€<=100). The following *n* lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following *m* lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values. | Print *m* lines, the *i*-th line should contain the length of common part of the given *n*-gon and the *i*-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=6. | [
"4 3\n0 0\n1 0\n1 1\n0 1\n0 0 1 1\n0 0 0 1\n0 0 1 -1\n"
] | [
"1.41421356237309514547\n1.00000000000000000000\n0.00000000000000000000\n"
] | none | [
{
"input": "4 3\n0 0\n1 0\n1 1\n0 1\n0 0 1 1\n0 0 0 1\n0 0 1 -1",
"output": "1.41421356237309514547\n1.00000000000000000000\n0.00000000000000000000"
},
{
"input": "4 9\n0 0\n0 1\n1 1\n1 0\n0 0 1 1\n1 1 0 0\n0 0 1 0\n0 0 0.5 0\n0 0.5 1 0.5\n0 1 1 1\n1 1 1 0\n0.75 0.75 0.75 0.25\n0 0.25 1 0.75",
"... | 46 | 0 | 0 | 112,773 | |
0 | none | [
"none"
] | null | null | There are *n* bears in the inn and *p* places to sleep. Bears will party together for some number of nights (and days).
Bears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.
A bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.
Radewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.
Each night, the following happens in this exact order:
1. Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears. 1. Each bear drinks a glass from each barrel he chose. 1. All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.
At the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).
Radewoosh wants to allow bears to win. He considers *q* scenarios. In the *i*-th scenario the party will last for *i* nights. Then, let *R**i* denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define . Your task is to find , where denotes the exclusive or (also denoted as XOR).
Note that the same barrel may be chosen by many bears and all of them will go to sleep at once. | The only line of the input contains three integers *n*, *p* and *q* (1<=β€<=*n*<=β€<=109, 1<=β€<=*p*<=β€<=130, 1<=β€<=*q*<=β€<=2<=000<=000)Β β the number of bears, the number of places to sleep and the number of scenarios, respectively. | Print one integer, equal to . | [
"5 1 3\n",
"1 100 4\n",
"3 2 1\n",
"100 100 100\n"
] | [
"32\n",
"4\n",
"7\n",
"381863924\n"
] | In the first sample, there are 5 bears and only 1 place to sleep. We have *R*<sub class="lower-index">1</sub>β=β6,β*R*<sub class="lower-index">2</sub>β=β11,β*R*<sub class="lower-index">3</sub>β=β16 so the answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b3272ae710321a0a8ceffa5d8c9afe3bf54e75eb.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Let's analyze the optimal strategy for scenario with 2 days. There are *R*<sub class="lower-index">2</sub>β=β11 barrels and 10 of them contain juice.
- In the first night, the *i*-th bear chooses a barrel *i* only. <ul> <li> If one of the first 5 barrels contains wine then one bear goes to sleep. Then, bears win because they know where wine is and there is at least one awake bear. - But let's say none of the first 5 barrels contains wine. In the second night, the *i*-th bear chooses a barrel 5β+β*i*. <ul> <li> If one of barrels 6βββ10 contains wine then one bear goes to sleep. And again, bears win in such a situation. - If nobody went to sleep then wine is in a barrel 11.
In the second sample, there is only one bear. He should choose an empty set of barrels in each night. Otherwise, he would maybe get wine and bears would lose (because there must be at least one awake bear). So, for any number of days we have *R*<sub class="lower-index">*i*</sub>β=β1. The answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c8b4cc3bcaf1329398e221289359b01c0a392ec5.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | [] | 5,000 | 4,198,400 | 0 | 112,807 | |
117 | Not Quick Transformation | [
"divide and conquer",
"math"
] | null | null | Let *a* be an array consisting of *n* numbers. The array's elements are numbered from 1 to *n*, *even* is an array consisting of the numerals whose numbers are even in *a* (*even**i*<==<=*a*2*i*, 1<=β€<=2*i*<=β€<=*n*), *odd* is an array consisting of the numberals whose numbers are odd in *Π°* (*odd**i*<==<=*a*2*i*<=-<=1, 1<=β€<=2*i*<=-<=1<=β€<=*n*). Then let's define the transformation of array *F*(*a*) in the following manner:
- if *n*<=><=1, *F*(*a*)<==<=*F*(*odd*)<=+<=*F*(*even*), where operation "<=+<=" stands for the arrays' concatenation (joining together) - if *n*<==<=1, *F*(*a*)<==<=*a*
Let *a* be an array consisting of *n* numbers 1,<=2,<=3,<=...,<=*n*. Then *b* is the result of applying the transformation to the array *a* (so *b*<==<=*F*(*a*)). You are given *m* queries (*l*,<=*r*,<=*u*,<=*v*). Your task is to find for each query the sum of numbers *b**i*, such that *l*<=β€<=*i*<=β€<=*r* and *u*<=β€<=*b**i*<=β€<=*v*. You should print the query results modulo *mod*. | The first line contains three integers *n*, *m*, *mod* (1<=β€<=*n*<=β€<=1018,<=1<=β€<=*m*<=β€<=105,<=1<=β€<=*mod*<=β€<=109). Next *m* lines describe the queries. Each query is defined by four integers *l*, *r*, *u*, *v* (1<=β€<=*l*<=β€<=*r*<=β€<=*n*, 1<=β€<=*u*<=β€<=*v*<=β€<=1018).
Please do not use the %lld specificator to read or write 64-bit integers in C++. Use %I64d specificator. | Print *m* lines each containing an integer β remainder modulo *mod* of the query result. | [
"4 5 10000\n2 3 4 5\n2 4 1 3\n1 2 2 4\n2 3 3 5\n1 3 3 4\n",
"2 5 10000\n1 2 2 2\n1 1 4 5\n1 1 2 5\n1 1 1 3\n1 2 5 5\n"
] | [
"0\n5\n3\n3\n3\n",
"2\n0\n0\n1\n0\n"
] | Let's consider the first example. First let's construct an array *b*β=β*F*(*a*)β=β*F*([1,β2,β3,β4]).
- Step 1. *F*([1,β2,β3,β4])β=β*F*([1,β3])β+β*F*([2,β4]) - Step 2. *F*([1,β3])β=β*F*([1])β+β*F*([3])β=β[1]β+β[3]β=β[1,β3] - Step 3. *F*([2,β4])β=β*F*([2])β+β*F*([4])β=β[2]β+β[4]β=β[2,β4] - Step 4. *b*β=β*F*([1,β2,β3,β4])β=β*F*([1,β3])β+β*F*([2,β4])β=β[1,β3]β+β[2,β4]β=β[1,β3,β2,β4] | [] | 154 | 0 | -1 | 113,064 | |
45 | Goats and Wolves | [
"greedy"
] | F. Goats and Wolves | 2 | 256 | Once Vasya needed to transport *m* goats and *m* wolves from riverbank to the other as quickly as possible. The boat can hold *n* animals and Vasya, in addition, he is permitted to put less than *n* animals in the boat. If in one place (on one of the banks or in the boat) the wolves happen to strictly outnumber the goats, then the wolves eat the goats and Vasya gets upset. When Vasya swims on the boat from one shore to the other, he must take at least one animal to accompany him, otherwise he will get bored and he will, yet again, feel upset. When the boat reaches the bank, first all the animals get off simultaneously, and then the animals chosen by Vasya simultaneously get on the boat. That means that at the moment when the animals that have just arrived have already got off and the animals that are going to leave haven't yet got on, somebody might eat someone. Vasya needs to transport all the animals from one river bank to the other so that nobody eats anyone and Vasya doesn't get upset. What is the minimal number of times he will have to cross the river? | The first line contains two space-separated numbers *m* and *n* (1<=β€<=*m*,<=*n*<=β€<=105) β the number of animals and the boat's capacity. | If it is impossible to transport all the animals so that no one got upset, and all the goats survived, print -1. Otherwise print the single number β how many times Vasya will have to cross the river. | [
"3 2\n",
"33 3\n"
] | [
"11\n",
"-1\n"
] | The first sample match to well-known problem for children. | [
{
"input": "3 2",
"output": "11"
},
{
"input": "33 3",
"output": "-1"
},
{
"input": "2 3",
"output": "3"
},
{
"input": "100000 100000",
"output": "5"
},
{
"input": "100000 4",
"output": "199997"
},
{
"input": "1 3",
"output": "1"
},
{
"inpu... | 62 | 0 | 0 | 113,597 |
60 | Mushroom Gnomes | [
"math",
"matrices"
] | E. Mushroom Gnomes | 3 | 256 | Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighboring ones.
The mushroom gnomes loved it when everything was in order, that's why they always planted the mushrooms in one line in the order of their weights' increasing. Well... The gnomes planted the mushrooms and went to eat. After *x* minutes they returned and saw that new mushrooms had grown up, so that the increasing order had been violated. The gnomes replanted all the mushrooms in the correct order, that is, they sorted the mushrooms in the order of the weights' increasing. And went to eat again (those gnomes were quite big eaters). What total weights modulo *p* will the mushrooms have in another *y* minutes? | The first line contains four integers *n*, *x*, *y*, *p* (1<=β€<=*n*<=β€<=106,<=0<=β€<=*x*,<=*y*<=β€<=1018,<=*x*<=+<=*y*<=><=0,<=2<=β€<=*p*<=β€<=109) which represent the number of mushrooms, the number of minutes after the first replanting, the number of minutes after the second replanting and the module. The next line contains *n* integers *a**i* which represent the mushrooms' weight in the non-decreasing order (0<=β€<=*a**i*<=β€<=109).
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). | The answer should contain a single number which is the total weights of the mushrooms modulo *p* in the end after *x*<=+<=*y* minutes. | [
"2 1 0 657276545\n1 2\n",
"2 1 1 888450282\n1 2\n",
"4 5 0 10000\n1 2 3 4\n"
] | [
"6\n",
"14\n",
"1825\n"
] | none | [
{
"input": "2 1 0 657276545\n1 2",
"output": "6"
},
{
"input": "2 1 1 888450282\n1 2",
"output": "14"
},
{
"input": "4 5 0 10000\n1 2 3 4",
"output": "1825"
},
{
"input": "4 0 8 78731972\n1 52 76 81",
"output": "1108850"
},
{
"input": "4 0 8 414790855\n1 88 97 99"... | 92 | 0 | 0 | 113,635 |
677 | Vanya and Treasure | [
"data structures",
"dp",
"graphs",
"shortest paths"
] | null | null | Vanya is in the palace that can be represented as a grid *n*<=Γ<=*m*. Each room contains a single chest, an the room located in the *i*-th row and *j*-th columns contains the chest of type *a**ij*. Each chest of type *x*<=β€<=*p*<=-<=1 contains a key that can open any chest of type *x*<=+<=1, and all chests of type 1 are not locked. There is exactly one chest of type *p* and it contains a treasure.
Vanya starts in cell (1,<=1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (*r*1,<=*c*1) (the cell in the row *r*1 and column *c*1) and (*r*2,<=*c*2) is equal to |*r*1<=-<=*r*2|<=+<=|*c*1<=-<=*c*2|. | The first line of the input contains three integers *n*, *m* and *p* (1<=β€<=*n*,<=*m*<=β€<=300,<=1<=β€<=*p*<=β€<=*n*Β·*m*)Β β the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively.
Each of the following *n* lines contains *m* integers *a**ij* (1<=β€<=*a**ij*<=β€<=*p*)Β β the types of the chests in corresponding rooms. It's guaranteed that for each *x* from 1 to *p* there is at least one chest of this type (that is, there exists a pair of *r* and *c*, such that *a**rc*<==<=*x*). Also, it's guaranteed that there is exactly one chest of type *p*. | Print one integerΒ β the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type *p*. | [
"3 4 3\n2 1 1 1\n1 1 1 1\n2 1 1 3\n",
"3 3 9\n1 3 5\n8 9 7\n4 6 2\n",
"3 4 12\n1 2 3 4\n8 7 6 5\n9 10 11 12\n"
] | [
"5\n",
"22\n",
"11\n"
] | none | [] | 30 | 0 | 0 | 114,100 | |
550 | Regular Bridge | [
"constructive algorithms",
"graphs",
"implementation"
] | null | null | An undirected graph is called *k*-regular, if the degrees of all its vertices are equal *k*. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected *k*-regular graph containing at least one bridge, or else state that such graph doesn't exist. | The single line of the input contains integer *k* (1<=β€<=*k*<=β€<=100) β the required degree of the vertices of the regular graph. | Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers *n* and *m* β the number of vertices and edges respectively.
Each of the next *m* lines must contain two integers, *a* and *b* (1<=β€<=*a*,<=*b*<=β€<=*n*, *a*<=β <=*b*), that mean that there is an edge connecting the vertices *a* and *b*. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal *k*. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges). | [
"1\n"
] | [
"YES\n2 1\n1 2\n"
] | In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | [
{
"input": "1",
"output": "YES\n2 1\n1 2"
},
{
"input": "3",
"output": "YES\n10 15\n1 6\n1 2\n1 3\n2 4\n2 5\n3 4\n3 5\n4 5\n6 7\n6 8\n7 9\n7 10\n8 9\n8 10\n9 10"
},
{
"input": "11",
"output": "YES\n26 143\n1 14\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n2 12\n2 13\n2 4\n2 5... | 46 | 0 | 0 | 114,357 | |
847 | Berland SU Computer Network | [
"constructive algorithms",
"dfs and similar",
"graphs",
"hashing",
"trees"
] | null | null | In the computer network of the Berland State University there are *n* routers numbered from 1 to *n*. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through other routers) is possible. There are no cycles in the network, so there is only one path between each pair of routers over patch cords.
Unfortunately, the exact topology of the network was lost by administrators. In order to restore it, the following auxiliary information was collected.
For each patch cord *p*, directly connected to the router *i*, list of routers located behind the patch cord *p* relatively *i* is known. In other words, all routers path from which to the router *i* goes through *p* are known. So for each router *i* there are *k**i* lists, where *k**i* is the number of patch cords connected to *i*.
For example, let the network consists of three routers connected in chain 1<=-<=2<=-<=3. Then:
- the router 1: for the single patch cord connected to the first router there is a single list containing two routers: 2 and 3; - the router 2: for each of the patch cords connected to the second router there is a list: one list contains the router 1 and the other β the router 3; - the router 3: for the single patch cord connected to the third router there is a single list containing two routers: 1 and 2.
Your task is to help administrators to restore the network topology, i. e. to identify all pairs of routers directly connected by a patch cord. | The first line contains a single integer *n* (2<=β€<=*n*<=β€<=1000) β the number of routers in the network.
The *i*-th of the following *n* lines contains a description of the lists for the router *i*.
The description of each list begins with the number of routers in it. Then the symbol ':' follows, and after that the numbers of routers from the list are given. This numbers are separated by comma. Lists are separated by symbol '-'.
It is guaranteed, that for each router *i* the total number of routers in its lists equals to *n*<=-<=1 and all the numbers in lists of each router are distinct. For each router *i* lists do not contain the number *i*. | Print -1 if no solution exists.
In the other case print to the first line *n*<=-<=1 β the total number of patch cords in the network. In each of the following *n*<=-<=1 lines print two integers β the routers which are directly connected by a patch cord. Information about each patch cord must be printed exactly once.
Patch cords and routers can be printed in arbitrary order. | [
"3\n2:3,2\n1:1-1:3\n2:1,2\n",
"5\n4:2,5,3,4\n1:4-1:1-2:5,3\n4:4,5,2,1\n4:2,1,3,5\n1:3-3:4,2,1\n",
"3\n1:2-1:3\n1:1-1:3\n1:1-1:2\n"
] | [
"2\n2 1\n2 3\n",
"4\n2 1\n2 4\n5 2\n3 5\n",
"-1\n"
] | The first example is analyzed in the statement.
The answer to the second example is shown on the picture.
The first router has one list, which contains all other routers. The second router has three lists: the first β the single router 4, the second β the single router 1, the third β two routers 3 and 5. The third router has one list, which contains all other routers. The fourth router also has one list, which contains all other routers. The fifth router has two lists: the first β the single router 3, the second β three routers 1, 2 and 4. | [
{
"input": "3\n2:3,2\n1:1-1:3\n2:1,2",
"output": "2\n2 1\n2 3"
},
{
"input": "5\n4:2,5,3,4\n1:4-1:1-2:5,3\n4:4,5,2,1\n4:2,1,3,5\n1:3-3:4,2,1",
"output": "4\n2 1\n2 4\n5 2\n3 5"
},
{
"input": "3\n1:2-1:3\n1:1-1:3\n1:1-1:2",
"output": "-1"
},
{
"input": "2\n1:2\n1:1",
"outp... | 46 | 0 | 0 | 114,453 | |
70 | Information Reform | [
"dp",
"implementation",
"trees"
] | E. Information Reform | 2 | 256 | Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal.
The North Pole governor decided to carry out an information reform. Several cities were decided to be chosen and made regional centers. Maintaining a region center takes *k* fishlars (which is a local currency) per year. It is assumed that a regional center always has information on the latest news.
For every city which is not a regional center, it was decided to appoint a regional center which will be responsible for keeping this city informed. In that case the maintenance costs will be equal to *d**len* fishlars per year, where *len* is the distance from a city to the corresponding regional center, measured in the number of roads along which one needs to go.
Your task is to minimize the costs to carry out the reform. | The first line contains two given numbers *n* and *k* (1<=β€<=*n*<=β€<=180,<=1<=β€<=*k*<=β€<=105).
The second line contains *n*<=-<=1 integers *d**i*, numbered starting with 1 (*d**i*<=β€<=*d**i*<=+<=1,<=0<=β€<=*d**i*<=β€<=105).
Next *n*<=-<=1 lines contain the pairs of cities connected by a road. | On the first line print the minimum number of fishlars needed for a year's maintenance. On the second line print *n* numbers, where the *i*-th number will represent the number of the regional center, appointed to the *i*-th city. If the *i*-th city is a regional center itself, then you should print number *i*.
If there are several solutions to that problem, print any of them. | [
"8 10\n2 5 9 11 15 19 20\n1 4\n1 3\n1 7\n4 6\n2 8\n2 3\n3 5\n"
] | [
"38\n3 3 3 4 3 4 3 3 "
] | none | [] | 92 | 0 | 0 | 114,461 |
335 | Counting Skyscrapers | [
"dp",
"math",
"probabilities"
] | null | null | A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between 2 and 314! (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height *i* having probability 2<=-<=*i* for all positive integers *i*. The floors of a skyscraper with height *i* are numbered 0 through *i*<=-<=1.
To speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the *i*-th floor of one skyscraper with the *i*-th floor of another skyscraper if and only if there are no skyscrapers between them that have an *i*-th floor.
Alice and Bob decide to count the number of skyscrapers.
Alice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.
Bob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than *h* due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds 2*i* to his counter, where *i* is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.
Consider the following example. There are 6 buildings, with heights 1, 4, 3, 4, 1, 2 from left to right, and *h*<==<=2. Alice begins with her counter at 1 and then adds 1 five times for a result of 6. Bob begins with his counter at 1, then he adds 1, 4, 4, and 2, in order, for a result of 12. Note that Bob ignores the highest zip line because of his fear of heights (*h*<==<=2).
Bob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.
When Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter. | The first line of input will be a name, either string "Alice" or "Bob". The second line of input contains two integers *n* and *h* (2<=β€<=*n*<=β€<=30000, 0<=β€<=*h*<=β€<=30). If the name is "Alice", then *n* represents the value of Alice's counter when she reaches the rightmost skyscraper, otherwise *n* represents the value of Bob's counter when he reaches the rightmost skyscraper; *h* represents the highest floor number Bob is willing to use. | Output a single real value giving the expected value of the Alice's counter if you were given Bob's counter, or Bob's counter if you were given Alice's counter.
You answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=9. | [
"Alice\n3 1\n",
"Bob\n2 30\n",
"Alice\n2572 10\n"
] | [
"3.500000000\n",
"2\n",
"3439.031415943\n"
] | In the first example, Bob's counter has a 62.5% chance of being 3, a 25% chance of being 4, and a 12.5% chance of being 5. | [] | 92 | 0 | 0 | 114,484 | |
203 | Transportation | [
"greedy",
"sortings",
"two pointers"
] | null | null | Valera came to Japan and bought many robots for his research. He's already at the airport, the plane will fly very soon and Valera urgently needs to bring all robots to the luggage compartment.
The robots are self-propelled (they can potentially move on their own), some of them even have compartments to carry other robots. More precisely, for the *i*-th robot we know value *c**i* β the number of robots it can carry. In this case, each of *c**i* transported robots can additionally carry other robots.
However, the robots need to be filled with fuel to go, so Valera spent all his last money and bought *S* liters of fuel. He learned that each robot has a restriction on travel distances. Thus, in addition to features *c**i*, the *i*-th robot has two features *f**i* and *l**i* β the amount of fuel (in liters) needed to move the *i*-th robot, and the maximum distance that the robot can go.
Due to the limited amount of time and fuel, Valera wants to move the maximum number of robots to the luggage compartment. He operates as follows.
- First Valera selects some robots that will travel to the luggage compartment on their own. In this case the total amount of fuel required to move all these robots must not exceed *S*. - Then Valera seats the robots into the compartments, so as to transport as many robots as possible. Note that if a robot doesn't move by itself, you can put it in another not moving robot that is moved directly or indirectly by a moving robot. - After that all selected and seated robots along with Valera go to the luggage compartment and the rest robots will be lost.
There are *d* meters to the luggage compartment. Therefore, the robots that will carry the rest, must have feature *l**i* of not less than *d*. During the moving Valera cannot stop or change the location of the robots in any way.
Help Valera calculate the maximum number of robots that he will be able to take home, and the minimum amount of fuel he will have to spend, because the remaining fuel will come in handy in Valera's research. | The first line contains three space-separated integers *n*,<=*d*,<=*S* (1<=β€<=*n*<=β€<=105,<=1<=β€<=*d*,<=*S*<=β€<=109). The first number represents the number of robots, the second one β the distance to the luggage compartment and the third one β the amount of available fuel.
Next *n* lines specify the robots. The *i*-th line contains three space-separated integers *c**i*,<=*f**i*,<=*l**i* (0<=β€<=*c**i*,<=*f**i*,<=*l**i*<=β€<=109) β the *i*-th robot's features. The first number is the number of robots the *i*-th robot can carry, the second number is the amount of fuel needed for the *i*-th robot to move and the third one shows the maximum distance the *i*-th robot can go. | Print two space-separated integers β the maximum number of robots Valera can transport to the luggage compartment and the minimum amount of fuel he will need for that. If Valera won't manage to get any robots to the luggage compartment, print two zeroes. | [
"3 10 10\n0 12 10\n1 6 10\n0 1 1\n",
"2 7 10\n3 12 10\n5 16 8\n",
"4 8 10\n0 12 3\n1 1 0\n0 3 11\n1 6 9\n"
] | [
"2 6\n",
"0 0\n",
"4 9\n"
] | none | [] | 92 | 0 | 0 | 114,655 | |
131 | Yet Another Task with Queens | [
"sortings"
] | null | null | A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.
There are *m* queens on a square *n*<=Γ<=*n* chessboard. You know each queen's positions, the *i*-th queen is positioned in the square (*r**i*,<=*c**i*), where *r**i* is the board row number (numbered from the top to the bottom from 1 to *n*), and *c**i* is the board's column number (numbered from the left to the right from 1 to *n*). No two queens share the same position.
For each queen one can count *w* β the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen *w* is between 0 and 8, inclusive.
Print the sequence *t*0,<=*t*1,<=...,<=*t*8, where *t**i* is the number of queens that threaten exactly *i* other queens, i.e. the number of queens that their *w* equals *i*. | The first line of the input contains a pair of integers *n*,<=*m* (1<=β€<=*n*,<=*m*<=β€<=105), where *n* is the size of the board and *m* is the number of queens on the board. Then *m* following lines contain positions of the queens, one per line. Each line contains a pair of integers *r**i*,<=*c**i* (1<=β€<=*r**i*,<=*c**i*<=β€<=*n*) β the queen's position. No two queens stand on the same square. | Print the required sequence *t*0,<=*t*1,<=...,<=*t*8, separating the numbers with spaces. | [
"8 4\n4 3\n4 8\n6 5\n1 6\n",
"10 3\n1 1\n1 2\n1 3\n"
] | [
"0 3 0 1 0 0 0 0 0 ",
"0 2 1 0 0 0 0 0 0 "
] | none | [] | 60 | 0 | 0 | 114,694 | |
542 | Quest | [
"dp",
"greedy"
] | null | null | Polycarp is making a quest for his friends. He has already made *n* tasks, for each task the boy evaluated how interesting it is as an integer *q**i*, and the time *t**i* in minutes needed to complete the task.
An interesting feature of his quest is: each participant should get the task that is best suited for him, depending on his preferences. The task is chosen based on an interactive quiz that consists of some questions. The player should answer these questions with "yes" or "no". Depending on the answer to the question, the participant either moves to another question or goes to one of the tasks that are in the quest. In other words, the quest is a binary tree, its nodes contain questions and its leaves contain tasks.
We know that answering any of the questions that are asked before getting a task takes exactly one minute from the quest player. Polycarp knows that his friends are busy people and they can't participate in the quest for more than *T* minutes. Polycarp wants to choose some of the *n* tasks he made, invent the corresponding set of questions for them and use them to form an interactive quiz as a binary tree so that no matter how the player answers quiz questions, he spends at most *T* minutes on completing the whole quest (that is, answering all the questions and completing the task). Specifically, the quest can contain zero questions and go straight to the task. Each task can only be used once (i.e., the people who give different answers to questions should get different tasks).
Polycarp wants the total "interest" value of the tasks involved in the quest to be as large as possible. Help him determine the maximum possible total interest value of the task considering that the quest should be completed in *T* minutes at any variant of answering questions. | The first line contains two integers *n* and *T* (1<=β€<=*n*<=β€<=1000, 1<=β€<=*T*<=β€<=100) β the number of tasks made by Polycarp and the maximum time a quest player should fit into.
Next *n* lines contain two integers *t**i*,<=*q**i* (1<=β€<=*t**i*<=β€<=*T*, 1<=β€<=*q**i*<=β€<=1000) each β the time in minutes needed to complete the *i*-th task and its interest value. | Print a single integer β the maximum possible total interest value of all the tasks in the quest. | [
"5 5\n1 1\n1 1\n2 2\n3 3\n4 4\n",
"5 5\n4 1\n4 2\n4 3\n4 4\n4 5\n",
"2 2\n1 1\n2 10\n"
] | [
"11\n",
"9\n",
"10\n"
] | In the first sample test all the five tasks can be complemented with four questions and joined into one quest.
In the second sample test it is impossible to use all the five tasks, but you can take two of them, the most interesting ones.
In the third sample test the optimal strategy is to include only the second task into the quest.
Here is the picture that illustrates the answers to the sample tests. The blue circles represent the questions, the two arrows that go from every circle represent where a person goes depending on his answer to that question. The tasks are the red ovals. | [
{
"input": "5 5\n1 1\n1 1\n2 2\n3 3\n4 4",
"output": "11"
},
{
"input": "5 5\n4 1\n4 2\n4 3\n4 4\n4 5",
"output": "9"
},
{
"input": "2 2\n1 1\n2 10",
"output": "10"
},
{
"input": "10 1\n1 732\n1 649\n1 821\n1 756\n1 377\n1 216\n1 733\n1 420\n1 857\n1 193",
"output": "857"... | 46 | 0 | 0 | 114,974 | |
0 | none | [
"none"
] | null | null | Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.
The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)
Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem. | The first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} β they are the colors of gems with which the box should be decorated. | Print the required number of different ways to decorate the box. | [
"YYYYYY\n",
"BOOOOB\n",
"ROYGBV\n"
] | [
"1\n",
"2\n",
"30\n"
] | none | [
{
"input": "YYYYYY",
"output": "1"
},
{
"input": "BOOOOB",
"output": "2"
},
{
"input": "ROYGBV",
"output": "30"
},
{
"input": "RRRRRR",
"output": "1"
},
{
"input": "BOOOOO",
"output": "1"
},
{
"input": "GOGGVG",
"output": "2"
},
{
"input": ... | 30 | 0 | 0 | 115,100 | |
0 | none | [
"none"
] | null | null | Recently a tournament in *k* kinds of sports has begun in Berland. Vasya wants to make money on the bets.
The scheme of the tournament is very mysterious and not fully disclosed. Competitions are held back to back, each of them involves two sportsmen who have not left the tournament yet. Each match can be held in any of the *k* kinds of sport. Loser leaves the tournament. The last remaining sportsman becomes the winner. Apart of this, the scheme can be arbitrary, it is not disclosed in advance.
Vasya knows powers of sportsmen in each kind of sport. He believes that the sportsmen with higher power always wins.
The tournament is held every year, and each year one new participant joins it. In the first tournament, only one sportsman has participated, in the second there were two sportsmen, and so on. Vasya has been watching the tournament for the last *n* years. Help him to find the number of possible winners for each of the *n* tournaments. | The first line contains two integers *n* and *k* (1<=β€<=*n*<=β€<=5Β·104, 1<=β€<=*k*<=β€<=10) β the number of tournaments and the number of kinds of sport, respectively.
Each of the next *n* lines contains *k* integers *s**i*1,<=*s**i*2,<=...,<=*s**ik* (1<=β€<=*s**ij*<=β€<=109), where *s**ij* is the power of the *i*-th sportsman in the *j*-th kind of sport. The sportsman with higher powers always wins. It's guaranteed that for any kind of sport all of these powers are distinct. | For each of the *n* tournaments output the number of contenders who can win. | [
"3 2\n1 5\n5 1\n10 10\n",
"3 2\n2 2\n3 3\n1 10\n",
"3 2\n2 3\n1 1\n3 2\n"
] | [
"1\n2\n1\n",
"1\n1\n3\n",
"1\n1\n2\n"
] | In the first sample:
In the first tournament there is only one sportsman, and he is the winner.
In the second tournament, there are two sportsmen, and everyone can defeat another, depending on kind of sports.
In the third tournament, the third sportsman in the strongest in both kinds of sports, so he is the winner regardless of the scheme. | [] | 46 | 0 | 0 | 115,177 | |
193 | Xor | [
"brute force"
] | null | null | John Doe has four arrays: *a*, *b*, *k*, and *p*. Each array consists of *n* integers. Elements of all arrays are indexed starting from 1. Array *p* is a permutation of integers 1 to *n*.
John invented a game for his friends and himself. Initially a player is given array *a*. The player must consecutively execute exactly *u* operations on *a*. You are permitted to execute the following operations:
- Operation 1: For each change *a**i* into . Expression means applying the operation of a bitwise xor to numbers *x* and *y*. The given operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "^", in Pascal β as "xor". - Operation 2: For each change *a**i* into *a**p**i*<=+<=*r*. When this operation is executed, all changes are made at the same time.
After all *u* operations are applied, the number of points the player gets is determined by the formula .
John wants to find out what maximum number of points a player can win in his game. Help him. | The first line contains space-separated integers *n*, *u* and *r* (1<=β€<=*n*,<=*u*<=β€<=30, 0<=β€<=*r*<=β€<=100) β the number of elements in each array, the number of operations and the number that describes one of the operations.
Each of the next four lines contains *n* space-separated integers β arrays *a*, *b*, *k*, *p*. The first line has array *a*, the second line has array *b*, the third line has array *k* and the fourth one has array *p*.
It is guaranteed that elements of arrays *a* and *b* are positive and do not exceed 104 (1<=β€<=*a**i*,<=*b**i*<=β€<=104), elements of array *k* do not exceed 104 in the absolute value (|*k*|<=β€<=104) and *p* is a permutation of numbers from 1 to *n*. | On a single line print number *s* β the maximum number of points that a player can win in John's game.
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. | [
"3 2 1\n7 7 7\n8 8 8\n1 2 3\n1 3 2\n",
"2 1 0\n1 1\n1 1\n1 -1\n1 2\n"
] | [
"96\n",
"0\n"
] | In the first sample you should first apply the operation of the first type, then the operation of the second type. | [] | 46 | 4,505,600 | 0 | 115,229 | |
404 | Maze 1D | [
"binary search",
"greedy",
"implementation"
] | null | null | Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot.
The robot has instructions β the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number 0. If the robot should go into the cell with an obstacle according the instructions, it will skip this move.
Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once β at its last move. Moreover, the latter move cannot be skipped.
Let's assume that *k* is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose *k* obstacles and the finishing cell so that the robot is able to complete the instructions successfully. | The first line contains a sequence of characters without spaces *s*1*s*2... *s**n* (1<=β€<=*n*<=β€<=106), consisting only of letters "L" and "R". If character *s**i* equals "L", then the robot on the *i*-th move must try to move one cell to the left. If the *s**i*-th character equals "R", then the robot on the *i*-th move must try to move one cell to the right. | Print a single integer β the required number of ways. It's guaranteed that this number fits into 64-bit signed integer type. | [
"RR\n",
"RRL\n"
] | [
"1\n",
"1\n"
] | In the first sample Valera mustn't add any obstacles and his finishing cell must be cell 2.
In the second sample, Valera must add an obstacle in cell number 1, and his finishing cell must be cell number β-β1. In this case robot skips the first two moves and on the third move he goes straight from the starting cell to the finishing one. But if Valera doesn't add any obstacles, or adds an obstacle to another cell, then the robot visits the finishing cell more than once. | [
{
"input": "RR",
"output": "1"
},
{
"input": "RRL",
"output": "1"
},
{
"input": "LLLLLRRRRR",
"output": "5"
},
{
"input": "LLRLLLLRLRRRLRRLLRLL",
"output": "0"
},
{
"input": "LRRLRLLLRRLRRRLLLLLRLLLLLRLLRRRLRRLRRLRLRLRLRLLLRRLRLLLLRLRRLLRLRRRRRLRLLLLRRLLRLLLRLLRRL... | 46 | 0 | 0 | 115,410 | |
954 | Water Taps | [
"binary search",
"greedy",
"sortings"
] | null | null | Consider a system of *n* water taps all pouring water into the same container. The *i*-th water tap can be set to deliver any amount of water from 0 to *a**i* ml per second (this amount may be a real number). The water delivered by *i*-th tap has temperature *t**i*.
If for every you set *i*-th tap to deliver exactly *x**i* ml of water per second, then the resulting temperature of water will be (if , then to avoid division by zero we state that the resulting water temperature is 0).
You have to set all the water taps in such a way that the resulting temperature is exactly *T*. What is the maximum amount of water you may get per second if its temperature has to be *T*? | The first line contains two integers *n* and *T* (1<=β€<=*n*<=β€<=200000, 1<=β€<=*T*<=β€<=106) β the number of water taps and the desired temperature of water, respectively.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=106) where *a**i* is the maximum amount of water *i*-th tap can deliver per second.
The third line contains *n* integers *t*1, *t*2, ..., *t**n* (1<=β€<=*t**i*<=β€<=106) β the temperature of water each tap delivers. | Print the maximum possible amount of water with temperature exactly *T* you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0).
Your answer is considered correct if its absolute or relative error doesn't exceed 10<=-<=6. | [
"2 100\n3 10\n50 150\n",
"3 9\n5 5 30\n6 6 10\n",
"2 12\n1 3\n10 15\n"
] | [
"6.000000000000000\n",
"40.000000000000000\n",
"1.666666666666667\n"
] | none | [
{
"input": "2 100\n3 10\n50 150",
"output": "6.000000000000000"
},
{
"input": "3 9\n5 5 30\n6 6 10",
"output": "40.000000000000000"
},
{
"input": "2 12\n1 3\n10 15",
"output": "1.666666666666667"
},
{
"input": "20 30\n70 97 14 31 83 22 83 56 19 87 59 7 7 89 24 82 34 40 6 24\n... | 155 | 39,526,400 | 3 | 115,424 | |
852 | Property | [
"greedy",
"sortings"
] | null | null | Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.
Billβs property can be observed as a convex regular 2*n*-sided polygon *A*0 *A*1... *A*2*n*<=-<=1 *A*2*n*,<= *A*2*n*<==<= *A*0, with sides of the exactly 1 meter in length.
Court rules for removing part of his property are as follows:
- Split every edge *A**k* *A**k*<=+<=1,<= *k*<==<=0... 2*n*<=-<=1 in *n* equal parts of size 1<=/<=*n* with points *P*0,<=*P*1,<=...,<=*P**n*<=-<=1 - On every edge *A*2*k* *A*2*k*<=+<=1,<= *k*<==<=0... *n*<=-<=1 court will choose one point *B*2*k*<==<= *P**i* for some *i*<==<=0,<=...,<= *n*<=-<=1 such that - On every edge *A*2*k*<=+<=1*A*2*k*<=+<=2,<= *k*<==<=0...*n*<=-<=1 Bill will choose one point *B*2*k*<=+<=1<==<= *P**i* for some *i*<==<=0,<=...,<= *n*<=-<=1 such that - Bill gets to keep property inside of 2*n*-sided polygon *B*0 *B*1... *B*2*n*<=-<=1
Luckily, Bill found out which *B*2*k* points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep. | The first line contains one integer number *n* (2<=β€<=*n*<=β€<=50000), representing number of edges of 2*n*-sided polygon.
The second line contains *n* distinct integer numbers *B*2*k* (0<=β€<=*B*2*k*<=β€<=*n*<=-<=1,<= *k*<==<=0... *n*<=-<=1) separated by a single space, representing points the court chose. If *B*2*k*<==<=*i*, the court chose point *P**i* on side *A*2*k* *A*2*k*<=+<=1. | Output contains *n* distinct integers separated by a single space representing points *B*1,<=*B*3,<=...,<=*B*2*n*<=-<=1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them. | [
"3\n0 1 2\n"
] | [
"0 2 1\n"
] | To maximize area Bill should choose points: *B*<sub class="lower-index">1</sub>β=β*P*<sub class="lower-index">0</sub>, *B*<sub class="lower-index">3</sub>β=β*P*<sub class="lower-index">2</sub>, *B*<sub class="lower-index">5</sub>β=β*P*<sub class="lower-index">1</sub>
<img class="tex-graphics" src="https://espresso.codeforces.com/03c7bbc496053c0ca19cfcf073d88965c4c90895.png" style="max-width: 100.0%;max-height: 100.0%;"/> | [
{
"input": "3\n0 1 2",
"output": "0 2 1"
},
{
"input": "10\n0 1 2 3 4 5 6 7 8 9",
"output": "0 1 2 3 5 6 7 8 9 4"
},
{
"input": "10\n1 7 3 6 8 2 4 5 0 9",
"output": "2 6 5 9 7 1 4 0 3 8"
},
{
"input": "10\n4 9 7 2 3 5 6 1 8 0",
"output": "8 9 6 1 4 7 2 5 3 0"
},
{
... | 93 | 0 | 0 | 116,057 | |
135 | Weak Subsequence | [
"combinatorics"
] | null | null | Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to *k*. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string *s* if the length of string's longest substring that is also its weak subsequence (see the definition given below) equals *w*.
String *a* with the length of *n* is considered the weak subsequence of the string *s* with the length of *m*, if there exists such a set of indexes 1<=β€<=*i*1<=<<=*i*2<=<<=...<=<<=*i**n*<=β€<=*m*, that has the following two properties:
- *a**k*<==<=*s**i**k* for all *k* from 1 to *n*; - there exists at least one such *k* (1<=β€<=*k*<=<<=*n*), for which *i**k*<=+<=1<=β<=*i**k*<=><=1.
Petya got interested how many different strings are available for him to purchase in the shop. As the number of strings can be very large, please find it modulo 1000000007 (109<=+<=7). If there are infinitely many such strings, print "-1". | The first line contains two integers *k* (1<=β€<=*k*<=β€<=106) and *w* (2<=β€<=*w*<=β€<=109) β the alphabet size and the required length of the maximum substring that also is the weak subsequence, correspondingly. | Print a single number β the number of strings Petya can buy using the voucher, modulo 1000000007 (109<=+<=7). If there are infinitely many such strings, print "-1" (without the quotes). | [
"2 2\n",
"3 5\n",
"2 139\n"
] | [
"10\n",
"1593\n",
"717248223\n"
] | In the first sample Petya can buy the following strings: aaa, aab, abab, abb, abba, baa, baab, baba, bba, bbb. | [
{
"input": "2 2",
"output": "10"
},
{
"input": "3 5",
"output": "1593"
},
{
"input": "2 139",
"output": "717248223"
},
{
"input": "5 6",
"output": "983725"
},
{
"input": "1000 1002",
"output": "9396758"
},
{
"input": "131 132",
"output": "757914194... | 46 | 0 | 0 | 116,244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.