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
997
Good Subsegments
[ "data structures" ]
null
null
A permutation $p$ of length $n$ is a sequence $p_1, p_2, \ldots, p_n$ consisting of $n$ distinct integers, each of which from $1$ to $n$ ($1 \leq p_i \leq n$) . Let's call the subsegment $[l,r]$ of the permutation good if all numbers from the minimum on it to the maximum on this subsegment occur among the numbers $p_l, p_{l+1}, \dots, p_r$. For example, good segments of permutation $[1, 3, 2, 5, 4]$ are: - $[1, 1]$, - $[1, 3]$, - $[1, 5]$, - $[2, 2]$, - $[2, 3]$, - $[2, 5]$, - $[3, 3]$, - $[4, 4]$, - $[4, 5]$, - $[5, 5]$. You are given a permutation $p_1, p_2, \ldots, p_n$. You need to answer $q$ queries of the form: find the number of good subsegments of the given segment of permutation. In other words, to answer one query, you need to calculate the number of good subsegments $[x \dots y]$ for some given segment $[l \dots r]$, such that $l \leq x \leq y \leq r$.
The first line contains a single integer $n$ ($1 \leq n \leq 120000$) — the number of elements in the permutation. The second line contains $n$ distinct integers $p_1, p_2, \ldots, p_n$ separated by spaces ($1 \leq p_i \leq n$). The third line contains an integer $q$ ($1 \leq q \leq 120000$) — number of queries. The following $q$ lines describe queries, each line contains a pair of integers $l$, $r$ separated by space ($1 \leq l \leq r \leq n$).
Print a $q$ lines, $i$-th of them should contain a number of good subsegments of a segment, given in the $i$-th query.
[ "5\n1 3 2 5 4\n15\n1 1\n1 2\n1 3\n1 4\n1 5\n2 2\n2 3\n2 4\n2 5\n3 3\n3 4\n3 5\n4 4\n4 5\n5 5\n" ]
[ "1\n2\n5\n6\n10\n1\n3\n4\n7\n1\n2\n4\n1\n3\n1\n" ]
none
[]
46
0
0
43,064
571
Campus
[ "binary search", "data structures", "dsu", "trees" ]
null
null
Oscolcovo city has a campus consisting of *n* student dormitories, *n* universities and *n* military offices. Initially, the *i*-th dormitory belongs to the *i*-th university and is assigned to the *i*-th military office. Life goes on and the campus is continuously going through some changes. The changes can be of four types: 1. University *a**j* merges with university *b**j*. After that all the dormitories that belonged to university *b**j* are assigned to to university *a**j*, and university *b**j* disappears. 1. Military office *c**j* merges with military office *d**j*. After that all the dormitories that were assigned to military office *d**j*, are assigned to military office *c**j*, and military office *d**j* disappears. 1. Students of university *x**j* move in dormitories. Lets *k**x**j* is the number of dormitories that belong to this university at the time when the students move in. Then the number of students in each dormitory of university *x**j* increases by *k**x**j* (note that the more dormitories belong to the university, the more students move in each dormitory of the university). 1. Military office number *y**j* conducts raids on all the dormitories assigned to it and takes all students from there. Thus, at each moment of time each dormitory is assigned to exactly one university and one military office. Initially, all the dormitory are empty. Your task is to process the changes that take place in the campus and answer the queries, how many people currently live in dormitory *q**j*.
The first line contains two integers, *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=5·105) — the number of dormitories and the number of queries, respectively. Next *m* lines contain the queries, each of them is given in one of the following formats: - «U *a**j* *b**j*» — merging universities; - «M *c**j* *d**j*» — merging military offices; - «A *x**j*» — students of university *x**j* moving in the dormitories; - «Z *y**j*» — a raid in military office *y**j*; - «Q *q**j*» — a query asking the number of people in dormitory *q**j*.
In the *i*-th line print the answer to the *i*-th query asking the number of people in the dormitory.
[ "2 7\nA 1\nQ 1\nU 1 2\nA 1\nZ 1\nQ 1\nQ 2\n", "5 12\nU 1 2\nM 4 5\nA 1\nQ 1\nA 3\nA 4\nQ 3\nQ 4\nZ 4\nQ 4\nA 5\nQ 5\n" ]
[ "1\n0\n2\n", "2\n1\n1\n0\n1\n" ]
Consider the first sample test: - In the first query university 1 owns only dormitory 1, so after the query dormitory 1 will have 1 student. - After the third query university 1 owns dormitories 1 and 2. - The fourth query increases by 2 the number of students living in dormitories 1 and 2 that belong to university number 1. After that 3 students live in the first dormitory and 2 students live in the second dormitory. - At the fifth query the number of students living in dormitory 1, assigned to the military office 1, becomes zero.
[]
46
0
0
43,082
223
Two Strings
[ "data structures", "dp", "strings" ]
null
null
A subsequence of length |*x*| of string *s*<==<=*s*1*s*2... *s*|*s*| (where |*s*| is the length of string *s*) is a string *x*<==<=*s**k*1*s**k*2... *s**k*|*x*| (1<=≤<=*k*1<=&lt;<=*k*2<=&lt;<=...<=&lt;<=*k*|*x*|<=≤<=|*s*|). You've got two strings — *s* and *t*. Let's consider all subsequences of string *s*, coinciding with string *t*. Is it true that each character of string *s* occurs in at least one of these subsequences? In other words, is it true that for all *i* (1<=≤<=*i*<=≤<=|*s*|), there is such subsequence *x*<==<=*s**k*1*s**k*2... *s**k*|*x*| of string *s*, that *x*<==<=*t* and for some *j* (1<=≤<=*j*<=≤<=|*x*|) *k**j*<==<=*i*.
The first line contains string *s*, the second line contains string *t*. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2·105.
Print "Yes" (without the quotes), if each character of the string *s* occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise.
[ "abab\nab\n", "abacaba\naba\n", "abc\nba\n" ]
[ "Yes\n", "No\n", "No\n" ]
In the first sample string *t* can occur in the string *s* as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string *s* occurs at least once. In the second sample the 4-th character of the string *s* doesn't occur in any occurrence of string *t*. In the third sample there is no occurrence of string *t* in string *s*.
[ { "input": "abab\nab", "output": "Yes" }, { "input": "abacaba\naba", "output": "No" }, { "input": "abc\nba", "output": "No" }, { "input": "babbbbbaba\nab", "output": "No" }, { "input": "accbacabaa\nbada", "output": "No" }, { "input": "aaaaaaaaaaaaaaaaa...
92
0
0
43,251
625
Frog Fights
[ "data structures", "greedy" ]
null
null
Ostap Bender recently visited frog farm and was inspired to create his own frog game. Number of frogs are places on a cyclic gameboard, divided into *m* cells. Cells are numbered from 1 to *m*, but the board is cyclic, so cell number 1 goes right after the cell number *m* in the direction of movement. *i*-th frog during its turn can jump for *a**i* cells. Frogs move in turns, game starts with a move by frog 1. On its turn *i*-th frog moves *a**i* cells forward, knocking out all the frogs on its way. If there is a frog in the last cell of the path of the *i*-th frog, that frog is also knocked out. After this the value *a**i* is decreased by the number of frogs that were knocked out during this turn. If *a**i* is zero or goes negative, then *i*-th frog doesn't make moves anymore. After frog number 1 finishes its turn, frog number 2 starts to move, then frog number 3 and so on. After the frog number *n* makes its move, frog 1 starts to move again, then frog 2 and so on this process goes forever. If some frog was already knocked out from the board, we consider that it skips all its moves. Help Ostap to identify, what frogs will stay on the board at the end of a game?
First line of the input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=100000,<=1<=≤<=*m*<=≤<=109,<=*n*<=≤<=*m*) — number of frogs and gameboard size, respectively. Following *n* lines contains frogs descriptions — two integers *p**i* and *a**i* (1<=≤<=*p**i*,<=*a**i*<=≤<=*m*) — the number of cell occupied by *i*-th frog initially and initial jump length. All *p**i* are guaranteed to be distinct.
In the first line output number of frogs on the final gameboard. In the second line output their numbers in any order.
[ "3 5\n2 1\n5 3\n4 3\n", "5 6\n1 2\n3 4\n2 5\n5 1\n6 1\n" ]
[ "1\n3 ", "2\n1 4 " ]
In the first sample first frog jumps 1 cell and finishes in cell number 3. Second frog jumps for 3 cells and finishes on cell number 3, knocking out frog number 1. Current jump length for frog number 2 is now 2. Third frog jumps to cell 2, then second frog jumps to cell 5. Third frog in turn finishes in cell 5 and removes frog 2 from the gameboard. Now, it's the only remaining frog in the game. In the second sample first frog jumps 2 cells and knocks out frogs in cells 2 and 3. Its value *a*<sub class="lower-index">*i*</sub> is now 0. Then fourth frog jumps and knocks out fifth frog and its *a*<sub class="lower-index">*i*</sub> is now 0 too. These two frogs will remains on the gameboard forever.
[]
46
0
0
43,266
101
Buses
[ "binary search", "data structures", "dp" ]
B. Buses
2
265
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly *n*<=+<=1 bus stops. All of them are numbered with integers from 0 to *n* in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number *n*. There are *m* buses running between the house and the school: the *i*-th bus goes from stop *s**i* to *t**i* (*s**i*<=&lt;<=*t**i*), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the *i*-th bus on any stop numbered from *s**i* to *t**i*<=-<=1 inclusive, but he can get off the *i*-th bus only on the bus stop *t**i*. Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house. Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109<=+<=7).
The first line contains two space-separated integers: *n* and *m* (1<=≤<=*n*<=≤<=109,<=0<=≤<=*m*<=≤<=105). Then follow *m* lines each containing two integers *s**i*,<=*t**i*. They are the numbers of starting stops and end stops of the buses (0<=≤<=*s**i*<=&lt;<=*t**i*<=≤<=*n*).
Print the only number — the number of ways to get to the school modulo 1000000007 (109<=+<=7).
[ "2 2\n0 1\n1 2\n", "3 2\n0 1\n1 2\n", "5 5\n0 1\n0 2\n0 3\n0 4\n0 5\n" ]
[ "1\n", "0\n", "16\n" ]
The first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two. In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0. In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 2<sup class="upper-index">4</sup> = 16.
[ { "input": "2 2\n0 1\n1 2", "output": "1" }, { "input": "3 2\n0 1\n1 2", "output": "0" }, { "input": "5 5\n0 1\n0 2\n0 3\n0 4\n0 5", "output": "16" }, { "input": "3 3\n1 2\n2 3\n1 3", "output": "0" }, { "input": "10 10\n0 1\n0 2\n0 3\n0 4\n0 5\n0 6\n0 7\n0 8\n0 9\...
92
0
0
43,313
409
Big Data
[ "*special" ]
null
null
Little Petya wanted to give an April Fools Day present to some scientists. After some hesitation he decided to give them the array that he got as a present in Codeforces Round #153 (Div.2). The scientists rejoiced at the gift and decided to put some important facts to this array. Here are the first few of the facts: - The highest mountain above sea level in the world is Mount Everest. Its peak rises to 8848 m. - The largest board game tournament consisted of 958 participants playing chapaev.- The largest online maths competition consisted of 12766 participants.- The Nile is credited as the longest river in the world. From its farthest stream in Burundi, it extends 6695 km in length.- While not in flood, the main stretches of the Amazon river in South America can reach widths of up to 1100 km at its widest points.- Angel Falls is the highest waterfall. Its greatest single drop measures 807 m.- The Hotel Everest View above Namche, Nepal — the village closest to Everest base camp – is at a record height of 31962 m- Uranium is the heaviest of all the naturally occurring elements. Its most common isotope has a nucleus containing 146 neutrons.- The coldest permanently inhabited place is the Siberian village of Oymyakon, where the temperature of -68°C was registered in the twentieth century.- The longest snake held in captivity is over 25 feet long. Its name is Medusa.- Colonel Meow holds the world record for longest fur on a cat — almost 134 centimeters.- Sea otters can have up to 10000 hairs per square inch. This is the most dense fur in the animal kingdom.- The largest state of USA is Alaska; its area is 663268 square miles- Alaska has a longer coastline than all of the other 49 U.S. States put together: it is 154103 miles long.- Lake Baikal is the largest freshwater lake in the world. It reaches 1642 meters in depth and contains around one-fifth of the world’s unfrozen fresh water.- The most colorful national flag is the one of Turkmenistan, with 106 colors.
The input will contain a single integer between 1 and 16.
Output a single integer.
[ "1\n", "7\n" ]
[ "1\n", "0\n" ]
none
[ { "input": "1", "output": "1" }, { "input": "7", "output": "0" }, { "input": "13", "output": "1" }, { "input": "3", "output": "0" }, { "input": "8", "output": "1" }, { "input": "16", "output": "0" }, { "input": "11", "output": "0" }, ...
31
0
0
43,325
952
Puzzling Language
[ "constructive algorithms" ]
null
null
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck). The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table: You are given a string. Output a program in the described language which prints this string. You can download the language interpreter used for judging here: [https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp](https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp) (use C++11 to compile the code). Note several implementation details: - The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.- The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.- The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.- Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.- Console input (, command) is allowed in Brainfuck code but has no effect when executed.
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output a program in the described language which, when executed, will print the given message.
[ "$$$" ]
[ ".......X.......\n......XXX......\n.....XXXXX.....\n....XXXXXXX....\n...XXXXXXXXX...\n..XXXXXXXXXXX..\n.XXXXXXXXXXXXX.\n...............\nX.............X\nX..............\nX..............\nX..............\n" ]
The example corresponds to the following Brainfuck program: The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
[ { "input": "$$$", "output": "..\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\n.X\nX.\...
46
0
0
43,399
0
none
[ "none" ]
null
null
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator. Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator. According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order. The elevator has two commands: - Go up or down one floor. The movement takes 1 second. - Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1. You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=2000) — the number of employees. The *i*-th of the next *n* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=9, *a**i*<=≠<=*b**i*) — the floor on which an employee initially is, and the floor he wants to reach. The employees are given in the order they came to the elevator.
Print a single integer — the minimal possible time in seconds.
[ "2\n3 5\n5 3\n", "2\n5 3\n3 5\n" ]
[ "10", "12" ]
<img class="tex-graphics" src="https://espresso.codeforces.com/1b7e25450a0703db67675fea25386865f0290049.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 2 <img class="tex-graphics" src="https://espresso.codeforces.com/0f585328ada5689c39e5a7263a792979c00fb01a.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 3 <img class="tex-graphics" src="https://espresso.codeforces.com/61f0c2263487060af2083a06cedf6641d234e31b.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 5 <img class="tex-graphics" src="https://espresso.codeforces.com/4f5d7a22c1f2af851019589a1232851ced924fbf.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 6 <img class="tex-graphics" src="https://espresso.codeforces.com/4602434598e4844e9532caef51583bd84886b067.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 7 <img class="tex-graphics" src="https://espresso.codeforces.com/c1924de28ca19fe1346617380752126a2d4bbb75.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 9 <img class="tex-graphics" src="https://espresso.codeforces.com/2e58cd09a6a459da60780a790c49da336d0b2783.png" style="max-width: 100.0%;max-height: 100.0%;"/> *t* = 10
[]
15
0
0
43,424
839
Winter is here
[ "combinatorics", "dp", "math", "number theory" ]
null
null
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of *n* soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers. He has created a method to know how strong his army is. Let the *i*-th soldier’s strength be *a**i*. For some *k* he calls *i*1,<=*i*2,<=...,<=*i**k* a clan if *i*1<=&lt;<=*i*2<=&lt;<=*i*3<=&lt;<=...<=&lt;<=*i**k* and *gcd*(*a**i*1,<=*a**i*2,<=...,<=*a**i**k*)<=&gt;<=1 . He calls the strength of that clan *k*·*gcd*(*a**i*1,<=*a**i*2,<=...,<=*a**i**k*). Then he defines the strength of his army by the sum of strengths of all possible clans. Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109<=+<=7). Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.
The first line contains integer *n* (1<=≤<=*n*<=≤<=200000) — the size of the army. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000000) — denoting the strengths of his soldiers.
Print one integer — the strength of John Snow's army modulo 1000000007 (109<=+<=7).
[ "3\n3 3 1\n", "4\n2 3 4 6\n" ]
[ "12\n", "39\n" ]
In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12
[ { "input": "3\n3 3 1", "output": "12" }, { "input": "4\n2 3 4 6", "output": "39" } ]
1,434
35,942,400
3
43,433
730
Olympiad in Programming and Sports
[ "dp", "flows", "graphs", "greedy" ]
null
null
There are *n* students at Berland State University. Every student has two skills, each measured as a number: *a**i* — the programming skill and *b**i* — the sports skill. It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in the programming track and one to take part in the sports track. There should be exactly *p* students in the programming team and exactly *s* students in the sports team. A student can't be a member of both teams. The university management considers that the strength of the university on the Olympiad is equal to the sum of two values: the programming team strength and the sports team strength. The strength of a team is the sum of skills of its members in the corresponding area, so the strength of the programming team is the sum of all *a**i* and the strength of the sports team is the sum of all *b**i* over corresponding team members. Help Berland State University to compose two teams to maximize the total strength of the university on the Olympiad.
The first line contains three positive integer numbers *n*, *p* and *s* (2<=≤<=*n*<=≤<=3000, *p*<=+<=*s*<=≤<=*n*) — the number of students, the size of the programming team and the size of the sports team. The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=3000), where *a**i* is the programming skill of the *i*-th student. The third line contains *n* positive integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=3000), where *b**i* is the sports skill of the *i*-th student.
In the first line, print the the maximum strength of the university on the Olympiad. In the second line, print *p* numbers — the members of the programming team. In the third line, print *s* numbers — the members of the sports team. The students are numbered from 1 to *n* as they are given in the input. All numbers printed in the second and in the third lines should be distinct and can be printed in arbitrary order. If there are multiple solutions, print any of them.
[ "5 2 2\n1 3 4 5 2\n5 3 2 1 4\n", "4 2 2\n10 8 8 3\n10 7 9 4\n", "5 3 1\n5 2 5 1 7\n6 3 1 6 3\n" ]
[ "18\n3 4 \n1 5 \n", "31\n1 2 \n3 4 \n", "23\n1 3 5 \n4 \n" ]
none
[ { "input": "5 2 2\n1 3 4 5 2\n5 3 2 1 4", "output": "18\n3 4 \n1 5 " }, { "input": "4 2 2\n10 8 8 3\n10 7 9 4", "output": "31\n1 2 \n3 4 " }, { "input": "5 3 1\n5 2 5 1 7\n6 3 1 6 3", "output": "23\n1 3 5 \n4 " }, { "input": "2 1 1\n100 101\n1 100", "output": "200\n1 \n2 ...
0
0
-1
43,510
486
Palindrome Transformation
[ "brute force", "greedy", "implementation" ]
null
null
Nam is playing with a string on his computer. The string consists of *n* lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down. There is a cursor pointing at some symbol of the string. Suppose that cursor is at position *i* (1<=≤<=*i*<=≤<=*n*, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position *i*<=-<=1 if *i*<=&gt;<=1 or to the end of the string (i. e. position *n*) otherwise. The same holds when he presses the right arrow key (if *i*<==<=*n*, the cursor appears at the beginning of the string). When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key. Initially, the text cursor is at position *p*. Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
The first line contains two space-separated integers *n* (1<=≤<=*n*<=≤<=105) and *p* (1<=≤<=*p*<=≤<=*n*), the length of Nam's string and the initial position of the text cursor. The next line contains *n* lowercase characters of Nam's string.
Print the minimum number of presses needed to change string into a palindrome.
[ "8 3\naeabcaez\n" ]
[ "6\n" ]
A string is a palindrome if it reads the same forward or reversed. In the sample test, initial Nam's string is: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7cd1b7b2498296406fff738215b48ddd9a12898d.png" style="max-width: 100.0%;max-height: 100.0%;"/> (cursor position is shown bold). In optimal solution, Nam may do 6 following steps: The result, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f998673d1ad2128f8e2de7ff01895c8ef9ee34ff.png" style="max-width: 100.0%;max-height: 100.0%;"/>, is now a palindrome.
[ { "input": "8 3\naeabcaez", "output": "6" }, { "input": "8 3\nabcddcbb", "output": "3" }, { "input": "4 4\nrkoa", "output": "14" }, { "input": "39 30\nyehuqwaffoiyxhkmdipxroolhahbhzprioobxfy", "output": "138" }, { "input": "40 23\nvwjzsgpdsopsrpsyccavfkyyahdgkmdxr...
62
132,812,800
-1
43,578
138
Literature Lesson
[ "implementation" ]
null
null
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the *k*-th vowels (counting from the end) match. If a line has less than *k* vowels, then such line can't rhyme with any other line. For example, if *k*<==<=1, lines *commit* and *hermit* rhyme (the corresponding suffixes equal *it*), and if *k*<==<=2, they do not rhyme (*ommit*<=≠<=*ermit*). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): - Clerihew (*aabb*); - Alternating (*abab*); - Enclosed (*abba*). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by *aaaa*). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is *aaaa*. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=2500, 1<=≤<=*k*<=≤<=5) — the number of quatrains in the poem and the vowel's number, correspondingly. Next 4*n* lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
[ "1 1\nday\nmay\nsun\nfun\n", "1 1\nday\nmay\ngray\nway\n", "2 1\na\na\na\na\na\na\ne\ne\n", "2 1\nday\nmay\nsun\nfun\ntest\nhill\nfest\nthrill\n" ]
[ "aabb\n", "aaaa\n", "aabb\n", "NO\n" ]
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
[ { "input": "1 1\nday\nmay\nsun\nfun", "output": "aabb" }, { "input": "1 1\nday\nmay\ngray\nway", "output": "aaaa" }, { "input": "2 1\na\na\na\na\na\na\ne\ne", "output": "aabb" }, { "input": "2 1\nday\nmay\nsun\nfun\ntest\nhill\nfest\nthrill", "output": "NO" }, { "...
342
7,372,800
3
43,653
815
Karen and Neighborhood
[ "binary search", "constructive algorithms", "implementation" ]
null
null
It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood. The neighborhood consists of *n* houses in a straight line, labelled 1 to *n* from left to right, all an equal distance apart. Everyone in this neighborhood loves peace and quiet. Because of this, whenever a new person moves into the neighborhood, he or she always chooses the house whose minimum distance to any occupied house is maximized. If there are multiple houses with the maximum possible minimum distance, he or she chooses the leftmost one. Note that the first person to arrive always moves into house 1. Karen is the *k*-th person to enter this neighborhood. If everyone, including herself, follows this rule, which house will she move into?
The first and only line of input contains two integers, *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=1018), describing the number of houses in the neighborhood, and that Karen was the *k*-th person to move in, respectively.
Output a single integer on a line by itself, the label of the house Karen will move into.
[ "6 4\n", "39 3\n" ]
[ "2\n", "20\n" ]
In the first test case, there are 6 houses in the neighborhood, and Karen is the fourth person to move in: 1. The first person moves into house 1. 1. The second person moves into house 6. 1. The third person moves into house 3. 1. The fourth person moves into house 2. In the second test case, there are 39 houses in the neighborhood, and Karen is the third person to move in: 1. The first person moves into house 1. 1. The second person moves into house 39. 1. The third person moves into house 20.
[ { "input": "6 4", "output": "2" }, { "input": "39 3", "output": "20" }, { "input": "1 1", "output": "1" }, { "input": "1000000000000000000 1", "output": "1" }, { "input": "1000000000000000000 2", "output": "1000000000000000000" }, { "input": "69 69", ...
61
7,168,000
-1
43,668
102
Clothes
[ "brute force" ]
A. Clothes
2
256
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap. Overall the shop sells *n* clothing items, and exactly *m* pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.
The first input file line contains integers *n* and *m* — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the prices of the clothing items in rubles. Next *m* lines each contain a pair of space-separated integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=*u**i*<=≠<=*v**i*). Each such pair of numbers means that the *u**i*-th and the *v**i*-th clothing items match each other. It is guaranteed that in each pair *u**i* and *v**i* are distinct and all the unordered pairs (*u**i*,<=*v**i*) are different.
Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).
[ "3 3\n1 2 3\n1 2\n2 3\n3 1\n", "3 2\n2 3 4\n2 3\n2 1\n", "4 4\n1 1 1 1\n1 2\n2 3\n3 4\n4 1\n" ]
[ "6\n", "-1\n", "-1\n" ]
In the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles. The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1. In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.
[ { "input": "3 3\n1 2 3\n1 2\n2 3\n3 1", "output": "6" }, { "input": "3 2\n2 3 4\n2 3\n2 1", "output": "-1" }, { "input": "4 4\n1 1 1 1\n1 2\n2 3\n3 4\n4 1", "output": "-1" }, { "input": "4 3\n10 10 5 1\n2 1\n3 1\n3 4", "output": "-1" }, { "input": "4 0\n9 8 2 10",...
154
6,656,000
-1
43,705
711
Directed Roads
[ "combinatorics", "dfs and similar", "graphs", "math" ]
null
null
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of *n* towns numbered from 1 to *n*. There are *n* directed roads in the Udayland. *i*-th of them goes from town *i* to some other town *a**i* (*a**i*<=≠<=*i*). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town *A* to town *B* before the flip, it will go from town *B* to town *A* after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns *A*1,<=*A*2,<=...,<=*A**k* (*k*<=&gt;<=1) such that for every 1<=≤<=*i*<=&lt;<=*k* there is a road from town *A**i* to town *A**i*<=+<=1 and another road from town *A**k* to town *A*1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2*n* variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of towns in Udayland. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*,<=*a**i*<=≠<=*i*), *a**i* denotes a road going from town *i* to town *a**i*.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109<=+<=7.
[ "3\n2 3 1\n", "4\n2 1 1 1\n", "5\n2 4 2 5 3\n" ]
[ "6\n", "8\n", "28\n" ]
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e5b18c46402af724bd3841d549d5d6f52fc16253.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29f71c065c3536e88b54429c734103ad3604f68b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/030fc9181b578c2d906254d38dc56da5554323eb.png" style="max-width: 100.0%;max-height: 100.0%;"/> initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing. <img class="tex-graphics" src="https://espresso.codeforces.com/2e275877797bea4817665ce9cfb5274b837194bc.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "3\n2 3 1", "output": "6" }, { "input": "4\n2 1 1 1", "output": "8" }, { "input": "5\n2 4 2 5 3", "output": "28" }, { "input": "4\n2 1 4 3", "output": "4" }, { "input": "7\n2 3 4 1 6 5 4", "output": "56" }, { "input": "20\n2 3 4 5 6 7 8 9 10...
61
2,867,200
-1
43,745
802
Heidi and Library (easy)
[ "greedy" ]
null
null
Your search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are *n* different books, numbered 1 through *n*. We will look at the library's operation during *n* consecutive days. Heidi knows in advance that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) precisely one person will come to the library, request to borrow the book *a**i*, read it in a few hours, and return the book later on the same day. Heidi desperately wants to please all her guests, so she will make sure to always have the book *a**i* available in the library on the *i*-th day. During the night before the *i*-th day, she has the option of going to the bookstore (which operates at nights to avoid competition with the library) and buying any book for the price of 1 CHF. Of course, if she already has a book at the library, she does not need to buy it again. Initially, the library contains no books. There is a problem, though. The capacity of the library is *k* – this means that at any time, there can be at most *k* books at the library. If buying a new book would cause Heidi to have more than *k* books, she must first get rid of some book that she already has, in order to make room for the new book. If she later needs a book that she got rid of, she will need to buy that book again. You are given *k* and the sequence of requests for books *a*1,<=*a*2,<=...,<=*a**n*. What is the minimum cost (in CHF) of buying new books to satisfy all the requests?
The first line of input will contain two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=80). The second line will contain *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) – the sequence of book requests.
On a single line print the minimum cost of buying books at the store so as to satisfy all requests.
[ "4 80\n1 2 2 1\n", "4 1\n1 2 2 1\n", "4 2\n1 2 3 1\n" ]
[ "2\n", "3\n", "3\n" ]
In the first test case, Heidi is able to keep all books forever. Therefore, she only needs to buy the book 1 before the first day and the book 2 before the second day. In the second test case, she can only keep one book at a time. Therefore she will need to buy new books on the first, second and fourth day. In the third test case, before buying book 3 on the third day, she must decide which of the books 1 and 2 she should get rid of. Of course, she should keep the book 1, which will be requested on the fourth day.
[ { "input": "4 80\n1 2 2 1", "output": "2" }, { "input": "4 1\n1 2 2 1", "output": "3" }, { "input": "4 2\n1 2 3 1", "output": "3" }, { "input": "11 1\n1 2 3 5 1 10 10 1 1 3 5", "output": "9" }, { "input": "5 2\n1 2 3 1 2", "output": "4" }, { "input": "...
108
2,150,400
-1
43,761
825
String Compression
[ "dp", "hashing", "string suffix structures", "strings" ]
null
null
Ivan wants to write a letter to his friend. The letter is a string *s* consisting of lowercase Latin letters. Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string *s* instead of the string itself. The compressed version of string *s* is a sequence of strings *c*1,<=*s*1,<=*c*2,<=*s*2,<=...,<=*c**k*,<=*s**k*, where *c**i* is the decimal representation of number *a**i* (without any leading zeroes) and *s**i* is some string consisting of lowercase Latin letters. If Ivan writes string *s*1 exactly *a*1 times, then string *s*2 exactly *a*2 times, and so on, the result will be string *s*. The length of a compressed version is |*c*1|<=+<=|*s*1|<=+<=|*c*2|<=+<=|*s*2|... |*c**k*|<=+<=|*s**k*|. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length.
The only line of input contains one string *s* consisting of lowercase Latin letters (1<=≤<=|*s*|<=≤<=8000).
Output one integer number — the minimum possible length of a compressed version of *s*.
[ "aaaaaaaaaa\n", "abcab\n", "cczabababab\n" ]
[ "3\n", "6\n", "7\n" ]
In the first example Ivan will choose this compressed version: *c*<sub class="lower-index">1</sub> is 10, *s*<sub class="lower-index">1</sub> is a. In the second example Ivan will choose this compressed version: *c*<sub class="lower-index">1</sub> is 1, *s*<sub class="lower-index">1</sub> is abcab. In the third example Ivan will choose this compressed version: *c*<sub class="lower-index">1</sub> is 2, *s*<sub class="lower-index">1</sub> is c, *c*<sub class="lower-index">2</sub> is 1, *s*<sub class="lower-index">2</sub> is z, *c*<sub class="lower-index">3</sub> is 4, *s*<sub class="lower-index">3</sub> is ab.
[ { "input": "aaaaaaaaaa", "output": "3" }, { "input": "abcab", "output": "6" }, { "input": "cczabababab", "output": "7" }, { "input": "kbyjorwqjk", "output": "11" }, { "input": "baaabbbaba", "output": "9" }, { "input": "aaaaaaaaaa", "output": "3" ...
62
4,608,000
0
43,777
431
Random Task
[ "binary search", "bitmasks", "combinatorics", "dp", "math" ]
null
null
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer *n*, that among numbers *n*<=+<=1, *n*<=+<=2, ..., 2·*n* there are exactly *m* numbers which binary representation contains exactly *k* digits one". The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
The first line contains two space-separated integers, *m* and *k* (0<=≤<=*m*<=≤<=1018; 1<=≤<=*k*<=≤<=64).
Print the required number *n* (1<=≤<=*n*<=≤<=1018). If there are multiple answers, print any of them.
[ "1 1\n", "3 2\n" ]
[ "1\n", "5\n" ]
none
[ { "input": "1 1", "output": "1" }, { "input": "3 2", "output": "5" }, { "input": "3 3", "output": "7" }, { "input": "1 11", "output": "1024" }, { "input": "4 20", "output": "983040" }, { "input": "45902564 24", "output": "6406200698" }, { "...
109
1,228,800
3
43,802
717
Dexterina’s Lab
[ "games", "matrices", "probabilities" ]
null
null
Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges they’ve given to one another, their score is equal and they’re both desperately trying to best the other in various games of wits. This time, Dexterina challenged Womandark to a game of Nim. Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects from a single heap. The player who can't make a turn loses. By their agreement, the sizes of piles are selected randomly from the range [0,<=*x*]. Each pile's size is taken independently from the same probability distribution that is known before the start of the game. Womandark is coming up with a brand new and evil idea on how to thwart Dexterina’s plans, so she hasn’t got much spare time. She, however, offered you some tips on looking fabulous in exchange for helping her win in Nim. Your task is to tell her what is the probability that the first player to play wins, given the rules as above.
The first line of the input contains two integers *n* (1<=≤<=*n*<=≤<=109) and *x* (1<=≤<=*x*<=≤<=100) — the number of heaps and the maximum number of objects in a heap, respectively. The second line contains *x*<=+<=1 real numbers, given with up to 6 decimal places each: *P*(0),<=*P*(1),<=... ,<=*P*(*X*). Here, *P*(*i*) is the probability of a heap having exactly *i* objects in start of a game. It's guaranteed that the sum of all *P*(*i*) is equal to 1.
Output a single real number, the probability that the first player wins. The answer will be judged as correct if it differs from the correct answer by at most 10<=-<=6.
[ "2 2\n0.500000 0.250000 0.250000\n" ]
[ "0.62500000\n" ]
none
[ { "input": "2 2\n0.500000 0.250000 0.250000", "output": "0.62500000" }, { "input": "9 9\n0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000", "output": "0.93687014" }, { "input": "1000001 5\n0.000000 0.300000 0.000000 0.500000 0.000000 0.200000", ...
140
1,945,600
0
43,841
131
Opposites Attract
[ "implementation", "math" ]
null
null
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the *i*-th client number *t**i* (<=-<=10<=≤<=*t**i*<=≤<=10). Of course, one number can be assigned to any number of customers. "Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of *t*. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence *t*1,<=*t*2,<=...,<=*t**n*. For example, if *t*<==<=(1,<=<=-<=1,<=1,<=<=-<=1), then any two elements *t**i* and *t**j* form a couple if *i* and *j* have different parity. Consequently, in this case the sought number equals 4. Of course, a client can't form a couple with him/herself.
The first line of the input data contains an integer *n* (1<=≤<=*n*<=≤<=105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers *t*1,<=*t*2,<=...,<=*t**n* (<=-<=10<=≤<=*t**i*<=≤<=10), *t**i* — is the parameter of the *i*-th customer that has been assigned to the customer by the result of the analysis of his interests.
Print the number of couples of customs with opposite *t*. The opposite number for *x* is number <=-<=*x* (0 is opposite to itself). Couples that only differ in the clients' order are considered the same. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
[ "5\n-3 3 0 0 3\n", "3\n0 0 0\n" ]
[ "3\n", "3\n" ]
In the first sample the couples of opposite clients are: (1,2), (1,5) и (3,4). In the second sample any couple of clients is opposite.
[ { "input": "5\n-3 3 0 0 3", "output": "3" }, { "input": "3\n0 0 0", "output": "3" }, { "input": "1\n0", "output": "0" }, { "input": "1\n5", "output": "0" }, { "input": "2\n0 0", "output": "1" }, { "input": "2\n-3 3", "output": "1" }, { "inp...
30
0
0
43,859
266
More Queries to Array...
[ "data structures", "math" ]
null
null
You've got an array, consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. Your task is to quickly run the queries of two types: 1. Assign value *x* to all elements from *l* to *r* inclusive. After such query the values of the elements of array *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r* become equal to *x*.1. Calculate and print sum , where *k* doesn't exceed 5. As the value of the sum can be rather large, you should print it modulo 1000000007 (109<=+<=7).
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105), showing, how many numbers are in the array and the number of queries, correspondingly. The second line contains *n* integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109) — the initial values of the array elements. Then *m* queries follow, one per line: 1. The assign query has the following format: "", (1<=≤<=*l*<=≤<=*r*<=≤<=*n*; 0<=≤<=*x*<=≤<=109).1. The query to calculate the sum has the following format: "", (1<=≤<=*l*<=≤<=*r*<=≤<=*n*; 0<=≤<=*k*<=≤<=5). All numbers in the input are integers.
For each query to calculate the sum print an integer — the required sum modulo 1000000007 (109<=+<=7).
[ "4 5\n5 10 2 1\n? 1 2 1\n= 2 2 0\n? 2 4 3\n= 1 4 1\n? 1 4 5\n", "3 1\n1000000000 1000000000 1000000000\n? 1 3 0\n" ]
[ "25\n43\n1300\n", "999999986\n" ]
none
[]
92
1,228,800
0
43,929
715
Complete The Graph
[ "binary search", "constructive algorithms", "graphs", "shortest paths" ]
null
null
ZS the Coder has drawn an undirected graph of *n* vertices numbered from 0 to *n*<=-<=1 and *m* edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices *s* and *t* in the resulting graph is exactly *L*. Can you help him?
The first line contains five integers *n*,<=*m*,<=*L*,<=*s*,<=*t* (2<=≤<=*n*<=≤<=1000,<=<=1<=≤<=*m*<=≤<=10<=000,<=<=1<=≤<=*L*<=≤<=109,<=<=0<=≤<=*s*,<=*t*<=≤<=*n*<=-<=1,<=<=*s*<=≠<=*t*) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, *m* lines describing the edges of the graph follow. *i*-th of them contains three integers, *u**i*,<=*v**i*,<=*w**i* (0<=≤<=*u**i*,<=*v**i*<=≤<=*n*<=-<=1,<=<=*u**i*<=≠<=*v**i*,<=<=0<=≤<=*w**i*<=≤<=109). *u**i* and *v**i* denote the endpoints of the edge and *w**i* denotes its weight. If *w**i* is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices.
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next *m* lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. *i*-th of them should contain three integers *u**i*, *v**i* and *w**i*, denoting an edge between vertices *u**i* and *v**i* of weight *w**i*. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between *s* and *t* must be equal to *L*. If there are multiple solutions, print any of them.
[ "5 5 13 0 4\n0 1 5\n2 1 2\n3 2 3\n1 4 0\n4 3 4\n", "2 1 123456789 0 1\n0 1 0\n", "2 1 999999999 1 0\n0 1 1000000000\n" ]
[ "YES\n0 1 5\n2 1 2\n3 2 3\n1 4 8\n4 3 4\n", "YES\n0 1 123456789\n", "NO\n" ]
Here's how the graph in the first sample case looks like : In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
[ { "input": "5 5 13 0 4\n0 1 5\n2 1 2\n3 2 3\n1 4 0\n4 3 4", "output": "YES\n0 1 5\n2 1 2\n3 2 3\n1 4 8\n4 3 4" }, { "input": "2 1 123456789 0 1\n0 1 0", "output": "YES\n0 1 123456789" }, { "input": "2 1 999999999 1 0\n0 1 1000000000", "output": "NO" }, { "input": "4 5 10 1 2\...
4,000
27,238,400
0
43,963
590
Birthday
[ "graph matchings", "strings" ]
null
null
Today is birthday of a Little Dasha — she is now 8 years old! On this occasion, each of her *n* friends and relatives gave her a ribbon with a greeting written on it, and, as it turned out, all the greetings are different. Dasha gathered all the ribbons and decided to throw away some of them in order to make the remaining set stylish. The birthday girl considers a set of ribbons stylish if no greeting written on some ribbon is a substring of another greeting written on some other ribbon. Let us recall that the substring of the string *s* is a continuous segment of *s*. Help Dasha to keep as many ribbons as possible, so that she could brag about them to all of her friends. Dasha cannot rotate or flip ribbons, that is, each greeting can be read in a single way given in the input.
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=750) — the number of Dasha's relatives and friends. Each of the next *n* lines contains exactly one greeting. Each greeting consists of characters 'a' and 'b' only. The total length of all greetings won't exceed 10<=000<=000 characters.
In the first line print the maximum size of the stylish set. In the second line print the numbers of ribbons involved in it, assuming that they are numbered from 1 to *n* in the order they appear in the input. If there are several stylish sets of the maximum size, print any of them.
[ "5\nabab\naba\naabab\nababb\nbab\n" ]
[ "2\n2 5\n" ]
In the sample, the answer that keeps ribbons 3 and 4 is also considered correct.
[]
2,386
14,950,400
0
44,094
819
Mister B and Astronomers
[ "number theory" ]
null
null
After studying the beacons Mister B decided to visit alien's planet, because he learned that they live in a system of flickering star Moon. Moreover, Mister B learned that the star shines once in exactly *T* seconds. The problem is that the star is yet to be discovered by scientists. There are *n* astronomers numerated from 1 to *n* trying to detect the star. They try to detect the star by sending requests to record the sky for 1 second. The astronomers send requests in cycle: the *i*-th astronomer sends a request exactly *a**i* second after the (*i*<=-<=1)-th (i.e. if the previous request was sent at moment *t*, then the next request is sent at moment *t*<=+<=*a**i*); the 1-st astronomer sends requests *a*1 seconds later than the *n*-th. The first astronomer sends his first request at moment 0. Mister B doesn't know the first moment the star is going to shine, but it's obvious that all moments at which the star will shine are determined by the time of its shine moment in the interval [0,<=*T*). Moreover, this interval can be split into *T* parts of 1 second length each of form [*t*,<=*t*<=+<=1), where *t*<==<=0,<=1,<=2,<=...,<=(*T*<=-<=1). Mister B wants to know how lucky each astronomer can be in discovering the star first. For each astronomer compute how many segments of form [*t*,<=*t*<=+<=1) (*t*<==<=0,<=1,<=2,<=...,<=(*T*<=-<=1)) there are in the interval [0,<=*T*) so that this astronomer is the first to discover the star if the first shine of the star happens in this time interval.
The first line contains two integers *T* and *n* (1<=≤<=*T*<=≤<=109, 2<=≤<=*n*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
Print *n* integers: for each astronomer print the number of time segments describer earlier.
[ "4 2\n2 3\n", "5 4\n1 1 1 1\n" ]
[ "3 1 \n", "2 1 1 1 \n" ]
In the first sample test the first astronomer will send requests at moments *t*<sub class="lower-index">1</sub> = 0, 5, 10, ..., the second — at moments *t*<sub class="lower-index">2</sub> = 3, 8, 13, .... That's why interval [0, 1) the first astronomer will discover first at moment *t*<sub class="lower-index">1</sub> = 0, [1, 2) — the first astronomer at moment *t*<sub class="lower-index">1</sub> = 5, [2, 3) — the first astronomer at moment *t*<sub class="lower-index">1</sub> = 10, and [3, 4) — the second astronomer at moment *t*<sub class="lower-index">2</sub> = 3. In the second sample test interval [0, 1) — the first astronomer will discover first, [1, 2) — the second astronomer, [2, 3) — the third astronomer, [3, 4) — the fourth astronomer, [4, 5) — the first astronomer.
[]
62
0
0
44,119
895
Square Subsets
[ "bitmasks", "combinatorics", "dp", "math" ]
null
null
Petya was late for the lesson too. The teacher gave him an additional task. For some array *a* Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer. Two ways are considered different if sets of indexes of elements chosen by these ways are different. Since the answer can be very large, you should find the answer modulo 109<=+<=7.
First line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. Second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=70) — the elements of the array.
Print one integer — the number of different ways to choose some elements so that their product is a square of a certain integer modulo 109<=+<=7.
[ "4\n1 1 1 1\n", "4\n2 2 2 2\n", "5\n1 2 4 5 8\n" ]
[ "15\n", "7\n", "7\n" ]
In first sample product of elements chosen by any way is 1 and 1 = 1<sup class="upper-index">2</sup>. So the answer is 2<sup class="upper-index">4</sup> - 1 = 15. In second sample there are six different ways to choose elements so that their product is 4, and only one way so that their product is 16. So the answer is 6 + 1 = 7.
[ { "input": "4\n1 1 1 1", "output": "15" }, { "input": "4\n2 2 2 2", "output": "7" }, { "input": "5\n1 2 4 5 8", "output": "7" }, { "input": "1\n64", "output": "1" }, { "input": "5\n2 2 2 2 2", "output": "15" }, { "input": "6\n1 2 3 4 5 6", "output"...
0
0
-1
44,302
718
Matvey's Birthday
[ "bitmasks", "graphs" ]
null
null
Today is Matvey's birthday. He never knows what to ask as a present so friends gave him a string *s* of length *n*. This string consists of only first eight English letters: 'a', 'b', ..., 'h'. First question that comes to mind is: who might ever need some string? Matvey is a special boy so he instantly found what to do with this string. He used it to build an undirected graph where vertices correspond to position in the string and there is an edge between distinct positions *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=*n*) if at least one of the following conditions hold: 1. *a* and *b* are neighbouring, i.e. |*a*<=-<=*b*|<==<=1. 1. Positions *a* and *b* contain equal characters, i.e. *s**a*<==<=*s**b*. Then Matvey decided to find the diameter of this graph. Diameter is a maximum distance (length of the shortest path) among all pairs of vertices. Also, Matvey wants to find the number of pairs of vertices such that the distance between them is equal to the diameter of the graph. As he is very cool and experienced programmer he managed to solve this problem very fast. Will you do the same?
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000) — the length of the string. The second line contains the string *s* itself. It's guaranteed that *s* consists of only first eight letters of English alphabet.
Print two integers — the diameter of the graph and the number of pairs of positions with the distance equal to the diameter.
[ "3\nabc\n", "7\naaabaaa\n" ]
[ "2 1\n", "2 4\n" ]
Consider the second sample. The maximum distance is 2. It's obtained for pairs (1, 4), (2, 4), (4, 6) and (4, 7).
[]
2,000
27,852,800
0
44,306
767
The Queue
[ "brute force", "greedy" ]
null
null
Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow. He knows that the receptionist starts working after *t**s* minutes have passed after midnight and closes after *t**f* minutes have passed after midnight (so that (*t**f*<=-<=1) is the last minute when the receptionist is still working). The receptionist spends exactly *t* minutes on each person in the queue. If the receptionist would stop working within *t* minutes, he stops serving visitors (other than the one he already serves). Vasya also knows that exactly *n* visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately. For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them. Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!
The first line contains three integers: the point of time when the receptionist begins to work *t**s*, the point of time when the receptionist stops working *t**f* and the time the receptionist spends on each visitor *t*. The second line contains one integer *n* — the amount of visitors (0<=≤<=*n*<=≤<=100<=000). The third line contains positive integers in non-decreasing order — the points of time when the visitors arrive to the passport office. All times are set in minutes and do not exceed 1012; it is guaranteed that *t**s*<=&lt;<=*t**f*. It is also guaranteed that Vasya can arrive at the passport office at such a point of time that he would be served by the receptionist.
Print single non-negative integer — the point of time when Vasya should arrive at the passport office. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and queues up the last. If there are many answers, you can print any of them.
[ "10 15 2\n2\n10 13\n", "8 17 3\n4\n3 4 5 8\n" ]
[ "12", "2" ]
In the first example the first visitor comes exactly at the point of time when the receptionist begins to work, and he is served for two minutes. At 12 minutes after the midnight the receptionist stops serving the first visitor, and if Vasya arrives at this moment, he will be served immediately, because the next visitor would only come at 13 minutes after midnight. In the second example, Vasya has to come before anyone else to be served.
[ { "input": "10 15 2\n2\n10 13", "output": "12" }, { "input": "8 17 3\n4\n3 4 5 8", "output": "2" }, { "input": "7 14 3\n2\n1 2", "output": "0" }, { "input": "30 70 10\n3\n30 32 35", "output": "60" }, { "input": "21 56 7\n5\n1 2 3 4 5", "output": "0" }, { ...
93
13,516,800
3
44,398
584
Dima and Lisa
[ "brute force", "math", "number theory" ]
null
null
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes. More formally, you are given an odd numer *n*. Find a set of numbers *p**i* (1<=≤<=*i*<=≤<=*k*), such that 1. 1<=≤<=*k*<=≤<=31. *p**i* is a prime1. The numbers *p**i* do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.
The single line contains an odd number *n* (3<=≤<=*n*<=&lt;<=109).
In the first line print *k* (1<=≤<=*k*<=≤<=3), showing how many numbers are in the representation you found. In the second line print numbers *p**i* in any order. If there are multiple possible solutions, you can print any of them.
[ "27\n" ]
[ "3\n5 11 11\n" ]
A prime is an integer strictly larger than one that is divisible only by one and by itself.
[ { "input": "27", "output": "3\n2 2 23" }, { "input": "3", "output": "1\n3" }, { "input": "25", "output": "2\n2 23" }, { "input": "9", "output": "2\n2 7" }, { "input": "91", "output": "2\n2 89" }, { "input": "57", "output": "3\n2 2 53" }, { ...
46
0
0
44,737
581
Zublicanes and Mumocrates
[ "dp", "trees", "two pointers" ]
null
null
It's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on *n* main squares of the capital of Berland. Each of the *n* squares certainly can have demonstrations of only one party, otherwise it could lead to riots. On the other hand, both parties have applied to host a huge number of demonstrations, so that on all squares demonstrations must be held. Now the capital management will distribute the area between the two parties. Some pairs of squares are connected by (*n*<=-<=1) bidirectional roads such that between any pair of squares there is a unique way to get from one square to another. Some squares are on the outskirts of the capital meaning that they are connected by a road with only one other square, such squares are called dead end squares. The mayor of the capital instructed to distribute all the squares between the parties so that the dead end squares had the same number of demonstrations of the first and the second party. It is guaranteed that the number of dead end squares of the city is even. To prevent possible conflicts between the zublicanes and the mumocrates it was decided to minimize the number of roads connecting the squares with the distinct parties. You, as a developer of the department of distributing squares, should determine this smallest number.
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=5000) — the number of squares in the capital of Berland. Next *n*<=-<=1 lines contain the pairs of integers *x*,<=*y* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*) — the numbers of the squares connected by the road. All squares are numbered with integers from 1 to *n*. It is guaranteed that the number of dead end squares of the city is even.
Print a single number — the minimum number of roads connecting the squares with demonstrations of different parties.
[ "8\n1 4\n2 4\n3 4\n6 5\n7 5\n8 5\n4 5\n", "5\n1 2\n1 3\n1 4\n1 5\n" ]
[ "1\n", "2\n" ]
none
[ { "input": "8\n1 4\n2 4\n3 4\n6 5\n7 5\n8 5\n4 5", "output": "1" }, { "input": "5\n1 2\n1 3\n1 4\n1 5", "output": "2" }, { "input": "11\n1 7\n2 1\n2 9\n6 2\n7 10\n1 3\n5 2\n3 8\n8 11\n2 4", "output": "2" }, { "input": "20\n2 18\n15 18\n18 4\n4 20\n20 6\n8 6\n1 8\n9 6\n11 9\n1...
0
0
-1
44,755
533
Board Game
[ "games", "greedy", "implementation", "math" ]
null
null
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (*x*,<=*y*) to (*x*<=-<=1,<=*y*) or (*x*,<=*y*<=-<=1). Vasiliy can move his pawn from (*x*,<=*y*) to one of cells: (*x*<=-<=1,<=*y*),<=(*x*<=-<=1,<=*y*<=-<=1) and (*x*,<=*y*<=-<=1). Both players are also allowed to skip move. There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative *x*-coordinate or *y*-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0,<=0). You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
The first line contains four integers: *x**p*,<=*y**p*,<=*x**v*,<=*y**v* (0<=≤<=*x**p*,<=*y**p*,<=*x**v*,<=*y**v*<=≤<=105) — Polycarp's and Vasiliy's starting coordinates. It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0,<=0).
Output the name of the winner: "Polycarp" or "Vasiliy".
[ "2 1 2 2\n", "4 7 7 4\n" ]
[ "Polycarp\n", "Vasiliy\n" ]
In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn.
[ { "input": "2 1 2 2", "output": "Polycarp" }, { "input": "4 7 7 4", "output": "Vasiliy" }, { "input": "20 0 7 22", "output": "Polycarp" }, { "input": "80 100 83 97", "output": "Vasiliy" }, { "input": "80 100 77 103", "output": "Vasiliy" }, { "input": "...
61
6,758,400
0
44,793
629
Famil Door and Roads
[ "combinatorics", "data structures", "dfs and similar", "dp", "probabilities", "trees" ]
null
null
Famil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are *n* intersections in the city connected by *n*<=-<=1 bidirectional roads. There are *m* friends of Famil Door living in the city. The *i*-th friend lives at the intersection *u**i* and works at the intersection *v**i*. Everyone in the city is unhappy because there is exactly one simple path between their home and work. Famil Door plans to construct exactly one new road and he will randomly choose one among *n*·(*n*<=-<=1)<=/<=2 possibilities. Note, that he may even build a new road between two cities that are already connected by one. He knows, that each of his friends will become happy, if after Famil Door constructs a new road there is a path from this friend home to work and back that doesn't visit the same road twice. Formally, there is a simple cycle containing both *u**i* and *v**i*. Moreover, if the friend becomes happy, his pleasure is equal to the length of such path (it's easy to see that it's unique). For each of his friends Famil Door wants to know his expected pleasure, that is the expected length of the cycle containing both *u**i* and *v**i* if we consider only cases when such a cycle exists.
The first line of the input contains integers *n* and *m* (2<=≤<=*n*,<= *m*<=≤<=100<=000) — the number of the intersections in the Treeland and the number of Famil Door's friends. Then follow *n*<=-<=1 lines describing bidirectional roads. Each of them contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*) — the indices of intersections connected by the *i*-th road. Last *m* lines of the input describe Famil Door's friends. The *i*-th of these lines contain two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=*u**i*<=≠<=*v**i*) — indices of intersections where the *i*-th friend lives and works.
For each friend you should print the expected value of pleasure if he will be happy. 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 .
[ "4 3\n2 4\n4 1\n3 2\n3 1\n2 3\n4 1\n", "3 3\n1 2\n1 3\n1 2\n1 3\n2 3\n" ]
[ "4.00000000\n3.00000000\n3.00000000\n", "2.50000000\n2.50000000\n3.00000000\n" ]
Consider the second sample. 1. Both roads (1, 2) and (2, 3) work, so the expected length if <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ec563337e40cadafa8449c9571eb5b8c7199e10c.png" style="max-width: 100.0%;max-height: 100.0%;"/> 1. Roads (1, 3) and (2, 3) make the second friend happy. Same as for friend 1 the answer is 2.5 1. The only way to make the third friend happy is to add road (2, 3), so the answer is 3
[ { "input": "4 3\n2 4\n4 1\n3 2\n3 1\n2 3\n4 1", "output": "4.00000000\n3.00000000\n3.00000000" }, { "input": "3 3\n1 2\n1 3\n1 2\n1 3\n2 3", "output": "2.50000000\n2.50000000\n3.00000000" }, { "input": "10 5\n8 10\n3 6\n7 3\n7 4\n8 9\n9 4\n5 1\n10 5\n6 2\n9 1\n7 6\n5 1\n6 9\n10 2", "...
46
0
0
44,854
700
Huffman Coding on Segment
[ "data structures", "greedy" ]
null
null
Alice wants to send an important message to Bob. Message *a*<==<=(*a*1,<=...,<=*a**n*) is a sequence of positive integers (characters). To compress the message Alice wants to use binary Huffman coding. We recall that binary Huffman code, or binary prefix code is a function *f*, that maps each letter that appears in the string to some binary string (that is, string consisting of characters '0' and '1' only) such that for each pair of different characters *a**i* and *a**j* string *f*(*a**i*) is not a prefix of *f*(*a**j*) (and vice versa). The result of the encoding of the message *a*1,<=*a*2,<=...,<=*a**n* is the concatenation of the encoding of each character, that is the string *f*(*a*1)*f*(*a*2)... *f*(*a**n*). Huffman codes are very useful, as the compressed message can be easily and uniquely decompressed, if the function *f* is given. Code is usually chosen in order to minimize the total length of the compressed message, i.e. the length of the string *f*(*a*1)*f*(*a*2)... *f*(*a**n*). Because of security issues Alice doesn't want to send the whole message. Instead, she picks some substrings of the message and wants to send them separately. For each of the given substrings *a**l**i*... *a**r**i* she wants to know the minimum possible length of the Huffman coding. Help her solve this problem.
The first line of the input contains the single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the length of the initial message. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100<=000) — characters of the message. Next line contains the single integer *q* (1<=≤<=*q*<=≤<=100<=000) — the number of queries. Then follow *q* lines with queries descriptions. The *i*-th of these lines contains two integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*) — the position of the left and right ends of the *i*-th substring respectively. Positions are numbered from 1. Substrings may overlap in any way. The same substring may appear in the input more than once.
Print *q* lines. Each line should contain a single integer — the minimum possible length of the Huffman encoding of the substring *a**l**i*... *a**r**i*.
[ "7\n1 2 1 3 1 2 1\n5\n1 7\n1 3\n3 5\n2 4\n4 4\n" ]
[ "10\n3\n3\n5\n0\n" ]
In the first query, one of the optimal ways to encode the substring is to map 1 to "0", 2 to "10" and 3 to "11". Note that it is correct to map the letter to the empty substring (as in the fifth query from the sample).
[]
62
512,000
0
44,871
723
Lakes in Berland
[ "dfs and similar", "dsu", "graphs", "greedy", "implementation" ]
null
null
The map of Berland is a rectangle of the size *n*<=×<=*m*, which consists of cells of size 1<=×<=1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell. You task is to fill up with the earth the minimum number of water cells so that there will be exactly *k* lakes in Berland. Note that the initial number of lakes on the map is not less than *k*.
The first line of the input contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=50, 0<=≤<=*k*<=≤<=50) — the sizes of the map and the number of lakes which should be left on the map. The next *n* lines contain *m* characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least *k* lakes.
In the first line print the minimum number of cells which should be transformed from water to land. In the next *n* lines print *m* symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them. It is guaranteed that the answer exists on the given data.
[ "5 4 1\n****\n*..*\n****\n**.*\n..**\n", "3 3 0\n***\n*.*\n***\n" ]
[ "1\n****\n*..*\n****\n****\n..**\n", "1\n***\n***\n***\n" ]
In the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.
[ { "input": "5 4 1\n****\n*..*\n****\n**.*\n..**", "output": "1\n****\n*..*\n****\n****\n..**" }, { "input": "3 3 0\n***\n*.*\n***", "output": "1\n***\n***\n***" }, { "input": "3 5 1\n.**.*\n*.*.*\n***..", "output": "0\n.**.*\n*.*.*\n***.." }, { "input": "3 5 0\n.**.*\n*.*.*\n...
124
4,096,000
3
44,997
763
Timofey and remoduling
[ "brute force", "implementation", "math", "number theory" ]
null
null
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime *m*. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of distinct integers *a*1,<=*a*2,<=...,<=*a**n*. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo *m*, or not. Arithmetical progression modulo *m* of length *n* with first element *x* and difference *d* is sequence of integers *x*,<=*x*<=+<=*d*,<=*x*<=+<=2*d*,<=...,<=*x*<=+<=(*n*<=-<=1)·*d*, each taken modulo *m*.
The first line contains two integers *m* and *n* (2<=≤<=*m*<=≤<=109<=+<=7, 1<=≤<=*n*<=≤<=105, *m* is prime) — Timofey's favorite prime module and the length of the sequence. The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=&lt;<=*m*) — the elements of the sequence.
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo *m*. Otherwise, print two integers — the first element of the obtained progression *x* (0<=≤<=*x*<=&lt;<=*m*) and its difference *d* (0<=≤<=*d*<=&lt;<=*m*). If there are multiple answers, print any of them.
[ "17 5\n0 2 4 13 15\n", "17 5\n0 2 4 13 14\n", "5 3\n1 2 3\n" ]
[ "13 2\n", "-1\n", "3 4\n" ]
none
[ { "input": "17 5\n0 2 4 13 15", "output": "13 2" }, { "input": "17 5\n0 2 4 13 14", "output": "-1" }, { "input": "5 3\n1 2 3", "output": "3 4" }, { "input": "17 8\n7 9 11 13 15 1 3 5", "output": "1 2" }, { "input": "13 2\n0 11", "output": "0 11" }, { "...
217
8,089,600
0
45,038
536
Tavas in Kansas
[ "dp", "games" ]
null
null
Tavas lives in Kansas. Kansas has *n* cities numbered from 1 to *n* connected with *m* bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities. Tavas invented a game and called it "Dashti". He wants to play Dashti with his girlfriends, Nafas. In this game, they assign an arbitrary integer value to each city of Kansas. The value of *i*-th city equals to *p**i*. During the game, Tavas is in city *s* and Nafas is in city *t*. They play in turn and Tavas goes first. A player in his/her turn, must choose a non-negative integer *x* and his/her score increases by the sum of values of all cities with (shortest) distance no more than *x* from his/her city. Each city may be used once, or in the other words, after first time a player gets score from a city, city score becomes zero. There is an additional rule: the player must choose *x* such that he/she gets the point of at least one city that was not used before. Note that city may initially have value 0, such city isn't considered as been used at the beginning of the game, i. e. each player may use it to fullfill this rule. The game ends when nobody can make a move. A player's score is the sum of the points he/she earned during the game. The winner is the player with greater score, or there is a draw if players score the same value. Both players start game with zero points. If Tavas wins, he'll break his girlfriend's heart, and if Nafas wins, Tavas will cry. But if their scores are equal, they'll be happy and Tavas will give Nafas flowers. They're not too emotional after all, so they'll play optimally. Your task is to tell Tavas what's going to happen after the game ends.
The first line of input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=2000, *n*<=-<=1<=≤<=*m*<=≤<=105). The second line of input contains two integers *s* and *t* (1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*). The next line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* separated by spaces (|*p**i*|<=≤<=109). The next *m* lines contain the roads. Each line contains three integers *v*,<=*u*,<=*w* and it means that there's an road with length *w* between cities *v* and *u* (1<=≤<=*u*,<=*v*<=≤<=*n* and 0<=≤<=*w*<=≤<=109). The road may lead from the city to itself, there may be several roads between each pair of cities.
If Tavas wins, print "Break a heart". If Nafas wins print "Cry" and if nobody wins (i. e. the game ended with draw) print "Flowers".
[ "4 4\n1 2\n3 2 5 -11\n1 4 2\n3 4 2\n3 1 5\n3 2 1\n", "5 4\n1 2\n2 2 -5 -4 6\n1 2 4\n2 3 5\n2 4 2\n4 5 2\n", "2 1\n1 2\n-5 -5\n1 2 10\n" ]
[ "Cry\n", "Break a heart\n", "Flowers\n" ]
none
[]
0
0
-1
45,103
543
Remembering Strings
[ "bitmasks", "dp" ]
null
null
You have multiset of *n* strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position *i* and some letter *c* of the English alphabet, such that this string is the only string in the multiset that has letter *c* in position *i*. For example, a multiset of strings {"abc", "aba", "adc", "ada"} are not easy to remember. And multiset {"abc", "ada", "ssa"} is easy to remember because: - the first string is the only string that has character *c* in position 3; - the second string is the only string that has character *d* in position 2; - the third string is the only string that has character *s* in position 2. You want to change your multiset a little so that it is easy to remember. For *a**ij* coins, you can change character in the *j*-th position of the *i*-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember.
The first line contains two integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=20) — the number of strings in the multiset and the length of the strings respectively. Next *n* lines contain the strings of the multiset, consisting only of lowercase English letters, each string's length is *m*. Next *n* lines contain *m* integers each, the *i*-th of them contains integers *a**i*1,<=*a**i*2,<=...,<=*a**im* (0<=≤<=*a**ij*<=≤<=106).
Print a single number — the answer to the problem.
[ "4 5\nabcde\nabcde\nabcde\nabcde\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n", "4 3\nabc\naba\nadc\nada\n10 10 10\n10 1 10\n10 10 10\n10 1 10\n", "3 3\nabc\nada\nssa\n1 1 1\n1 1 1\n1 1 1\n" ]
[ "3\n", "2\n", "0\n" ]
none
[ { "input": "4 5\nabcde\nabcde\nabcde\nabcde\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1", "output": "3" }, { "input": "4 3\nabc\naba\nadc\nada\n10 10 10\n10 1 10\n10 10 10\n10 1 10", "output": "2" }, { "input": "3 3\nabc\nada\nssa\n1 1 1\n1 1 1\n1 1 1", "output": "0" }, { "in...
686
21,504,000
3
45,179
533
Landmarks
[ "data structures", "dp" ]
null
null
We have an old building with *n*<=+<=2 columns in a row. These columns support the ceiling. These columns are located in points with coordinates 0<==<=*x*0<=&lt;<=*x*1<=&lt;<=...<=&lt;<=*x**n*<=&lt;<=*x**n*<=+<=1. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary. For each column we know its durability *d**i*. Let's consider an ordinary column with coordinate *x*. Let's assume that the coordinate of the closest to it column to the left (bearing or ordinary) is *a* and the coordinate of the closest to it column to the right (also, bearing or ordinary) is *b*. In this task let's assume that this column supports the segment of the ceiling from point to point (here both fractions are considered as real division). If the length of the segment of the ceiling supported by the column exceeds *d**i*, then the column cannot support it and it crashes after a while, and after that the load is being redistributeed between the neighbouring columns according to the same principle. Thus, ordinary columns will be crashing for some time until the process stops at some state. One can prove that the set of the remaining columns doesn't depend on the order in which columns crash. If there are only two bearing columns left in the end, then we assume that the whole construction crashes under the weight of the roof. But if at least one ordinary column stays in addition to the bearing ones, then the building doesn't crash. To make the building stronger, we can add one extra ordinary column of arbitrary durability *d*' at any (not necessarily integer) point 0<=&lt;<=*x*'<=&lt;<=*x**n*<=+<=1. If point *x*' is already occupied by an ordinary column, it is replaced by a new one. Your task is to find out: what minimal durability can the added column have so that the building doesn't crash?
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of ordinary columns. The second line contains *n*<=+<=2 integers *x*0,<=*x*1,<=...,<=*x**n*,<=*x**n*<=+<=1 (*x*0<==<=0, *x**i*<=&lt;<=*x**i*<=+<=1 for 0<=≤<=*i*<=≤<=*n*, *x**n*<=+<=1<=≤<=109) — the coordinates of the columns. The third line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≤<=*d**i*<=≤<=109).
Print a single number — the minimum possible durability of the column that you need to add in order to make the building stay. If you do not have to add the column, please print 0. Your answer will be checked with the relative or absolute error 10<=-<=4.
[ "2\n0 20 40 100\n15 40\n", "3\n0 4 10 28 30\n9 13 5\n" ]
[ "10\n", "0\n" ]
none
[]
30
0
0
45,385
69
Bets
[ "greedy", "implementation" ]
B. Bets
2
256
In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor. To begin with friends learned the rules: in the race there are *n* sections of equal length and *m* participants. The participants numbered from 1 to *m*. About each participant the following is known: - *l**i* — the number of the starting section, - *r**i* — the number of the finishing section (*l**i*<=≤<=*r**i*),- *t**i* — the time a biathlete needs to complete an section of the path,- *c**i* — the profit in roubles. If the *i*-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The *i*-th biathlete passes the sections from *l**i* to *r**i* inclusive. The competitor runs the whole way in (*r**i*<=-<=*l**i*<=+<=1)·*t**i* time units. It takes him exactly *t**i* time units to pass each section. In case of the athlete's victory on *k* sections the man who has betted on him receives *k*·*c**i* roubles. In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed. We should also add that Nikita can bet on each section and on any contestant running in this section. Help the friends find the maximum possible profit.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100). Then follow *m* lines, each containing 4 integers *l**i*, *r**i*, *t**i*, *c**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*, 1<=≤<=*t**i*,<=*c**i*<=≤<=1000).
Print a single integer, the maximal profit in roubles that the friends can get. In each of *n* sections it is not allowed to place bets on more than one sportsman.
[ "4 4\n1 4 20 5\n1 3 21 10\n3 3 4 30\n3 4 4 20\n", "8 4\n1 5 24 10\n2 4 6 15\n4 6 30 50\n6 7 4 20\n" ]
[ "60", "105" ]
In the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles. In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles.
[ { "input": "4 4\n1 4 20 5\n1 3 21 10\n3 3 4 30\n3 4 4 20", "output": "60" }, { "input": "8 4\n1 5 24 10\n2 4 6 15\n4 6 30 50\n6 7 4 20", "output": "105" }, { "input": "2 2\n1 2 3 1\n2 2 3 10", "output": "2" }, { "input": "20 30\n15 17 54 46\n4 18 26 18\n18 20 49 94\n12 12 83 ...
92
0
3.977
45,394
0
none
[ "none" ]
null
null
A newspaper is published in Walrusland. Its heading is *s*1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word *s*2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters. For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac". Which least number of newspaper headings *s*1 will Fangy need to glue them, erase several letters and get word *s*2?
The input data contain two lines. The first line contain the heading *s*1, the second line contains the word *s*2. The lines only consist of lowercase Latin letters (1<=≤<=|*s*1|<=≤<=104,<=1<=≤<=|*s*2|<=≤<=106).
If it is impossible to get the word *s*2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings *s*1, which Fangy will need to receive the word *s*2.
[ "abc\nxyz\n", "abcd\ndabc\n" ]
[ "-1\n", "2\n" ]
none
[ { "input": "abc\nxyz", "output": "-1" }, { "input": "abcd\ndabc", "output": "2" }, { "input": "ab\nbabaaab", "output": "5" }, { "input": "ab\nbaaabba", "output": "6" }, { "input": "fbaaigiihhfaahgdbddgeggjdeigfadhfddja\nhbghjgijijcdafcbgiedichdeebaddfddb", "ou...
186
10,240,000
-1
45,440
620
Professor GukiZ and Two Arrays
[ "binary search", "two pointers" ]
null
null
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a *s**a* as close as possible to the sum of the elements in the array b *s**b*. So he wants to minimize the value *v*<==<=|*s**a*<=-<=*s**b*|. In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5,<=1,<=3,<=2,<=4] and the array b is [3,<=3,<=2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2,<=1,<=3,<=2,<=4] and the new array b [3,<=3,<=5]. Professor doesn't want to make more than two swaps. Find the minimal value *v* and some sequence of no more than two swaps that will lead to the such value *v*. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of elements in the array a. The second line contains *n* integers *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) — the elements of the array a. The third line contains integer *m* (1<=≤<=*m*<=≤<=2000) — the number of elements in the array b. The fourth line contains *m* integers *b**j* (<=-<=109<=≤<=*b**j*<=≤<=109) — the elements of the array b.
In the first line print the minimal value *v*<==<=|*s**a*<=-<=*s**b*| that can be got with no more than two swaps. The second line should contain the number of swaps *k* (0<=≤<=*k*<=≤<=2). Each of the next *k* lines should contain two integers *x**p*,<=*y**p* (1<=≤<=*x**p*<=≤<=*n*,<=1<=≤<=*y**p*<=≤<=*m*) — the index of the element in the array a and the index of the element in the array b in the *p*-th swap. If there are several optimal solutions print any of them. Print the swaps in order the professor did them.
[ "5\n5 4 3 2 1\n4\n1 1 1 1\n", "5\n1 2 3 4 5\n1\n15\n", "5\n1 2 3 4 5\n4\n1 2 3 4\n" ]
[ "1\n2\n1 1\n4 2\n", "0\n0\n", "1\n1\n3 1\n" ]
none
[ { "input": "5\n5 4 3 2 1\n4\n1 1 1 1", "output": "1\n2\n1 1\n4 2" }, { "input": "5\n1 2 3 4 5\n1\n15", "output": "0\n0" }, { "input": "5\n1 2 3 4 5\n4\n1 2 3 4", "output": "1\n1\n3 1" }, { "input": "1\n-42\n1\n-86", "output": "44\n0" }, { "input": "1\n-21\n10\n-43...
30
0
0
45,472
671
Robin Hood
[ "binary search", "greedy" ]
null
null
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor. There are *n* citizens in Kekoland, each person has *c**i* coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in *k* days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after *k* days. Note that the choosing at random among richest and poorest doesn't affect the answer.
The first line of the input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=500<=000,<=0<=≤<=*k*<=≤<=109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement. The second line contains *n* integers, the *i*-th of them is *c**i* (1<=≤<=*c**i*<=≤<=109) — initial wealth of the *i*-th person.
Print a single line containing the difference between richest and poorest peoples wealth.
[ "4 1\n1 1 4 2\n", "3 1\n2 2 2\n" ]
[ "2\n", "0\n" ]
Lets look at how wealth changes through day in the first sample. 1. [1, 1, 4, 2] 1. [2, 1, 3, 2] or [1, 2, 3, 2] So the answer is 3 - 1 = 2 In second sample wealth will remain the same for each person.
[ { "input": "4 1\n1 1 4 2", "output": "2" }, { "input": "3 1\n2 2 2", "output": "0" }, { "input": "10 20\n6 4 7 10 4 5 5 3 7 10", "output": "1" }, { "input": "30 7\n3 3 2 2 2 2 3 4 4 5 2 1 1 5 5 3 4 3 2 1 3 4 3 2 2 5 2 5 1 2", "output": "2" }, { "input": "2 0\n182 ...
109
0
0
45,480
41
Pawn
[ "dp" ]
D. Pawn
2
256
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its *k* brothers, the number of peas must be divisible by *k*<=+<=1. Find the maximal number of peas it will be able to collect and which moves it should make to do it. The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
The first line contains three integers *n*, *m*, *k* (2<=≤<=*n*,<=*m*<=≤<=100,<=0<=≤<=*k*<=≤<=10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow *n* lines containing each *m* numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
If it is impossible to reach the highest row having collected the number of peas divisible by *k*<=+<=1, print -1. Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by *k*<=+<=1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of *n*<=-<=1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
[ "3 3 1\n123\n456\n789\n", "3 3 0\n123\n456\n789\n", "2 2 10\n98\n75\n" ]
[ "16\n2\nRL\n", "17\n3\nLR\n", "-1\n" ]
none
[ { "input": "3 3 1\n123\n456\n789", "output": "16\n2\nRL" }, { "input": "3 3 0\n123\n456\n789", "output": "17\n3\nLR" }, { "input": "2 2 10\n98\n75", "output": "-1" }, { "input": "3 4 2\n8244\n4768\n4474", "output": "18\n3\nLR" }, { "input": "4 3 10\n194\n707\n733\...
92
4,915,200
0
45,563
922
Birds
[ "dp" ]
null
null
Apart from plush toys, Imp is a huge fan of little yellow birds! To summon birds, Imp needs strong magic. There are *n* trees in a row on an alley in a park, there is a nest on each of the trees. In the *i*-th nest there are *c**i* birds; to summon one bird from this nest Imp needs to stay under this tree and it costs him *cost**i* points of mana. However, for each bird summoned, Imp increases his mana capacity by *B* points. Imp summons birds one by one, he can summon any number from 0 to *c**i* birds from the *i*-th nest. Initially Imp stands under the first tree and has *W* points of mana, and his mana capacity equals *W* as well. He can only go forward, and each time he moves from a tree to the next one, he restores *X* points of mana (but it can't exceed his current mana capacity). Moving only forward, what is the maximum number of birds Imp can summon?
The first line contains four integers *n*, *W*, *B*, *X* (1<=≤<=*n*<=≤<=103,<=0<=≤<=*W*,<=*B*,<=*X*<=≤<=109) — the number of trees, the initial points of mana, the number of points the mana capacity increases after a bird is summoned, and the number of points restored when Imp moves from a tree to the next one. The second line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (0<=≤<=*c**i*<=≤<=104) — where *c**i* is the number of birds living in the *i*-th nest. It is guaranteed that . The third line contains *n* integers *cost*1,<=*cost*2,<=...,<=*cost**n* (0<=≤<=*cost**i*<=≤<=109), where *cost**i* is the mana cost to summon a bird from the *i*-th nest.
Print a single integer — the maximum number of birds Imp can summon.
[ "2 12 0 4\n3 4\n4 2\n", "4 1000 10 35\n1 2 4 5\n1000 500 250 200\n", "2 10 7 11\n2 10\n6 1\n" ]
[ "6\n", "5\n", "11\n" ]
In the first sample base amount of Imp's mana is equal to 12 (with maximum capacity also equal to 12). After he summons two birds from the first nest, he loses 8 mana points, although his maximum capacity will not increase (since *B* = 0). After this step his mana will be 4 of 12; during the move you will replenish 4 mana points, and hence own 8 mana out of 12 possible. Now it's optimal to take 4 birds from the second nest and spend 8 mana. The final answer will be — 6. In the second sample the base amount of mana is equal to 1000. The right choice will be to simply pick all birds from the last nest. Note that Imp's mana doesn't restore while moving because it's initially full.
[ { "input": "2 12 0 4\n3 4\n4 2", "output": "6" }, { "input": "4 1000 10 35\n1 2 4 5\n1000 500 250 200", "output": "5" }, { "input": "2 10 7 11\n2 10\n6 1", "output": "11" }, { "input": "5 1 4 6\n3 4 6 5 1\n3 0 10 2 9", "output": "10" }, { "input": "75 262 870 596\...
1,000
90,214,400
0
45,581
743
Vladik and cards
[ "binary search", "bitmasks", "brute force", "dp" ]
null
null
Vladik was bored on his way home and decided to play the following game. He took *n* cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: - the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are *c**k* cards with number *k* on them in the subsequence, than for all pairs of integers the condition |*c**i*<=-<=*c**j*|<=≤<=1 must hold. - if there is at least one card with number *x* on it in the subsequence, then all cards with number *x* in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1,<=1,<=2,<=2] satisfies this condition while the subsequence [1,<=2,<=2,<=1] doesn't. Note that [1,<=1,<=2,<=2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.
The first line contains single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of cards in Vladik's sequence. The second line contains the sequence of *n* positive integers not exceeding 8 — the description of Vladik's sequence.
Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.
[ "3\n1 1 1\n", "8\n8 7 6 5 4 3 2 1\n", "24\n1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8\n" ]
[ "1", "8", "17" ]
In the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.
[ { "input": "3\n1 1 1", "output": "1" }, { "input": "8\n8 7 6 5 4 3 2 1", "output": "8" }, { "input": "24\n1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8", "output": "17" }, { "input": "1\n8", "output": "1" }, { "input": "2\n5 4", "output": "2" }, { "i...
46
0
0
45,588
177
Party
[ "dfs and similar", "dsu", "graphs" ]
null
null
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings. More formally, for each invited person the following conditions should be fulfilled: - all his friends should also be invited to the party; - the party shouldn't have any people he dislikes; - all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people *a*1 and *a**p* are connected through a chain of common friends if there exists a sequence of people *a*2,<=*a*3,<=...,<=*a**p*<=-<=1 such that all pairs of people *a**i* and *a**i*<=+<=1 (1<=≤<=*i*<=&lt;<=*p*) are friends. Help the Beaver find the maximum number of acquaintances he can invite.
The first line of input contains an integer *n* — the number of the Beaver's acquaintances. The second line contains an integer *k* — the number of pairs of friends. Next *k* lines contain space-separated pairs of integers *u**i*,<=*v**i* — indices of people who form the *i*-th pair of friends. The next line contains an integer *m* — the number of pairs of people who dislike each other. Next *m* lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: - 2<=≤<=*n*<=≤<=14 The input limitations for getting 100 points are: - 2<=≤<=*n*<=≤<=2000
Output a single number — the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.
[ "9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9\n" ]
[ "3" ]
Let's have a look at the example. Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).
[ { "input": "9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9", "output": "3" }, { "input": "2\n1\n1 2\n0", "output": "2" }, { "input": "2\n0\n1\n1 2", "output": "1" }, { "input": "3\n2\n1 2\n1 3\n1\n2 3", "output": "0" }, { "input": "3\n3\n1 3\n2 1\n2 3\n...
92
307,200
3
45,598
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\...
310
1,331,200
3.92002
45,632
965
Short Code
[ "data structures", "dp", "greedy", "strings", "trees" ]
null
null
Arkady's code contains $n$ variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code. He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names. A string $a$ is a prefix of a string $b$ if you can delete some (possibly none) characters from the end of $b$ and obtain $a$. Please find this minimum possible total length of new names.
The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of variables. The next $n$ lines contain variable names, one per line. Each name is non-empty and contains only lowercase English letters. The total length of these strings is not greater than $10^5$. The variable names are distinct.
Print a single integer — the minimum possible total length of new variable names.
[ "3\ncodeforces\ncodehorses\ncode\n", "5\nabba\nabb\nab\naa\naacada\n", "3\ntelegram\ndigital\nresistance\n" ]
[ "6\n", "11\n", "3\n" ]
In the first example one of the best options is to shorten the names in the given order as "cod", "co", "c". In the second example we can shorten the last name to "aac" and the first name to "a" without changing the other names.
[ { "input": "3\ncodeforces\ncodehorses\ncode", "output": "6" }, { "input": "5\nabba\nabb\nab\naa\naacada", "output": "11" }, { "input": "3\ntelegram\ndigital\nresistance", "output": "3" }, { "input": "1\na", "output": "1" }, { "input": "10\naaaba\nbabba\nbbba\naaab...
30
0
0
45,676
405
Unusual Product
[ "implementation", "math" ]
null
null
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors *x* and *y* of size *n* is the sum of the products of the corresponding components of the vectors. The unusual square of an *n*<=×<=*n* square matrix *A* is defined as the sum of *n* dot products. The *i*-th of them is the dot product of the *i*-th row vector and the *i*-th column vector in the matrix *A*. Fortunately for Chris, he has to work only in *GF*(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix *A* is binary: each element of *A* is either 0 or 1. For example, consider the following matrix *A*: The unusual square of *A* is equal to (1·1<=+<=1·0<=+<=1·1)<=+<=(0·1<=+<=1·1<=+<=1·0)<=+<=(1·1<=+<=0·1<=+<=0·0)<==<=0<=+<=1<=+<=1<==<=0. However, there is much more to the homework. Chris has to process *q* queries; each query can be one of the following: 1. given a row index *i*, flip all the values in the *i*-th row in *A*; 1. given a column index *i*, flip all the values in the *i*-th column in *A*; 1. find the unusual square of *A*. To flip a bit value *w* means to change it to 1<=-<=*w*, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix *A*, output the answers for each query of the third type! Can you solve Chris's homework?
The first line of input contains an integer *n* (1<=≤<=*n*<=≤<=1000), the number of rows and the number of columns in the matrix *A*. The next *n* lines describe the matrix: the *i*-th line contains *n* space-separated bits and describes the *i*-th row of *A*. The *j*-th number of the *i*-th line *a**ij* (0<=≤<=*a**ij*<=≤<=1) is the element on the intersection of the *i*-th row and the *j*-th column of *A*. The next line of input contains an integer *q* (1<=≤<=*q*<=≤<=106), the number of queries. Each of the next *q* lines describes a single query, which can be one of the following: - 1 *i* — flip the values of the *i*-th row; - 2 *i* — flip the values of the *i*-th column; - 3 — output the unusual square of *A*. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Let the number of the 3rd type queries in the input be *m*. Output a single string *s* of length *m*, where the *i*-th symbol of *s* is the value of the unusual square of *A* for the *i*-th query of the 3rd type as it appears in the input.
[ "3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3\n" ]
[ "01001\n" ]
none
[ { "input": "3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3", "output": "01001" }, { "input": "1\n1\n9\n1 1\n3\n1 1\n1 1\n3\n1 1\n3\n1 1\n3", "output": "0010" }, { "input": "3\n1 0 1\n0 1 1\n1 0 1\n4\n3\n3\n3\n3", "output": "1111" }, { "input": "1...
389
63,078,400
3
45,718
926
Endless Roses Most Beautiful
[]
null
null
Arkady decided to buy roses for his girlfriend. A flower shop has white, orange and red roses, and the total amount of them is *n*. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color. Arkady wants to buy exactly *k* roses. For each rose in the shop he knows its beauty and color: the beauty of the *i*-th rose is *b**i*, and its color is *c**i* ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose). Compute the maximum possible total beauty of a bouquet of *k* roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=200<=000) — the number of roses in the show and the number of roses Arkady wants to buy. The second line contains a sequence of integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=10<=000), where *b**i* equals the beauty of the *i*-th rose. The third line contains a string *c* of length *n*, consisting of uppercase English letters 'W', 'O' and 'R', where *c**i* denotes the color of the *i*-th rose: 'W' denotes white, 'O'  — orange, 'R' — red.
Print the maximum possible total beauty of a bouquet of *k* roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
[ "5 3\n4 3 4 1 6\nRROWW\n", "5 2\n10 20 14 20 11\nRRRRR\n", "11 5\n5 6 3 2 3 4 7 5 4 5 6\nRWOORWORROW\n" ]
[ "11\n", "-1\n", "28\n" ]
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11. In the second example Arkady can not buy a bouquet because all roses have the same color.
[ { "input": "5 3\n4 3 4 1 6\nRROWW", "output": "11" }, { "input": "5 2\n10 20 14 20 11\nRRRRR", "output": "-1" }, { "input": "11 5\n5 6 3 2 3 4 7 5 4 5 6\nRWOORWORROW", "output": "28" }, { "input": "15 10\n8560 6244 9607 5137 7187 3217 5527 9919 282 8748 3529 6110 5767 521 339...
93
0
0
45,920
281
Nearest Fraction
[ "brute force", "implementation", "two pointers" ]
null
null
You are given three positive integers *x*,<=*y*,<=*n*. Your task is to find the nearest fraction to fraction whose denominator is no more than *n*. Formally, you should find such pair of integers *a*,<=*b* (1<=≤<=*b*<=≤<=*n*; 0<=≤<=*a*) that the value is as minimal as possible. If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.
A single line contains three integers *x*,<=*y*,<=*n* (1<=≤<=*x*,<=*y*,<=*n*<=≤<=105).
Print the required fraction in the format "*a*/*b*" (without quotes).
[ "3 7 6\n", "7 2 4\n" ]
[ "2/5\n", "7/2\n" ]
none
[]
154
1,536,000
0
45,957
87
Beautiful Road
[ "dfs and similar", "dp", "dsu", "graphs", "implementation", "sortings", "trees" ]
D. Beautiful Road
1
256
A long time ago in some country in Asia were civil wars. Each of *n* cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city. Road making was difficult, so the country had few roads, exactly *n*<=-<=1. Also you could reach any city from any other city going on those roads. Even during the war the Oriental people remain spiritually rich and appreciate the beauty of nature. And to keep the memory of this great crusade for the centuries to come, they planted one beautiful tree by the road on which the army spent most time. The Oriental people love nature, that's why if there were several such roads, then one tree was planted by each of them. Recently, when the records of the war were found, it became clear that each city attacked each other one exactly once. There were exactly *n*(*n*<=-<=1) attacks in total. Everyone has been wondering what road after those wars became the most beautiful, that is, by which road they planted the largest number of beautiful trees.
The first line contains an integer *n* (2<=≤<=*n*<=≤<=105), which represents the number of cities. Next *n*<=-<=1 lines contain three integers each: the numbers of cities *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*), connected by the *i*-th road and the number of days *d**i* the army spends to go on it (1<=≤<=*d**i*<=≤<=109). The lengths of several roads may coincide.
Print on the first line two integers — the number of beautiful trees on the most beautiful road and the number of the most beautiful roads. Print on the second line the list of the most beautiful roads in the sorted order by the numbers' increasing. The roads are numbered from 1 to *n*<=-<=1 in the order in which they are given in the input data. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator).
[ "2\n2 1 5\n", "6\n1 2 1\n1 3 5\n3 4 2\n3 5 3\n3 6 4\n" ]
[ "2 1\n1 \n", "16 1\n2 \n" ]
none
[ { "input": "2\n2 1 5", "output": "2 1\n1 " }, { "input": "6\n1 2 1\n1 3 5\n3 4 2\n3 5 3\n3 6 4", "output": "16 1\n2 " }, { "input": "10\n10 6 43981\n4 2 6730\n1 2 35174\n5 3 61951\n8 7 43981\n7 1 6730\n5 8 6730\n9 3 52479\n6 4 18138", "output": "32 1\n4 " }, { "input": "9\n6 ...
31
0
0
46,070
630
Challenge Pennants
[ "combinatorics", "math" ]
null
null
Because of budget cuts one IT company established new non-financial reward system instead of bonuses. Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table. Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought. In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table. One man can have several pennants of one type and of course he can have pennants of both types on his table. There are *n* tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.
The only line of the input contains one integer *n* (1<=≤<=*n*<=≤<=500) — the number of tables in the IT company.
Output one integer — the amount of ways to place the pennants on *n* tables.
[ "2\n" ]
[ "24" ]
none
[ { "input": "2", "output": "24" }, { "input": "1", "output": "1" }, { "input": "3", "output": "210" }, { "input": "4", "output": "1120" }, { "input": "5", "output": "4410" }, { "input": "6", "output": "14112" }, { "input": "7", "output":...
77
2,150,400
-1
46,209
370
Mittens
[ "constructive algorithms", "greedy", "sortings" ]
null
null
A Christmas party in city S. had *n* children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to *m*, and the children are numbered from 1 to *n*. Then the *i*-th child has both mittens of color *c**i*. The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children. The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.
The first line contains two integers *n* and *m* — the number of the children and the number of possible mitten colors (1<=≤<=*n*<=≤<=5000, 1<=≤<=*m*<=≤<=100). The second line contains *n* integers *c*1,<=*c*2,<=... *c**n*, where *c**i* is the color of the mittens of the *i*-th child (1<=≤<=*c**i*<=≤<=*m*).
In the first line, print the maximum number of children who can end up with a distinct-colored pair of mittens. In the next *n* lines print the way the mittens can be distributed in this case. On the *i*-th of these lines print two space-separated integers: the color of the left and the color of the right mitten the *i*-th child will get. If there are multiple solutions, you can print any of them.
[ "6 3\n1 3 2 2 1 1\n", "4 2\n1 2 1 1\n" ]
[ "6\n2 1\n1 2\n2 1\n1 3\n1 2\n3 1\n", "2\n1 2\n1 1\n2 1\n1 1\n" ]
none
[ { "input": "6 3\n1 3 2 2 1 1", "output": "6\n2 1\n1 2\n2 1\n1 3\n1 2\n3 1" }, { "input": "4 2\n1 2 1 1", "output": "2\n1 2\n1 1\n2 1\n1 1" }, { "input": "1 1\n1", "output": "0\n1 1" }, { "input": "4 1\n1 1 1 1", "output": "0\n1 1\n1 1\n1 1\n1 1" }, { "input": "2 2...
30
512,000
0
46,267
354
Vasya and Beautiful Arrays
[ "brute force", "dp", "number theory" ]
null
null
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers *a* of length *n*. Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array *a* left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by *k* for each number). The seller can obtain array *b* from array *a* if the following conditions hold: *b**i*<=&gt;<=0; 0<=≤<=*a**i*<=-<=*b**i*<=≤<=*k* for all 1<=≤<=*i*<=≤<=*n*. Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=3·105;<=1<=≤<=*k*<=≤<=106). The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — array *a*.
In the single line print a single number — the maximum possible beauty of the resulting array.
[ "6 1\n3 6 10 12 13 16\n", "5 3\n8 21 52 15 77\n" ]
[ "3\n", "7\n" ]
In the first sample we can obtain the array: 3 6 9 12 12 15 In the second sample we can obtain the next array: 7 21 49 14 77
[ { "input": "6 1\n3 6 10 12 13 16", "output": "3" }, { "input": "5 3\n8 21 52 15 77", "output": "7" }, { "input": "13 11\n55 16 26 40 84 80 48 52 25 43 75 21 58", "output": "16" }, { "input": "18 9\n85 29 29 15 17 71 46 69 48 80 44 73 40 55 61 57 22 68", "output": "13" }...
389
31,846,400
3
46,292
305
Playing with String
[ "games" ]
null
null
Two people play the following string game. Initially the players have got some string *s*. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. A player's move is the sequence of actions: 1. The player chooses one of the available pieces of paper with some string written on it. Let's denote it is *t*. Note that initially, only one piece of paper is available. 1. The player chooses in the string *t*<==<=*t*1*t*2... *t*|*t*| character in position *i* (1<=≤<=*i*<=≤<=|*t*|) such that for some positive integer *l* (0<=&lt;<=*i*<=-<=*l*; *i*<=+<=*l*<=≤<=|*t*|) the following equations hold: *t**i*<=-<=1<==<=*t**i*<=+<=1, *t**i*<=-<=2<==<=*t**i*<=+<=2, ..., *t**i*<=-<=*l*<==<=*t**i*<=+<=*l*. 1. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string *t*1*t*2... *t**i*<=-<=1, the second one will contain a string consisting of a single character *t**i*, the third one contains string *t**i*<=+<=1*t**i*<=+<=2... *t*|*t*|. Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.
The first line contains string *s* (1<=≤<=|*s*|<=≤<=5000). It is guaranteed that string *s* only contains lowercase English letters.
If the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move — integer *i* (1<=≤<=*i*<=≤<=|*s*|).
[ "abacaba\n", "abcde\n" ]
[ "First\n2\n", "Second\n" ]
In the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves.
[ { "input": "abacaba", "output": "First\n2" }, { "input": "abcde", "output": "Second" }, { "input": "aaaaa", "output": "First\n3" }, { "input": "aaabbbbbbbbabaaabbaabbbbabbabaabaabbbaabbbbbbabbbabaabaaabaaaabbaaabbbbaabbbaaabababbbbabbabbabaaaaabababbbaabbbaabababaaabababbaaaa...
0
0
-1
46,375
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...
93
2,969,600
-1
46,489
610
Harmony Analysis
[ "constructive algorithms" ]
null
null
The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or <=-<=1 and any two vectors are orthogonal. Just as a reminder, two vectors in *n*-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2*k* vectors in 2*k*-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?
The only line of the input contains a single integer *k* (0<=≤<=*k*<=≤<=9).
Print 2*k* lines consisting of 2*k* characters each. The *j*-th character of the *i*-th line must be equal to '<=*<=' if the *j*-th coordinate of the *i*-th vector is equal to <=-<=1, and must be equal to '<=+<=' if it's equal to <=+<=1. It's guaranteed that the answer always exists. If there are many correct answers, print any.
[ "2\n" ]
[ "++**\n+*+*\n++++\n+**+" ]
Consider all scalar products in example: - Vectors 1 and 2: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( + 1) + ( - 1)·( - 1) = 0 - Vectors 1 and 3: ( + 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) + ( - 1)·( + 1) = 0 - Vectors 1 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( - 1) + ( - 1)·( + 1) = 0 - Vectors 2 and 3: ( + 1)·( + 1) + ( - 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) = 0 - Vectors 2 and 4: ( + 1)·( + 1) + ( - 1)·( - 1) + ( + 1)·( - 1) + ( - 1)·( + 1) = 0 - Vectors 3 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( + 1)·( - 1) + ( + 1)·( + 1) = 0
[ { "input": "2", "output": "++++\n+*+*\n++**\n+**+" }, { "input": "1", "output": "++\n+*" }, { "input": "3", "output": "++++++++\n+*+*+*+*\n++**++**\n+**++**+\n++++****\n+*+**+*+\n++****++\n+**+*++*" }, { "input": "0", "output": "+" }, { "input": "4", "output":...
139
6,963,200
3
46,578
628
Bear and Fair Set
[ "flows", "graphs" ]
null
null
Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve. It's a well-known fact that Limak, as every bear, owns a set of numbers. You know some information about the set: - The elements of the set are distinct positive integers. - The number of elements in the set is *n*. The number *n* is divisible by 5. - All elements are between 1 and *b*, inclusive: bears don't know numbers greater than *b*. - For each *r* in {0,<=1,<=2,<=3,<=4}, the set contains exactly elements that give remainder *r* when divided by 5. (That is, there are elements divisible by 5, elements of the form 5*k*<=+<=1, elements of the form 5*k*<=+<=2, and so on.) Limak smiles mysteriously and gives you *q* hints about his set. The *i*-th hint is the following sentence: "If you only look at elements that are between 1 and *upTo**i*, inclusive, you will find exactly *quantity**i* such elements in my set." In a moment Limak will tell you the actual puzzle, but something doesn't seem right... That smile was very strange. You start to think about a possible reason. Maybe Limak cheated you? Or is he a fair grizzly bear? Given *n*, *b*, *q* and hints, check whether Limak can be fair, i.e. there exists at least one set satisfying the given conditions. If it's possible then print ''fair". Otherwise, print ''unfair".
The first line contains three integers *n*, *b* and *q* (5<=≤<=*n*<=≤<=*b*<=≤<=104, 1<=≤<=*q*<=≤<=104, *n* divisible by 5) — the size of the set, the upper limit for numbers in the set and the number of hints. The next *q* lines describe the hints. The *i*-th of them contains two integers *upTo**i* and *quantity**i* (1<=≤<=*upTo**i*<=≤<=*b*, 0<=≤<=*quantity**i*<=≤<=*n*).
Print ''fair" if there exists at least one set that has all the required properties and matches all the given hints. Otherwise, print ''unfair".
[ "10 20 1\n10 10\n", "10 20 3\n15 10\n5 0\n10 5\n", "10 20 2\n15 3\n20 10\n" ]
[ "fair\n", "fair\n", "unfair\n" ]
In the first example there is only one set satisfying all conditions: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}. In the second example also there is only one set satisfying all conditions: {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}. Easy to see that there is no set satisfying all conditions from the third example. So Limak lied to you :-(
[ { "input": "10 20 1\n10 10", "output": "fair" }, { "input": "10 20 3\n15 10\n5 0\n10 5", "output": "fair" }, { "input": "10 20 2\n15 3\n20 10", "output": "unfair" }, { "input": "15 27 2\n6 4\n23 5", "output": "unfair" }, { "input": "50 7654 4\n1273 11\n6327 38\n12...
233
9,011,200
3
46,809
379
New Year Letter
[ "bitmasks", "brute force", "dp" ]
null
null
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, *s*1 anf *s*2, consisting of uppercase English letters. Then the boy makes string *s**k*, using a recurrent equation *s**n*<==<=*s**n*<=-<=2<=+<=*s**n*<=-<=1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string *s**k* on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string *s**k* has exactly *x* occurrences of substring AC (the short-cut reminds him оf accepted problems). Besides, Vasya decided that string *s*1 should have length *n*, and string *s*2 should have length *m*. Vasya hasn't decided anything else. At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, *s*1 and *s*2 in the required manner. Help Vasya.
The first line contains four integers *k*,<=*x*,<=*n*,<=*m* (3<=≤<=*k*<=≤<=50; 0<=≤<=*x*<=≤<=109; 1<=≤<=*n*,<=*m*<=≤<=100).
In the first line print string *s*1, consisting of *n* uppercase English letters. In the second line print string *s*2, consisting of *m* uppercase English letters. If there are multiple valid strings, print any of them. If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
[ "3 2 2 2\n", "3 3 2 2\n", "3 0 2 2\n", "4 3 2 1\n", "4 2 2 1\n" ]
[ "AC\nAC\n", "Happy new year!\n", "AA\nAA\n", "Happy new year!\n", "Happy new year!\n" ]
none
[ { "input": "3 2 2 2", "output": "AC\nAC" }, { "input": "3 3 2 2", "output": "Happy new year!" }, { "input": "3 0 2 2", "output": "AA\nAA" }, { "input": "4 3 2 1", "output": "Happy new year!" }, { "input": "4 2 2 1", "output": "Happy new year!" }, { "in...
716
0
3
46,815
135
Zero-One
[ "constructive algorithms", "games", "greedy" ]
null
null
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him. Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it. An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.
Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).
[ "????\n", "1010\n", "1?1\n" ]
[ "00\n01\n10\n11\n", "10\n", "01\n11\n" ]
In the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes. In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end.
[ { "input": "????", "output": "00\n01\n10\n11" }, { "input": "1010", "output": "10" }, { "input": "1?1", "output": "01\n11" }, { "input": "111?", "output": "11" }, { "input": "000?", "output": "00" }, { "input": "1??1?", "output": "00\n01\n10\n11" ...
92
0
0
46,856
286
Lucky Permutation
[ "constructive algorithms", "math" ]
null
null
A permutation *p* of size *n* is the sequence *p*1,<=*p*2,<=...,<=*p**n*, consisting of *n* distinct integers, each of them is from 1 to *n* (1<=≤<=*p**i*<=≤<=*n*). A lucky permutation is such permutation *p*, that any integer *i* (1<=≤<=*i*<=≤<=*n*) meets this condition *p**p**i*<==<=*n*<=-<=*i*<=+<=1. You have integer *n*. Find some lucky permutation *p* of size *n*.
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the required permutation size.
Print "-1" (without the quotes) if the lucky permutation *p* of size *n* doesn't exist. Otherwise, print *n* distinct integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*) after a space — the required permutation. If there are multiple answers, you can print any of them.
[ "1\n", "2\n", "4\n", "5\n" ]
[ "1 \n", "-1\n", "2 4 1 3 \n", "2 5 3 1 4 \n" ]
none
[ { "input": "1", "output": "1 " }, { "input": "2", "output": "-1" }, { "input": "4", "output": "2 4 1 3 " }, { "input": "5", "output": "2 5 3 1 4 " }, { "input": "3", "output": "-1" }, { "input": "100000", "output": "2 100000 4 99998 6 99996 8 99994...
404
28,262,400
3
47,077
575
Party
[ "bitmasks", "brute force", "graph matchings" ]
null
null
Note the unusual memory limit for the problem. People working in MDCS (Microsoft Development Center Serbia) like partying. They usually go to night clubs on Friday and Saturday. There are *N* people working in MDCS and there are *N* clubs in the city. Unfortunately, if there is more than one Microsoft employee in night club, level of coolness goes infinitely high and party is over, so club owners will never let more than one Microsoft employee enter their club in the same week (just to be sure). You are organizing night life for Microsoft employees and you have statistics about how much every employee likes Friday and Saturday parties for all clubs. You need to match people with clubs maximizing overall sum of their happiness (they are happy as much as they like the club), while half of people should go clubbing on Friday and the other half on Saturday.
The first line contains integer *N* — number of employees in MDCS. Then an *N*<=×<=*N* matrix follows, where element in *i*-th row and *j*-th column is an integer number that represents how much *i*-th person likes *j*-th club’s Friday party. Then another *N*<=×<=*N* matrix follows, where element in *i*-th row and *j*-th column is an integer number that represents how much *i*-th person likes *j*-th club’s Saturday party. - 2<=≤<=*N*<=≤<=20 - *N* is even - 0<=≤<= level of likeness <=≤<=106 - All values are integers
Output should contain a single integer — maximum sum of happiness possible.
[ "4\n1 2 3 4\n2 3 4 1\n3 4 1 2\n4 1 2 3\n5 8 7 1\n6 9 81 3\n55 78 1 6\n1 1 1 1\n" ]
[ "167\n" ]
Here is how we matched people with clubs: Friday: 1st person with 4th club (4 happiness) and 4th person with 1st club (4 happiness). Saturday: 2nd person with 3rd club (81 happiness) and 3rd person with 2nd club (78 happiness). 4+4+81+78 = 167
[]
46
0
-1
47,114
383
Vowels
[ "combinatorics", "divide and conquer", "dp" ]
null
null
Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of *n* 3-words. A 3-word is a sequence of exactly 3 lowercase letters of the first 24 letters of the English alphabet (*a* to *x*). She decided that some of the letters are vowels, and all the others are consonants. The whole language is based on a simple rule: any word that contains at least one vowel is correct. Iahubina forgot which letters are the vowels, and wants to find some possible correct sets of vowels. She asks Iahub questions. In each question, she will give Iahub a set of letters considered vowels (in this question). For each question she wants to know how many words of the dictionary are correct, considering the given set of vowels. Iahubina wants to know the *xor* of the squared answers to all the possible questions. There are 224 different questions, they are all subsets of the set of the first 24 letters of the English alphabet. Help Iahub find that number.
The first line contains one integer, *n* (1<=≤<=*n*<=≤<=104). Each of the next *n* lines contains a 3-word consisting of 3 lowercase letters. There will be no two identical 3-words.
Print one number, the *xor* of the squared answers to the queries.
[ "5\nabc\naaa\nada\nbcd\ndef\n" ]
[ "0\n" ]
none
[ { "input": "5\nabc\naaa\nada\nbcd\ndef", "output": "0" }, { "input": "100\namd\namj\natr\nbcp\nbjm\ncna\ncpj\ncse\ndij\ndjp\ndlv\nebk\nedf\nelw\nfbr\nfcl\nfhs\nflo\nfmj\ngcg\ngen\nghg\ngvb\ngxx\nhbe\nhbf\nhgu\nhlv\nhqa\nibg\nifp\nima\nitt\nivl\nixu\njle\njli\nket\nkit\nkws\nlep\nles\nleu\nmbp\nmci\n...
46
0
0
47,115
1,009
Allowed Letters
[ "bitmasks", "flows", "graph matchings", "graphs", "greedy" ]
null
null
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup! Actually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent. In addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there. Finally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?) More formally, you are given a string consisting of lowercase Latin letters from "a" to "f". You can swap letters at any positions arbitrary number of times (zero swaps is also possible). What is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters? If Polycarp can't produce any valid name then print "Impossible".
The first line is the string $s$ ($1 \le |s| \le 10^5$) — the name Polycarp has came up with. The string consists only of lowercase Latin letters from "a" to "f". The second line contains a single integer $m$ ($0 \le m \le |s|$) — the number of investors. The $i$-th of the next $m$ lines contain an integer number $pos_i$ and a non-empty string of allowed characters for $pos_i$ ($1 \le pos_i \le |s|$). Each string contains pairwise distinct letters from "a" to "f". $pos_1, pos_2, \dots, pos_m$ are pairwise distinct. If any position of the string doesn't appear in the investors demands then any letter can go in this position.
If Polycarp can't produce any valid name then print "Impossible". Otherwise print the smallest lexicographically name Polycarp can obtain by swapping letters in string $s$ such that the letter at every position is among the allowed ones.
[ "bedefead\n5\n2 e\n1 dc\n5 b\n7 ef\n6 ef\n", "abacaba\n0\n", "fc\n2\n1 cfab\n2 f\n" ]
[ "deadbeef\n", "aaaabbc\n", "cf\n" ]
none
[ { "input": "bedefead\n5\n2 e\n1 dc\n5 b\n7 ef\n6 ef", "output": "deadbeef" }, { "input": "abacaba\n0", "output": "aaaabbc" }, { "input": "fc\n2\n1 cfab\n2 f", "output": "cf" }, { "input": "bbcbbc\n6\n1 c\n2 c\n3 b\n4 ab\n5 ab\n6 ab", "output": "ccbbbb" }, { "input...
233
10,137,600
3
47,118
171
Mysterious numbers - 2
[ "*special" ]
null
null
The only line of input contains three integers *a*1,<=*a*2,<=*a*3 (1<=≤<=*a*1,<=*a*2,<=*a*3<=≤<=20), separated by spaces. Output a single integer.
The only line of input contains three integers *a*1,<=*a*2,<=*a*3 (1<=≤<=*a*1,<=*a*2,<=*a*3<=≤<=20), separated by spaces.
Output a single integer.
[ "2 3 2\n", "13 14 1\n", "14 5 9\n", "17 18 3\n" ]
[ "5\n", "14\n", "464\n", "53\n" ]
none
[ { "input": "2 3 2", "output": "5" }, { "input": "13 14 1", "output": "14" }, { "input": "14 5 9", "output": "464" }, { "input": "17 18 3", "output": "53" }, { "input": "1 1 1", "output": "1" }, { "input": "4 6 7", "output": "110" }, { "inpu...
122
0
3
47,176
232
Fence
[ "binary search", "data structures", "string suffix structures" ]
null
null
John Doe has a crooked fence, consisting of *n* rectangular planks, lined up from the left to the right: the plank that goes *i*-th (1<=≤<=*i*<=≤<=*n*) (from left to right) has width 1 and height *h**i*. We will assume that the plank that goes *i*-th (1<=≤<=*i*<=≤<=*n*) (from left to right) has index *i*. A piece of the fence from *l* to *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) is a sequence of planks of wood with indices from *l* to *r* inclusive, that is, planks with indices *l*,<=*l*<=+<=1,<=...,<=*r*. The width of the piece of the fence from *l* to *r* is value *r*<=-<=*l*<=+<=1. Two pieces of the fence from *l*1 to *r*1 and from *l*2 to *r*2 are called matching, if the following conditions hold: - the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence; - the pieces are of the same width; - for all *i* (0<=≤<=*i*<=≤<=*r*1<=-<=*l*1) the following condition holds: *h**l*1<=+<=*i*<=+<=*h**l*2<=+<=*i*<==<=*h**l*1<=+<=*h**l*2. John chose a few pieces of the fence and now wants to know how many distinct matching pieces are for each of them. Two pieces of the fence are distinct if there is a plank, which belongs to one of them and does not belong to the other one.
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of wood planks in the fence. The second line contains *n* space-separated integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=109) — the heights of fence planks. The third line contains integer *q* (1<=≤<=*q*<=≤<=105) — the number of queries. Next *q* lines contain two space-separated integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*) — the boundaries of the *i*-th piece of the fence.
For each query on a single line print a single integer — the number of pieces of the fence that match the given one. Print the answers to the queries in the order, in which the queries are given in the input.
[ "10\n1 2 2 1 100 99 99 100 100 100\n6\n1 4\n1 2\n3 4\n1 5\n9 10\n10 10\n" ]
[ "1\n2\n2\n0\n2\n9\n" ]
none
[]
46
0
0
47,181
0
none
[ "none" ]
null
null
Programmer Vasya is studying a new programming language &amp;K*. The &amp;K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages. There is a very powerful system of pointers on &amp;K* — you can add an asterisk to the right of the existing type *X* — that will result in new type *X*<=*<=. That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of *X*, which is a pointer, you can add an ampersand — that will result in a type &amp;*X*, to which refers *X*. That is called a dereference operation. The &amp;K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof. - The operator "typedef *A* *B*" defines a new data type *B*, which is equivalent to *A*. *A* can have asterisks and ampersands, and *B* cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.- The operator "typeof *A*" returns type of *A*, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**. An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype*<==<=&amp;errtype<==<=errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype. Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change. Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &amp;*T*<=*<= is always equal to *T*. Note, that the operators are executed consecutively one by one. If we have two operators "typedef &amp;void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &amp;void* = void (see sample 2). Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of operators. Then follow *n* lines with operators. Each operator is of one of two types: either "typedef *A* *B*", or "typeof *A*". In the first case the *B* type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands. All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
[ "5\ntypedef void* ptv\ntypeof ptv\ntypedef &amp;&amp;ptv node\ntypeof node\ntypeof &amp;ptv\n", "17\ntypedef void* b\ntypedef b* c\ntypeof b\ntypeof c\ntypedef &amp;b b\ntypeof b\ntypeof c\ntypedef &amp;&amp;b* c\ntypeof c\ntypedef &amp;b* c\ntypeof c\ntypedef &amp;void b\ntypeof b\ntypedef b******* c\ntypeof c\n...
[ "void*\nerrtype\nvoid\n", "void*\nvoid**\nvoid\nvoid**\nerrtype\nvoid\nerrtype\nerrtype\nerrtype\n" ]
Let's look at the second sample. After the first two queries typedef the b type is equivalent to void*, and с — to void**. The next query typedef redefines b — it is now equal to &amp;b = &amp;void* = void. At that, the с type doesn't change. After that the с type is defined as &amp;&amp;b* = &amp;&amp;void* = &amp;void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &amp;void* = void. Then the b type is again redefined as &amp;void = errtype. Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &amp;void******* = void******. The same happens in the last typedef.
[ { "input": "5\ntypedef void* ptv\ntypeof ptv\ntypedef &&ptv node\ntypeof node\ntypeof &ptv", "output": "void*\nerrtype\nvoid" }, { "input": "17\ntypedef void* b\ntypedef b* c\ntypeof b\ntypeof c\ntypedef &b b\ntypeof b\ntypeof c\ntypedef &&b* c\ntypeof c\ntypedef &b* c\ntypeof c\ntypedef &void b\nty...
280
0
3
47,199
734
Anton and Digits
[ "brute force", "greedy", "implementation", "math" ]
null
null
Recently Anton found a box with digits in his room. There are *k*2 digits 2, *k*3 digits 3, *k*5 digits 5 and *k*6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit can be used no more than once, i.e. the composed integers should contain no more than *k*2 digits 2, *k*3 digits 3 and so on. Of course, unused digits are not counted in the sum.
The only line of the input contains four integers *k*2, *k*3, *k*5 and *k*6 — the number of digits 2, 3, 5 and 6 respectively (0<=≤<=*k*2,<=*k*3,<=*k*5,<=*k*6<=≤<=5·106).
Print one integer — maximum possible sum of Anton's favorite integers that can be composed using digits from the box.
[ "5 1 3 4\n", "1 1 1 1\n" ]
[ "800\n", "256\n" ]
In the first sample, there are five digits 2, one digit 3, three digits 5 and four digits 6. Anton can compose three integers 256 and one integer 32 to achieve the value 256 + 256 + 256 + 32 = 800. Note, that there is one unused integer 2 and one unused integer 6. They are not counted in the answer. In the second sample, the optimal answer is to create on integer 256, thus the answer is 256.
[ { "input": "5 1 3 4", "output": "800" }, { "input": "1 1 1 1", "output": "256" }, { "input": "10 2 1 5", "output": "320" }, { "input": "4 2 7 2", "output": "576" }, { "input": "489 292 127 263", "output": "41856" }, { "input": "9557 5242 1190 7734", ...
46
0
3
47,279
82
General Mobilization
[ "data structures", "dfs and similar", "sortings" ]
C. General Mobilization
2
256
The Berland Kingdom is a set of *n* cities connected with each other with *n*<=-<=1 railways. Each road connects exactly two different cities. The capital is located in city 1. For each city there is a way to get from there to the capital by rail. In the *i*-th city there is a soldier division number *i*, each division is characterized by a number of *a**i*. It represents the priority, the smaller the number, the higher the priority of this division. All values of *a**i* are different. One day the Berland King Berl Great declared a general mobilization, and for that, each division should arrive in the capital. Every day from every city except the capital a train departs. So there are exactly *n*<=-<=1 departing trains each day. Each train moves toward the capital and finishes movement on the opposite endpoint of the railway on the next day. It has some finite capacity of *c**j*, expressed in the maximum number of divisions, which this train can transport in one go. Each train moves in the direction of reducing the distance to the capital. So each train passes exactly one railway moving from a city to the neighboring (where it stops) toward the capital. In the first place among the divisions that are in the city, division with the smallest number of *a**i* get on the train, then with the next smallest and so on, until either the train is full or all the divisions are be loaded. So it is possible for a division to stay in a city for a several days. The duration of train's progress from one city to another is always equal to 1 day. All divisions start moving at the same time and end up in the capital, from where they don't go anywhere else any more. Each division moves along a simple path from its city to the capital, regardless of how much time this journey will take. Your goal is to find for each division, in how many days it will arrive to the capital of Berland. The countdown begins from day 0.
The first line contains the single integer *n* (1<=≤<=*n*<=≤<=5000). It is the number of cities in Berland. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* represents the priority of the division, located in the city number *i*. All numbers *a*1,<=*a*2,<=...,<=*a**n* are different (1<=≤<=*a**i*<=≤<=109). Then *n*<=-<=1 lines contain the descriptions of the railway roads. Each description consists of three integers *v**j*,<=*u**j*,<=*c**j*, where *v**j*, *u**j* are number of cities connected by the *j*-th rail, and *c**j* stands for the maximum capacity of a train riding on this road (1<=≤<=*v**j*,<=*u**j*<=≤<=*n*,<=*v**j*<=≠<=*u**j*, 1<=≤<=*c**j*<=≤<=*n*).
Print sequence *t*1,<=*t*2,<=...,<=*t**n*, where *t**i* stands for the number of days it takes for the division of city *i* to arrive to the capital. Separate numbers with spaces.
[ "4\n40 10 30 20\n1 2 1\n2 3 1\n4 2 1\n", "5\n5 4 3 2 1\n1 2 1\n2 3 1\n2 4 1\n4 5 1\n" ]
[ "0 1 3 2 ", "0 1 4 2 3 " ]
none
[]
2,000
15,257,600
0
47,347
39
Tram
[]
I. Tram
2
64
In a Berland city S*** there is a tram engine house and only one tram. Three people work in the house — the tram driver, the conductor and the head of the engine house. The tram used to leave the engine house every morning and drove along his loop route. The tram needed exactly *c* minutes to complete the route. The head of the engine house controlled the tram’s movement, going outside every *c* minutes when the tram drove by the engine house, and the head left the driver without a bonus if he was even one second late. It used to be so. Afterwards the Berland Federal Budget gave money to make more tramlines in S***, and, as it sometimes happens, the means were used as it was planned. The tramlines were rebuilt and as a result they turned into a huge network. The previous loop route may have been destroyed. S*** has *n* crossroads and now *m* tramlines that links the pairs of crossroads. The traffic in Berland is one way so the tram can move along each tramline only in one direction. There may be several tramlines between two crossroads, which go same way or opposite ways. Every tramline links two different crossroads and for each crossroad there is at least one outgoing tramline. So, the tramlines were built but for some reason nobody gave a thought to increasing the number of trams in S***! The tram continued to ride alone but now the driver had an excellent opportunity to get rid of the unending control of the engine house head. For now due to the tramline network he could choose the route freely! Now at every crossroad the driver can arbitrarily choose the way he can go. The tram may even go to the parts of S*** from where it cannot return due to one way traffic. The driver is not afraid of the challenge: at night, when the city is asleep, he can return to the engine house safely, driving along the tramlines in the opposite direction. The city people were rejoicing for some of the had been waiting for the tram to appear on their streets for several years. However, the driver’s behavior enraged the engine house head. Now he tries to carry out an insidious plan of installing cameras to look after the rebellious tram. The plan goes as follows. The head of the engine house wants to install cameras at some crossroads, to choose a period of time *t* and every *t* minutes turn away from the favourite TV show to check where the tram is. Also the head of the engine house wants at all moments of time, divisible by *t*, and only at such moments the tram to appear on a crossroad under a camera. There must be a camera on the crossroad by the engine house to prevent possible terrorist attacks on the engine house head. Among all the possible plans the engine house head chooses the plan with the largest possible value of *t* (as he hates being distracted from his favourite TV show but he has to). If such a plan is not unique, pick the plan that requires the minimal possible number of cameras. Find such a plan.
The first line contains integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=105) — the number of crossroads and tramlines in S*** respectively. The next *m* lines contain the descriptions of the tramlines in "*u* *v*" format, where *u* is the initial tramline crossroad and *v* is its final crossroad. The crossroads are numbered with integers from 1 to *n*, and the engine house is at the crossroad number 1.
In the first line output the value of *t*. In the next line output the value of *k* — the required number of the cameras. In the next line output space-separated numbers of the crossroads, where the cameras should be installed. Output the numbers in increasing order.
[ "4 5\n1 2\n2 3\n3 4\n4 1\n1 4\n" ]
[ "2\n2\n1 3\n" ]
none
[]
62
0
0
47,666
359
Pair of Numbers
[ "binary search", "brute force", "data structures", "math", "two pointers" ]
null
null
Simon has an array *a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* positive integers. Today Simon asked you to find a pair of integers *l*,<=*r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), such that the following conditions hold: 1. there is integer *j* (*l*<=≤<=*j*<=≤<=*r*), such that all integers *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r* are divisible by *a**j*; 1. value *r*<=-<=*l* takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (*l*,<=*r*). If there are multiple required pairs find all of them.
The first line contains integer *n* (1<=≤<=*n*<=≤<=3·105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106).
Print two integers in the first line — the number of required pairs and the maximum value of *r*<=-<=*l*. On the following line print all *l* values from optimal pairs in increasing order.
[ "5\n4 6 9 3 6\n", "5\n1 3 5 7 9\n", "5\n2 3 5 7 11\n" ]
[ "1 3\n2 \n", "1 4\n1 \n", "5 0\n1 2 3 4 5 \n" ]
In the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3. In the second sample all numbers are divisible by number 1. In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).
[ { "input": "5\n4 6 9 3 6", "output": "1 3\n2 " }, { "input": "5\n1 3 5 7 9", "output": "1 4\n1 " }, { "input": "5\n2 3 5 7 11", "output": "5 0\n1 2 3 4 5 " }, { "input": "1\n1343", "output": "1 0\n1 " }, { "input": "1\n1000000", "output": "1 0\n1 " }, { ...
794
63,385,600
3
47,848
346
Doodle Jump
[ "math", "number theory" ]
null
null
In Doodle Jump the aim is to guide a four-legged creature called "The Doodler" up a never-ending series of platforms without falling. — Wikipedia. It is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't reach due to the limits of its jumping ability. Consider the following problem. There are *n* platforms. The height of the *x*-th (1<=≤<=*x*<=≤<=*n*) platform is *a*·*x* mod *p*, where *a* and *p* are positive co-prime integers. The maximum possible height of a Doodler's jump is *h*. That is, it can jump from height *h*1 to height *h*2 (*h*1<=&lt;<=*h*2) if *h*2<=-<=*h*1<=≤<=*h*. Initially, the Doodler is on the ground, the height of which is 0. The question is whether it can reach the highest platform or not. For example, when *a*<==<=7, *n*<==<=4, *p*<==<=12, *h*<==<=2, the heights of the platforms are 7, 2, 9, 4 as in the picture below. With the first jump the Doodler can jump to the platform at height 2, with the second one the Doodler can jump to the platform at height 4, but then it can't jump to any of the higher platforms. So, it can't reach the highest platform. User xiaodao thought about the problem for a long time but didn't solve it, so she asks you for help. Also, she has a lot of instances of the problem. Your task is solve all of these instances.
The first line contains an integer *t* (1<=≤<=*t*<=≤<=104) — the number of problem instances. Each of the next *t* lines contains four integers *a*, *n*, *p* and *h* (1<=≤<=*a*<=≤<=109, 1<=≤<=*n*<=&lt;<=*p*<=≤<=109, 0<=≤<=*h*<=≤<=109). It's guaranteed that *a* and *p* are co-prime.
For each problem instance, if the Doodler can reach the highest platform, output "YES", otherwise output "NO".
[ "3\n7 4 12 2\n7 1 9 4\n7 4 12 3\n" ]
[ "NO\nNO\nYES\n" ]
none
[]
343
0
0
47,919
815
Karen and Supermarket
[ "brute force", "dp", "trees" ]
null
null
On the way home, Karen decided to stop by the supermarket to buy some groceries. She needs to buy a lot of goods, but since she is a student her budget is still quite limited. In fact, she can only spend up to *b* dollars. The supermarket sells *n* goods. The *i*-th good can be bought for *c**i* dollars. Of course, each good can only be bought once. Lately, the supermarket has been trying to increase its business. Karen, being a loyal customer, was given *n* coupons. If Karen purchases the *i*-th good, she can use the *i*-th coupon to decrease its price by *d**i*. Of course, a coupon cannot be used without buying the corresponding good. There is, however, a constraint with the coupons. For all *i*<=≥<=2, in order to use the *i*-th coupon, Karen must also use the *x**i*-th coupon (which may mean using even more coupons to satisfy the requirement for that coupon). Karen wants to know the following. What is the maximum number of goods she can buy, without exceeding her budget *b*?
The first line of input contains two integers *n* and *b* (1<=≤<=*n*<=≤<=5000, 1<=≤<=*b*<=≤<=109), the number of goods in the store and the amount of money Karen has, respectively. The next *n* lines describe the items. Specifically: - The *i*-th line among these starts with two integers, *c**i* and *d**i* (1<=≤<=*d**i*<=&lt;<=*c**i*<=≤<=109), the price of the *i*-th good and the discount when using the coupon for the *i*-th good, respectively. - If *i*<=≥<=2, this is followed by another integer, *x**i* (1<=≤<=*x**i*<=&lt;<=*i*), denoting that the *x**i*-th coupon must also be used before this coupon can be used.
Output a single integer on a line by itself, the number of different goods Karen can buy, without exceeding her budget.
[ "6 16\n10 9\n10 5 1\n12 2 1\n20 18 3\n10 2 3\n2 1 5\n", "5 10\n3 1\n3 1 1\n3 1 2\n3 1 3\n3 1 4\n" ]
[ "4\n", "5\n" ]
In the first test case, Karen can purchase the following 4 items: - Use the first coupon to buy the first item for 10 - 9 = 1 dollar. - Use the third coupon to buy the third item for 12 - 2 = 10 dollars. - Use the fourth coupon to buy the fourth item for 20 - 18 = 2 dollars. - Buy the sixth item for 2 dollars. The total cost of these goods is 15, which falls within her budget. Note, for example, that she cannot use the coupon on the sixth item, because then she should have also used the fifth coupon to buy the fifth item, which she did not do here. In the second test case, Karen has enough money to use all the coupons and purchase everything.
[ { "input": "6 16\n10 9\n10 5 1\n12 2 1\n20 18 3\n10 2 3\n2 1 5", "output": "4" }, { "input": "5 10\n3 1\n3 1 1\n3 1 2\n3 1 3\n3 1 4", "output": "5" }, { "input": "13 30\n6 4\n25 5 1\n7 1 2\n9 4 2\n10 2 1\n12 3 1\n5 2 3\n10 9 6\n2 1 1\n5 3 9\n10 2 10\n10 9 6\n3 2 11", "output": "9" ...
1,481
536,883,200
0
47,970
236
Easy Number Challenge
[ "implementation", "number theory" ]
null
null
Let's denote *d*(*n*) as the number of divisors of a positive integer *n*. You are given three integers *a*, *b* and *c*. Your task is to calculate the following sum: Find the sum modulo 1073741824 (230).
The first line contains three space-separated integers *a*, *b* and *c* (1<=≤<=*a*,<=*b*,<=*c*<=≤<=100).
Print a single integer — the required sum modulo 1073741824 (230).
[ "2 2 2\n", "5 6 7\n" ]
[ "20\n", "1520\n" ]
For the first example. - *d*(1·1·1) = *d*(1) = 1; - *d*(1·1·2) = *d*(2) = 2; - *d*(1·2·1) = *d*(2) = 2; - *d*(1·2·2) = *d*(4) = 3; - *d*(2·1·1) = *d*(2) = 2; - *d*(2·1·2) = *d*(4) = 3; - *d*(2·2·1) = *d*(4) = 3; - *d*(2·2·2) = *d*(8) = 4. So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20.
[ { "input": "2 2 2", "output": "20" }, { "input": "5 6 7", "output": "1520" }, { "input": "91 42 25", "output": "3076687" }, { "input": "38 47 5", "output": "160665" }, { "input": "82 29 45", "output": "3504808" }, { "input": "40 15 33", "output": "...
2,000
0
0
47,988
599
Spongebob and Squares
[ "brute force", "math" ]
null
null
Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly *x* distinct squares in the table consisting of *n* rows and *m* columns. For example, in a 3<=×<=5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3<=×<=5 table is 15<=+<=8<=+<=3<==<=26.
The first line of the input contains a single integer *x* (1<=≤<=*x*<=≤<=1018) — the number of squares inside the tables Spongebob is interested in.
First print a single integer *k* — the number of tables with exactly *x* distinct squares inside. Then print *k* pairs of integers describing the tables. Print the pairs in the order of increasing *n*, and in case of equality — in the order of increasing *m*.
[ "26\n", "2\n", "8\n" ]
[ "6\n1 26\n2 9\n3 5\n5 3\n9 2\n26 1\n", "2\n1 2\n2 1\n", "4\n1 8\n2 3\n3 2\n8 1\n" ]
In a 1 × 2 table there are 2 1 × 1 squares. So, 2 distinct squares in total. In a 2 × 3 table there are 6 1 × 1 squares and 2 2 × 2 squares. That is equal to 8 squares in total.
[ { "input": "26", "output": "6\n1 26\n2 9\n3 5\n5 3\n9 2\n26 1" }, { "input": "2", "output": "2\n1 2\n2 1" }, { "input": "8", "output": "4\n1 8\n2 3\n3 2\n8 1" }, { "input": "1", "output": "1\n1 1" }, { "input": "5005", "output": "12\n1 5005\n5 335\n6 240\n10 9...
140
0
0
48,013
177
Fibonacci Strings
[ "strings" ]
null
null
Fibonacci strings are defined as follows: - *f*1 = «a» - *f*2 = «b» - *f**n* = *f**n*<=-<=1 *f**n*<=-<=2, *n*<=&gt;<=2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and *m* strings *s**i*. For each string *s**i*, find the number of times it occurs in the given Fibonacci string as a substring.
The first line contains two space-separated integers *k* and *m* — the number of a Fibonacci string and the number of queries, correspondingly. Next *m* lines contain strings *s**i* that correspond to the queries. It is guaranteed that strings *s**i* aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: - 1<=≤<=*k*<=≤<=3000 - 1<=≤<=*m*<=≤<=3000 - The total length of strings *s**i* doesn't exceed 3000 The input limitations for getting 100 points are: - 1<=≤<=*k*<=≤<=1018 - 1<=≤<=*m*<=≤<=104 - The total length of strings *s**i* doesn't exceed 105 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.
For each string *s**i* print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109<=+<=7). Print the answers for the strings in the order in which they are given in the input.
[ "6 5\na\nb\nab\nba\naba\n" ]
[ "3\n5\n3\n3\n1\n" ]
none
[ { "input": "6 5\na\nb\nab\nba\naba", "output": "3\n5\n3\n3\n1" }, { "input": "10 10\nbb\nab\nba\naa\nbb\nab\nba\naa\nbb\nab", "output": "12\n21\n21\n0\n12\n21\n21\n0\n12\n21" }, { "input": "10 10\nbbb\nabb\nbab\naab\nbba\naba\nbaa\naaa\nbbb\nabb", "output": "0\n12\n21\n0\n12\n8\n0\n0...
62
0
0
48,026
452
Permutation
[ "data structures", "divide and conquer", "hashing" ]
null
null
You are given a permutation of numbers from 1 to *n*. Determine whether there's a pair of integers *a*,<=*b* (1<=≤<=*a*,<=*b*<=≤<=*n*; *a*<=≠<=*b*) such that the element (note, that it is usual division, not integer one) is between *a* and *b* in this permutation.
First line consists of a single integer *n* (1<=≤<=*n*<=≤<=300000) — the size of permutation. Second line contains *n* integers — the permutation itself.
Print "YES", if such a pair exists, "NO" otherwise (in both cases without quotes, the answer is case insensitive).
[ "4\n1 3 4 2\n", "5\n1 5 2 4 3\n" ]
[ "NO\n", "YES\n" ]
In the second example 2 is between 1 and 3. Additionally 4 is between 3 and 5.
[ { "input": "4\n1 3 4 2", "output": "NO" }, { "input": "5\n1 5 2 4 3", "output": "YES" }, { "input": "100\n17 41 19 23 46 16 10 31 82 12 77 32 11 71 83 25 98 18 34 59 13 73 80 65 37 22 6 2 24 5 94 42 51 63 52 92 97 26 93 38 36 87 64 70 14 43 68 85 33 44 74 89 56 1 69 88 20 49 48 21 84 90 ...
30
0
0
48,048
420
Online Meeting
[ "implementation" ]
null
null
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat. One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting. You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).
The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105) — the number of team participants and the number of messages. Each of the next *m* lines contains a message in the format: - '+ *id*': the record means that the person with number *id* (1<=≤<=*id*<=≤<=*n*) has logged on to the meeting. - '- *id*': the record means that the person with number *id* (1<=≤<=*id*<=≤<=*n*) has logged off from the meeting. Assume that all the people of the team are numbered from 1 to *n* and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.
In the first line print integer *k* (0<=≤<=*k*<=≤<=*n*) — how many people can be leaders. In the next line, print *k* integers in the increasing order — the numbers of the people who can be leaders. If the data is such that no member of the team can be a leader, print a single number 0.
[ "5 4\n+ 1\n+ 2\n- 2\n- 1\n", "3 2\n+ 1\n- 2\n", "2 4\n+ 1\n- 1\n+ 2\n- 2\n", "5 6\n+ 1\n- 1\n- 3\n+ 3\n+ 4\n- 4\n", "2 4\n+ 1\n- 2\n+ 2\n- 1\n" ]
[ "4\n1 3 4 5 ", "1\n3 ", "0\n", "3\n2 3 5 ", "0\n" ]
none
[ { "input": "5 4\n+ 1\n+ 2\n- 2\n- 1", "output": "4\n1 3 4 5 " }, { "input": "3 2\n+ 1\n- 2", "output": "1\n3 " }, { "input": "2 4\n+ 1\n- 1\n+ 2\n- 2", "output": "0" }, { "input": "5 6\n+ 1\n- 1\n- 3\n+ 3\n+ 4\n- 4", "output": "3\n2 3 5 " }, { "input": "2 4\n+ 1\n...
15
0
0
48,060
730
Car Repair Shop
[ "implementation" ]
null
null
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time. Polycarp is good at marketing, so he has already collected *n* requests from clients. The requests are numbered from 1 to *n* in order they came. The *i*-th request is characterized by two values: *s**i* — the day when a client wants to start the repair of his car, *d**i* — duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on. Polycarp is making schedule by processing requests in the order from the first to the *n*-th request. He schedules the *i*-th request as follows: - If the car repair shop is idle for *d**i* days starting from *s**i* (*s**i*,<=*s**i*<=+<=1,<=...,<=*s**i*<=+<=*d**i*<=-<=1), then these days are used to repair a car of the *i*-th client. - Otherwise, Polycarp finds the first day *x* (from 1 and further) that there are *d**i* subsequent days when no repair is scheduled starting from *x*. In other words he chooses the smallest positive *x* that all days *x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*d**i*<=-<=1 are not scheduled for repair of any car. So, the car of the *i*-th client will be repaired in the range [*x*,<=*x*<=+<=*d**i*<=-<=1]. It is possible that the day *x* when repair is scheduled to start will be less than *s**i*. Given *n* requests, you are asked to help Polycarp schedule all of them according to the rules above.
The first line contains integer *n* (1<=≤<=*n*<=≤<=200) — the number of requests from clients. The following *n* lines contain requests, one request per line. The *i*-th request is given as the pair of integers *s**i*,<=*d**i* (1<=≤<=*s**i*<=≤<=109, 1<=≤<=*d**i*<=≤<=5·106), where *s**i* is the preferred time to start repairing the *i*-th car, *d**i* is the number of days to repair the *i*-th car. The requests should be processed in the order they are given in the input.
Print *n* lines. The *i*-th line should contain two integers — the start day to repair the *i*-th car and the finish day to repair the *i*-th car.
[ "3\n9 2\n7 3\n2 4\n", "4\n1000000000 1000000\n1000000000 1000000\n100000000 1000000\n1000000000 1000000\n" ]
[ "9 10\n1 3\n4 7\n", "1000000000 1000999999\n1 1000000\n100000000 100999999\n1000001 2000000\n" ]
none
[ { "input": "3\n9 2\n7 3\n2 4", "output": "9 10\n1 3\n4 7" }, { "input": "4\n1000000000 1000000\n1000000000 1000000\n100000000 1000000\n1000000000 1000000", "output": "1000000000 1000999999\n1 1000000\n100000000 100999999\n1000001 2000000" }, { "input": "1\n1 1", "output": "1 1" }, ...
31
0
0
48,163
391
Word Folding
[ "brute force" ]
null
null
You will receive 5 points for solving this problem. Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using this operation, Manao converts the string into a structure that has one more level than there were fold operations performed. See the following examples for clarity. We will denote the positions of folds with '|' characters. For example, the word "ABRACADABRA" written as "AB|RACA|DAB|RA" indicates that it has been folded three times: first, between the leftmost pair of 'B' and 'R' letters; second, between 'A' and 'D'; and third, between the rightmost pair of 'B' and 'R' letters. Here are several examples of folded strings: One last example for "ABCD|EFGH|IJ|K": Manao noticed that each folded string can be viewed as several piles of letters. For instance, in the previous example, there are four piles, which can be read as "AHI", "BGJK", "CF", and "DE" from bottom to top. Manao wonders what is the highest pile of identical letters he can build using fold operations on a given word. Note that the pile should not contain gaps and should start at the bottom level. For example, in the rightmost of the four examples above, none of the piles would be considered valid since each of them has gaps, starts above the bottom level, or both.
The input will consist of one line containing a single string of *n* characters with 1<=≤<=*n*<=≤<=1000 and no spaces. All characters of the string will be uppercase letters. This problem doesn't have subproblems. You will get 5 points for the correct submission.
Print a single integer — the size of the largest pile composed of identical characters that can be seen in a valid result of folding operations on the given string.
[ "ABRACADABRA\n", "ABBBCBDB\n", "AB\n" ]
[ "3\n", "3\n", "1\n" ]
Consider the first example. Manao can create a pile of three 'A's using the folding "AB|RACAD|ABRA", which results in the following structure: In the second example, Manao can create a pile of three 'B's using the following folding: "AB|BB|CBDB". Another way for Manao to create a pile of three 'B's with "ABBBCBDB" is the following folding: "AB|B|BCBDB". In the third example, there are no folds performed and the string is just written in one line.
[ { "input": "ABRACADABRA", "output": "3" }, { "input": "ABBBCBDB", "output": "3" }, { "input": "AB", "output": "1" }, { "input": "ABBCDEFB", "output": "3" }, { "input": "THISISATEST", "output": "3" }, { "input": "Z", "output": "1" }, { "inpu...
62
0
3
48,204
139
Wallpaper
[ "implementation", "math" ]
null
null
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has *n* rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris chose *m* types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type. The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely. After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=500) — the number of rooms in Boris's apartment. Each of the next *n* lines contains three space-separated positive integers — the length, width and height of the walls in a given room in meters, respectively. The next line contains a positive integer *m* (1<=≤<=*m*<=≤<=500) — the number of available wallpaper types. Each of the following *m* lines contains three space-separated positive integers — the length and width in meters of a given wallpaper and the price of one roll, respectively. All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper.
Print a single number — the minimum total cost of the rolls.
[ "1\n5 5 3\n3\n10 1 100\n15 2 320\n3 19 500\n" ]
[ "640\n" ]
Note to the sample: The total length of the walls (the perimeter) of the room is 20 m. One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700. A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640. One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.
[ { "input": "1\n5 5 3\n3\n10 1 100\n15 2 320\n3 19 500", "output": "640" }, { "input": "1\n9 10 7\n1\n7 1 3", "output": "114" }, { "input": "1\n6 9 5\n3\n8 5 10\n8 5 2\n6 3 7", "output": "12" }, { "input": "1\n3 3 10\n3\n5 5 1\n9 9 2\n10 1 500", "output": "6000" }, { ...
92
0
-1
48,427
0
none
[ "none" ]
null
null
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are *n* bamboos in a row, and the *i*-th from the left is *a**i* meters high. Vladimir has just planted *n* bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing. Vladimir wants to check the bamboos each *d* days (i.e. *d* days after he planted, then after 2*d* days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than *k* meters. What is the maximum value *d* he can choose so that he can achieve what he wants without cutting off more than *k* meters of bamboo?
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1011) — the number of bamboos and the maximum total length of cut parts, in meters. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — the required heights of bamboos, in meters.
Print a single integer — the maximum value of *d* such that Vladimir can reach his goal.
[ "3 4\n1 3 5\n", "3 40\n10 30 50\n" ]
[ "3\n", "32\n" ]
In the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters.
[]
46
0
0
48,514
601
Lipshitz Sequence
[ "data structures", "math" ]
null
null
A function is called Lipschitz continuous if there is a real constant *K* such that the inequality |*f*(*x*)<=-<=*f*(*y*)|<=≤<=*K*·|*x*<=-<=*y*| holds for all . We'll deal with a more... discrete version of this term. For an array , we define it's Lipschitz constant as follows: - if *n*<=&lt;<=2, - if *n*<=≥<=2, over all 1<=≤<=*i*<=&lt;<=*j*<=≤<=*n* In other words, is the smallest non-negative integer such that |*h*[*i*]<=-<=*h*[*j*]|<=≤<=*L*·|*i*<=-<=*j*| holds for all 1<=≤<=*i*,<=*j*<=≤<=*n*. You are given an array of size *n* and *q* queries of the form [*l*,<=*r*]. For each query, consider the subarray ; determine the sum of Lipschitz constants of all subarrays of .
The first line of the input contains two space-separated integers *n* and *q* (2<=≤<=*n*<=≤<=100<=000 and 1<=≤<=*q*<=≤<=100) — the number of elements in array and the number of queries respectively. The second line contains *n* space-separated integers (). The following *q* lines describe queries. The *i*-th of those lines contains two space-separated integers *l**i* and *r**i* (1<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=*n*).
Print the answers to all queries in the order in which they are given in the input. For the *i*-th query, print one line containing a single integer — the sum of Lipschitz constants of all subarrays of .
[ "10 4\n1 5 2 9 1 3 4 2 1 7\n2 4\n3 8\n7 10\n1 9\n", "7 6\n5 7 7 4 6 6 2\n1 2\n2 3\n2 6\n1 7\n4 7\n3 5\n" ]
[ "17\n82\n23\n210\n", "2\n0\n22\n59\n16\n8\n" ]
In the first query of the first sample, the Lipschitz constants of subarrays of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ddadffaf9e222576b1abb771dcd83dbad588d7fe.png" style="max-width: 100.0%;max-height: 100.0%;"/> with length at least 2 are: - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/887651f76ac57b8f2b2dbd46c6ac2335ac2a270a.png" style="max-width: 100.0%;max-height: 100.0%;"/> - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e9eed4a49028e9bd234162d9da74fd4f86481378.png" style="max-width: 100.0%;max-height: 100.0%;"/> - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/16eff35d7bd22d3e34c55fc95cc6c59212d5b1c8.png" style="max-width: 100.0%;max-height: 100.0%;"/> The answer to the query is their sum.
[ { "input": "10 4\n1 5 2 9 1 3 4 2 1 7\n2 4\n3 8\n7 10\n1 9", "output": "17\n82\n23\n210" }, { "input": "7 6\n5 7 7 4 6 6 2\n1 2\n2 3\n2 6\n1 7\n4 7\n3 5", "output": "2\n0\n22\n59\n16\n8" }, { "input": "2 2\n0 0\n1 2\n1 2", "output": "0\n0" }, { "input": "2 2\n0 100000000\n1 2...
0
0
-1
48,542
56
Changing a String
[ "dp" ]
D. Changing a String
2
256
There is a string *s*, consisting of capital Latin letters. Let's denote its current length as |*s*|. During one move it is allowed to apply one of the following operations to it: - INSERT *pos* *ch* — insert a letter *ch* in the string *s* in the position *pos* (1<=≤<=*pos*<=≤<=|*s*|<=+<=1,<=*A*<=≤<=*ch*<=≤<=*Z*). The letter *ch* becomes the *pos*-th symbol of the string *s*, at that the letters shift aside and the length of the string increases by 1. - DELETE *pos* — delete a character number *pos* (1<=≤<=*pos*<=≤<=|*s*|) from the string *s*. At that the letters shift together and the length of the string decreases by 1. - REPLACE *pos* *ch* — the letter in the position *pos* of the line *s* is replaced by *ch* (1<=≤<=*pos*<=≤<=|*s*|,<=*A*<=≤<=*ch*<=≤<=*Z*). At that the length of the string does not change. Your task is to find in which minimal number of moves one can get a *t* string from an *s* string. You should also find the sequence of actions leading to the required results.
The first line contains *s*, the second line contains *t*. The lines consist only of capital Latin letters, their lengths are positive numbers from 1 to 1000.
In the first line print the number of moves *k* in the given sequence of operations. The number should be the minimal possible one. Then print *k* lines containing one operation each. Print the operations in the format, described above. If there are several solutions, print any of them.
[ "ABA\nABBBA\n", "ACCEPTED\nWRONGANSWER\n" ]
[ "2\nINSERT 3 B\nINSERT 4 B\n", "10\nREPLACE 1 W\nREPLACE 2 R\nREPLACE 3 O\nREPLACE 4 N\nREPLACE 5 G\nREPLACE 6 A\nINSERT 7 N\nINSERT 8 S\nINSERT 9 W\nREPLACE 11 R\n" ]
none
[ { "input": "ABA\nABBBA", "output": "2\nINSERT 3 B\nINSERT 4 B" }, { "input": "ACCEPTED\nWRONGANSWER", "output": "10\nREPLACE 1 W\nREPLACE 2 R\nREPLACE 3 O\nREPLACE 4 N\nREPLACE 5 G\nREPLACE 6 A\nINSERT 7 N\nINSERT 8 S\nINSERT 9 W\nREPLACE 11 R" }, { "input": "V\nBNBNE", "output": "5\...
60
102,400
0
48,552
0
none
[ "none" ]
null
null
Dreamoon has a string *s* and a pattern string *p*. He first removes exactly *x* characters from *s* obtaining string *s*' as a result. Then he calculates that is defined as the maximal number of non-overlapping substrings equal to *p* that can be found in *s*'. He wants to make this number as big as possible. More formally, let's define as maximum value of over all *s*' that can be obtained by removing exactly *x* characters from *s*. Dreamoon wants to know for all *x* from 0 to |*s*| where |*s*| denotes the length of string *s*.
The first line of the input contains the string *s* (1<=≤<=|*s*|<=≤<=2<=000). The second line of the input contains the string *p* (1<=≤<=|*p*|<=≤<=500). Both strings will only consist of lower case English letters.
Print |*s*|<=+<=1 space-separated integers in a single line representing the for all *x* from 0 to |*s*|.
[ "aaaaa\naa\n", "axbaxxb\nab\n" ]
[ "2 2 1 1 0 0\n", "0 1 1 2 1 1 0 0\n" ]
For the first sample, the corresponding optimal values of *s*' after removal 0 through |*s*| = 5 characters from *s* are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}. For the second sample, possible corresponding optimal values of *s*' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
[]
46
307,200
-1
48,559
50
Bombing
[ "binary search", "dp", "probabilities" ]
D. Bombing
2
256
The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used. The enemy has *N* strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least *K* important objects of the enemy. The bombing impact point is already determined and has coordinates of [*X*0; *Y*0]. The nuclear warhead is marked by the estimated impact radius *R*<=≥<=0. All the buildings that are located closer than *R* to the bombing epicentre will be destroyed. All the buildings that are located further than *R* from the epicentre, can also be deactivated with some degree of probability. Let's assume that *D* is the distance between a building and the epicentre. This building's deactivation probability *P*(*D*,<=*R*) is calculated according to the following formula: If the estimated impact radius of the warhead is equal to zero, then all the buildings located in the impact point will be completely demolished and all the rest of important objects will not be damaged. The commanding officers want the probability of failing the task to be no more than ε. Nuclear warheads are too expensive a luxury, that's why you have to minimise the estimated impact radius of the warhead.
The first line contains an integer *N* which represents the number of the enemy's objects (1<=≤<=*N*<=≤<=100). The second line contains two integers: *K* is the required number of deactivated objects, and ε is the maximally permitted probability of not completing the task, given in per mils (1<=≤<=*K*<=≤<=*N*, 1<=≤<=ε<=≤<=999). The third line contains *X*0 and *Y*0 which are the coordinates of the strike impact point. The next *N* lines contain two numbers *X**i* and *Y**i* each which are the coordinates of every strategically important object. All the coordinates are integer, their absolute values do not exceed 1000. Let us remind you that there are a thousand per mils in unity (number one). There can be several objects in one point.
Print the sought estimated impact radius of the warhead. The absolute or relative measure of the inaccuracy of your answer should not exceed 10<=-<=6.
[ "1\n1 500\n5 5\n1 2\n", "5\n3 100\n0 0\n3 4\n60 70\n100 100\n10 10\n5 12\n" ]
[ "3.84257761518762740\n", "13.45126176453737600\n" ]
none
[]
62
0
0
48,613
0
none
[ "none" ]
null
null
Drazil is a monkey. He lives in a circular park. There are *n* trees around the park. The distance between the *i*-th tree and (*i*<=+<=1)-st trees is *d**i*, the distance between the *n*-th tree and the first tree is *d**n*. The height of the *i*-th tree is *h**i*. Drazil starts each day with the morning run. The morning run consists of the following steps: - Drazil chooses two different trees - He starts with climbing up the first tree - Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it - Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees. If the two trees Drazil chooses are *x*-th and *y*-th, we can estimate the energy the morning run takes to him as 2(*h**x*<=+<=*h**y*)<=+<=*dist*(*x*,<=*y*). Since there are children on exactly one of two arcs connecting *x* and *y*, the distance *dist*(*x*,<=*y*) between trees *x* and *y* is uniquely defined. Now, you know that on the *i*-th day children play between *a**i*-th tree and *b**i*-th tree. More formally, if *a**i*<=≤<=*b**i*, children play around the trees with indices from range [*a**i*,<=*b**i*], otherwise they play around the trees with indices from . Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.
The first line contains two integer *n* and *m* (3<=≤<=*n*<=≤<=105, 1<=≤<=*m*<=≤<=105), denoting number of trees and number of days, respectively. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≤<=*d**i*<=≤<=109), the distances between consecutive trees. The third line contains *n* integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=109), the heights of trees. Each of following *m* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children.
For each day print the answer in a separate line.
[ "5 3\n2 2 2 2 2\n3 5 2 1 4\n1 3\n2 2\n4 5\n", "3 3\n5 1 4\n5 1 4\n3 3\n2 2\n1 1\n" ]
[ "12\n16\n18\n", "17\n22\n11\n" ]
none
[ { "input": "5 3\n2 2 2 2 2\n3 5 2 1 4\n1 3\n2 2\n4 5", "output": "12\n16\n18" }, { "input": "3 3\n5 1 4\n5 1 4\n3 3\n2 2\n1 1", "output": "17\n22\n11" }, { "input": "10 10\n8477 33103 38654 6582 27496 1106 15985 3644 29818 8849\n88745 72099 87767 85285 73517 94562 87214 63194 83791 77619...
30
0
0
48,755
119
Alternative Reality
[ "geometry" ]
null
null
In the year of 3000 travelling around parallel realities became a routine thing. However one has to take into consideration that travelling like that is highly dangerous as you never know beforehand where you're gonna get... Little Vasya, for instance, found himself in a gaming reality and now he has to successfully complete all levels of a very weird game to get back. The gaming reality is a three-dimensional space where *n* points are given. The game has *m* levels and at the beginning of the *i*-th level the player is positioned at some plane *Q**i* that passes through the origin. On each level Vasya has to use special robots to construct and activate *n* powerful energy spheres of the equal radius with centers at the given points. The player chooses the radius of the spheres himself. The player has to spend *R* units of money to construct spheres whose radius equals *R* (consequently, one can construct spheres whose radius equals zero for free). Besides, once for each level a player can choose any point in space and release a laser ray from there, perpendicular to plane *Q**i* (this action costs nothing). The ray can either be directed towards the plane or from the plane. The spheres that share at least one point with the ray will be immediately activated. The level is considered completed if the player has managed to activate all spheres. Note that the centers of the spheres are the same for all *m* levels but the spheres do not remain: the player should construct them anew on each new level. Help Vasya find out what minimum sum of money will be enough to complete each level.
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=900,<=1<=≤<=*m*<=≤<=100) — the number of energetic spheres and the number of levels in the game correspondingly. Each of the following *n* lines contains three integers *x**i*, *y**i*, *z**i* (0<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=104) — the coordinates of the center of the *i*-th sphere. Assume that these points do not change their positions throughout the game. Then follow *m* lines, each containing three integers *a**i*, *b**i*, *c**i* (0<=≤<=*a**i*,<=*b**i*,<=*c**i*<=≤<=100, *a**i*2<=+<=*b**i*2<=+<=*c**i*2<=&gt;<=0). These numbers are the coefficients in the equation of plane *Q**i* (*a**i**x*<=+<=*b**i**y*<=+<=*c**i**z*<==<=0), where the player is positioned at the beginning of the *i*-th level.
Print *m* numbers, one per line: the *i*-th line should contain the minimum sum of money needed to complete the *i*-th level. The absolute or relative error should not exceed 10<=-<=6.
[ "4 1\n0 0 0\n0 1 0\n1 0 0\n1 1 0\n0 0 1\n", "5 3\n0 1 0\n1 0 1\n1 2 1\n2 0 1\n1 3 0\n1 1 1\n1 2 3\n3 0 3\n", "2 1\n0 20 0\n0 0 0\n0 10 0\n" ]
[ "0.7071067812\n", "1.6329931619\n1.6366341768\n1.5411035007\n", "0.0000000000\n" ]
none
[]
60
0
0
48,758
690
Recover Polygon (easy)
[]
null
null
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good. Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle. As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides).
The first line of each test case contains one integer *N*, the size of the lattice grid (5<=≤<=*N*<=≤<=50). The next *N* lines each contain *N* characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4. Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of *y* coordinate, and in one row cells go in the order of increasing *x* coordinate. This means that the first row corresponds to cells with coordinates (1,<=*N*),<=...,<=(*N*,<=*N*) and the last row corresponds to cells with coordinates (1,<=1),<=...,<=(*N*,<=1).
The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.
[ "6\n000000\n000000\n012100\n024200\n012100\n000000\n" ]
[ "Yes\n" ]
The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (*x*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">1</sub>), (*x*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">2</sub>), (*x*<sub class="lower-index">2</sub>, *y*<sub class="lower-index">1</sub>), (*x*<sub class="lower-index">2</sub>, *y*<sub class="lower-index">2</sub>)), has a non-zero area and be contained inside of the grid (that is, 0 ≤ *x*<sub class="lower-index">1</sub> &lt; *x*<sub class="lower-index">2</sub> ≤ *N*, 0 ≤ *y*<sub class="lower-index">1</sub> &lt; *y*<sub class="lower-index">2</sub> ≤ *N*), and result in the levels of Zombie Contamination as reported in the input.
[ { "input": "6\n000000\n000000\n012100\n024200\n012100\n000000", "output": "Yes" }, { "input": "6\n000000\n012210\n024420\n012210\n000000\n000000", "output": "Yes" }, { "input": "6\n000100\n001210\n002420\n001210\n000000\n000000", "output": "No" }, { "input": "10\n0000000000\n...
93
7,065,600
0
48,783
280
Rectangle Puzzle
[ "geometry" ]
null
null
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the *Ox* axis, equals *w*, the length of the side that is parallel to the *Oy* axis, equals *h*. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α. Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.
The first line contains three integers *w*,<=*h*,<=α (1<=≤<=*w*,<=*h*<=≤<=106; 0<=≤<=α<=≤<=180). Angle α is given in degrees.
In a single line print a real number — the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10<=-<=6.
[ "1 1 45\n", "6 4 30\n" ]
[ "0.828427125\n", "19.668384925\n" ]
The second sample has been drawn on the picture above.
[ { "input": "1 1 45", "output": "0.828427125" }, { "input": "6 4 30", "output": "19.668384925" }, { "input": "100 100 0", "output": "10000.000000000" }, { "input": "100 100 30", "output": "8452.994616207" }, { "input": "303304 904227 3", "output": "262706079399...
154
0
3
48,977
908
New Year and Entity Enumeration
[ "bitmasks", "combinatorics", "dp", "math" ]
null
null
You are given an integer *m*. Let *M*<==<=2*m*<=-<=1. You are also given a set of *n* integers denoted as the set *T*. The integers will be provided in base 2 as *n* binary strings of length *m*. A set of integers *S* is called "good" if the following hold. 1. If , then . 1. If , then 1. 1. All elements of *S* are less than or equal to *M*. Here, and refer to the bitwise XOR and bitwise AND operators, respectively. Count the number of good sets *S*, modulo 109<=+<=7.
The first line will contain two integers *m* and *n* (1<=≤<=*m*<=≤<=1<=000, 1<=≤<=*n*<=≤<=*min*(2*m*,<=50)). The next *n* lines will contain the elements of *T*. Each line will contain exactly *m* zeros and ones. Elements of *T* will be distinct.
Print a single integer, the number of good sets modulo 109<=+<=7.
[ "5 3\n11010\n00101\n11000\n", "30 2\n010101010101010010101010101010\n110110110110110011011011011011\n" ]
[ "4\n", "860616440\n" ]
An example of a valid set *S* is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
[ { "input": "5 3\n11010\n00101\n11000", "output": "4" }, { "input": "30 2\n010101010101010010101010101010\n110110110110110011011011011011", "output": "860616440" }, { "input": "30 10\n001000000011000111000010010000\n000001100001010000000000000100\n000110100010100000000000101000\n110000010...
46
5,529,600
0
48,980
354
Transferring Pyramid
[ "dp" ]
null
null
Vasya and Petya are using an interesting data storing structure: a pyramid. The pyramid consists of *n* rows, the *i*-th row contains *i* cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to as shown on the picture below. An example of a pyramid at *n*<==<=5 is: This data structure can perform operations of two types: 1. Change the value of a specific cell. It is described by three integers: "*t* *i* *v*", where *t*<==<=1 (the type of operation), *i* — the number of the cell to change and *v* the value to assign to the cell. 1. Change the value of some subpyramid. The picture shows a highlighted subpyramid with the top in cell 5. It is described by *s*<=+<=2 numbers: "*t* *i* *v*1 *v*2 ... *v**s*", where *t*<==<=2, *i* — the number of the top cell of the pyramid, *s* — the size of the subpyramid (the number of cells it has), *v**j* — the value you should assign to the *j*-th cell of the subpyramid. Formally: a subpyramid with top at the *i*-th cell of the *k*-th row (the 5-th cell is the second cell of the third row) will contain cells from rows from *k* to *n*, the (*k*<=+<=*p*)-th row contains cells from the *i*-th to the (*i*<=+<=*p*)-th (0<=≤<=*p*<=≤<=*n*<=-<=*k*). Vasya and Petya had two identical pyramids. Vasya changed some cells in his pyramid and he now wants to send his changes to Petya. For that, he wants to find a sequence of operations at which Petya can repeat all Vasya's changes. Among all possible sequences, Vasya has to pick the minimum one (the one that contains the fewest numbers). You have a pyramid of *n* rows with *k* changed cells. Find the sequence of operations which result in each of the *k* changed cells being changed by at least one operation. Among all the possible sequences pick the one that contains the fewest numbers.
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=105). The next *k* lines contain the coordinates of the modified cells *r**i* and *c**i* (1<=≤<=*c**i*<=≤<=*r**i*<=≤<=*n*) — the row and the cell's number in the row. All cells are distinct.
Print a single number showing how many numbers the final sequence has.
[ "4 5\n3 1\n3 3\n4 1\n4 3\n4 4\n", "7 11\n2 2\n3 1\n4 3\n5 1\n5 2\n5 5\n6 4\n7 2\n7 3\n7 4\n7 5\n" ]
[ "10\n", "26\n" ]
One of the possible solutions of the first sample consists of two operations: 2 4 *v*<sub class="lower-index">4</sub> *v*<sub class="lower-index">7</sub> *v*<sub class="lower-index">8</sub> 2 6 *v*<sub class="lower-index">6</sub> *v*<sub class="lower-index">9</sub> *v*<sub class="lower-index">10</sub> The picture shows the changed cells color-highlighted. The subpyramid used by the first operation is highlighted blue and the subpyramid used by the first operation is highlighted yellow:
[ { "input": "4 5\n3 1\n3 3\n4 1\n4 3\n4 4", "output": "10" }, { "input": "7 11\n2 2\n3 1\n4 3\n5 1\n5 2\n5 5\n6 4\n7 2\n7 3\n7 4\n7 5", "output": "26" }, { "input": "2 3\n1 1\n2 1\n2 2", "output": "5" }, { "input": "10 15\n2 1\n3 2\n4 1\n4 2\n4 3\n5 5\n7 6\n7 7\n8 2\n8 6\n9 7\...
1,418
11,468,800
3
49,179
58
Trees
[ "brute force" ]
C. Trees
2
256
On Bertown's main street *n* trees are growing, the tree number *i* has the height of *a**i* meters (1<=≤<=*i*<=≤<=*n*). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the *n*-th one) should be equal to each other, the heights of the 2-nd and the (*n*<=-<=1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) which is the number of trees. The second line contains integers *a**i* (1<=≤<=*a**i*<=≤<=105) which are the heights of the trees.
Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.
[ "3\n2 2 2\n", "4\n1 2 2 1\n" ]
[ "1\n", "0\n" ]
none
[ { "input": "3\n2 2 2", "output": "1" }, { "input": "4\n1 2 2 1", "output": "0" }, { "input": "3\n61452 50974 73849", "output": "2" }, { "input": "4\n86002 1199 86003 86002", "output": "1" }, { "input": "5\n92605 92606 41969 98774 92605", "output": "2" }, {...
92
0
0
49,221
827
Rusty String
[ "fft", "math", "strings" ]
null
null
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length *n* and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written. Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter "V" or "K" on each unreadable position, which values can the period of the resulting string be equal to? A period of a string is such an integer *d* from 1 to the length of the string that if we put the string shifted by *d* positions to the right on itself, then all overlapping letters coincide. For example, 3 and 5 are periods of "VKKVK".
There are several (at least one) test cases in the input. The first line contains single integer — the number of test cases. There is an empty line before each test case. Each test case is described in two lines: the first line contains single integer *n* (1<=≤<=*n*<=≤<=5·105) — the length of the string, the second line contains the string of length *n*, consisting of letters "V", "K" and characters "?". The latter means the letter on its position is unreadable. It is guaranteed that the sum of lengths among all test cases doesn't exceed 5·105. For hacks you can only use tests with one test case.
For each test case print two lines. In the first line print the number of possible periods after we replace each unreadable letter with "V" or "K". In the next line print all these values in increasing order.
[ "3\n \n5\nV??VK\n \n6\n??????\n \n4\n?VK?\n" ]
[ "2\n3 5\n6\n1 2 3 4 5 6\n3\n2 3 4\n" ]
In the first test case from example we can obtain, for example, "VKKVK", which has periods 3 and 5. In the second test case we can obtain "VVVVVV" which has all periods from 1 to 6. In the third test case string "KVKV" has periods 2 and 4, and string "KVKK" has periods 3 and 4.
[]
3,000
139,571,200
0
49,290
78
Archer's Shot
[ "binary search", "geometry", "math", "two pointers" ]
D. Archer's Shot
2
256
A breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them. The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playing field. The field can be considered infinite. Let's take a look at the battle unit called an "Archer". Each archer has a parameter "shot range". It's a positive integer that determines the radius of the circle in which the archer can hit a target. The center of the circle coincides with the center of the cell in which the archer stays. A cell is considered to be under the archer’s fire if and only if all points of this cell, including border points are located inside the circle or on its border. The picture below shows the borders for shot ranges equal to 3, 4 and 5. The archer is depicted as *A*. Find the number of cells that are under fire for some archer.
The first and only line of input contains a single positive integer *k* — the archer's shot range (1<=≤<=*k*<=≤<=106).
Print the single number, the number of cells that are under fire. Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator).
[ "3\n", "4\n", "5\n" ]
[ "7", "13", "19" ]
none
[ { "input": "3", "output": "7" }, { "input": "4", "output": "13" }, { "input": "5", "output": "19" }, { "input": "9", "output": "85" }, { "input": "11", "output": "121" }, { "input": "51", "output": "3037" }, { "input": "101", "output": ...
109
0
-1
49,374
147
Smile House
[ "binary search", "graphs", "matrices" ]
null
null
A smile house is created to raise the mood. It has *n* rooms. Some of the rooms are connected by doors. For each two rooms (number *i* and *j*), which are connected by a door, Petya knows their value *c**ij* — the value which is being added to his mood when he moves from room *i* to room *j*. Petya wondered whether he can raise his mood infinitely, moving along some cycle? And if he can, then what minimum number of rooms he will need to visit during one period of a cycle?
The first line contains two positive integers *n* and *m* (), where *n* is the number of rooms, and *m* is the number of doors in the Smile House. Then follows the description of the doors: *m* lines each containing four integers *i*, *j*, *c**ij* и *c**ji* (1<=≤<=*i*,<=*j*<=≤<=*n*,<=*i*<=≠<=*j*,<=<=-<=104<=≤<=*c**ij*,<=*c**ji*<=≤<=104). It is guaranteed that no more than one door connects any two rooms. No door connects the room with itself.
Print the minimum number of rooms that one needs to visit during one traverse of the cycle that can raise mood infinitely. If such cycle does not exist, print number 0.
[ "4 4\n1 2 -10 3\n1 3 1 -10\n2 4 -10 -1\n3 4 0 -3\n" ]
[ "4\n" ]
Cycle is such a sequence of rooms *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ..., *a*<sub class="lower-index">*k*</sub>, that *a*<sub class="lower-index">1</sub> is connected with *a*<sub class="lower-index">2</sub>, *a*<sub class="lower-index">2</sub> is connected with *a*<sub class="lower-index">3</sub>, ..., *a*<sub class="lower-index">*k* - 1</sub> is connected with *a*<sub class="lower-index">*k*</sub>, *a*<sub class="lower-index">*k*</sub> is connected with *a*<sub class="lower-index">1</sub>. Some elements of the sequence can coincide, that is, the cycle should not necessarily be simple. The number of rooms in the cycle is considered as *k*, the sequence's length. Note that the minimum possible length equals two.
[]
3,000
307,200
0
49,395
986
Oppa Funcan Style Remastered
[ "graphs", "math", "number theory", "shortest paths" ]
null
null
Surely you have seen insane videos by South Korean rapper PSY, such as "Gangnam Style", "Gentleman" and "Daddy". You might also hear that PSY has been recording video "Oppa Funcan Style" two years ago (unfortunately we couldn't find it on the internet). We will remind you what this hit looked like (you can find original description [here](http://acm.timus.ru/problem.aspx?space=1&amp;num=2107&amp;locale=en)): On the ground there are $n$ platforms, which are numbered with integers from $1$ to $n$, on $i$-th platform there is a dancer with number $i$. Further, every second all the dancers standing on the platform with number $i$ jump to the platform with the number $f(i)$. The moving rule $f$ is selected in advance and is not changed throughout the clip. The duration of the clip was $k$ seconds and the rule $f$ was chosen in such a way that after $k$ seconds all dancers were in their initial positions (i.e. the $i$-th dancer stood on the platform with the number $i$). That allowed to loop the clip and collect even more likes. PSY knows that enhanced versions of old artworks become more and more popular every day. So he decided to release a remastered-version of his video. In his case "enhanced version" means even more insanity, so the number of platforms can be up to $10^{18}$! But the video director said that if some dancer stays on the same platform all the time, then the viewer will get bored and will turn off the video immediately. Therefore, for all $x$ from $1$ to $n$ $f(x) \neq x$ must hold. Big part of classic video's success was in that looping, so in the remastered version all dancers should return to their initial positions in the end of the clip as well. PSY hasn't decided on the exact number of platforms and video duration yet, so he asks you to check if there is a good rule $f$ for different options.
In the first line of input there is one integer $t$ ($1 \le t \le 10^{4}$) — the number of options for $n$ and $k$ to check. In the next $t$ lines the options are given: each option is described with two integers $n$ and $k$ ($1 \le n \le 10^{18}$, $1 \le k \le 10^{15}$) — the number of dancers and the duration in seconds. It is guaranteed that the number of different values of $k$ in one test is not greater than $50$.
Print $t$ lines. If the $i$-th option of the video is feasible, print "YES" (without quotes) in $i$-th line, otherwise print "NO" (without quotes).
[ "3\n7 7\n3 8\n5 6\n" ]
[ "YES\nNO\nYES\n" ]
none
[]
0
0
-1
49,449
394
Dominoes
[ "constructive algorithms", "greedy" ]
null
null
During the break, we decided to relax and play dominoes. Our box with Domino was empty, so we decided to borrow the teacher's dominoes. The teacher responded instantly at our request. He put *nm* dominoes on the table as an *n*<=×<=2*m* rectangle so that each of the *n* rows contained *m* dominoes arranged horizontally. Each half of each domino contained number (0 or 1). We were taken aback, and the teacher smiled and said: "Consider some arrangement of dominoes in an *n*<=×<=2*m* matrix. Let's count for each column of the matrix the sum of numbers in this column. Then among all such sums find the maximum one. Can you rearrange the dominoes in the matrix in such a way that the maximum sum will be minimum possible? Note that it is prohibited to change the orientation of the dominoes, they all need to stay horizontal, nevertheless dominoes are allowed to rotate by 180 degrees. As a reward I will give you all my dominoes". We got even more taken aback. And while we are wondering what was going on, help us make an optimal matrix of dominoes.
The first line contains integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=103). In the next lines there is a description of the teachers' matrix. Each of next *n* lines contains *m* dominoes. The description of one domino is two integers (0 or 1), written without a space — the digits on the left and right half of the domino.
Print the resulting matrix of dominoes in the format: *n* lines, each of them contains *m* space-separated dominoes. If there are multiple optimal solutions, print any of them.
[ "2 3\n01 11 00\n00 01 11\n", "4 1\n11\n10\n01\n00\n" ]
[ "11 11 10\n00 00 01\n", "11\n10\n01\n00\n" ]
Consider the answer for the first sample. There, the maximum sum among all columns equals 1 (the number of columns is 6, and not 3). Obviously, this maximum can't be less than 1, then such matrix is optimal. Note that the dominoes can be rotated by 180 degrees.
[ { "input": "2 3\n01 11 00\n00 01 11", "output": "11 11 10\n00 00 01" }, { "input": "4 1\n11\n10\n01\n00", "output": "11\n10\n01\n00" }, { "input": "1 1\n00", "output": "00" }, { "input": "1 1\n01", "output": "10" }, { "input": "1 1\n11", "output": "11" }, ...
358
614,400
3
49,560
380
Sereja and Prefixes
[ "binary search", "brute force" ]
null
null
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in *m* stages. Each time he either adds a new number to the end of the sequence or takes *l* first elements of the current sequence and adds them *c* times to the end. More formally, if we represent the current sequence as *a*1,<=*a*2,<=...,<=*a**n*, then after we apply the described operation, the sequence transforms into *a*1,<=*a*2,<=...,<=*a**n*[,<=*a*1,<=*a*2,<=...,<=*a**l*] (the block in the square brackets must be repeated *c* times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
The first line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of stages to build a sequence. Next *m* lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer *x**i* (1<=≤<=*x**i*<=≤<=105) — the number to add. Type 2 means copying a prefix of length *l**i* to the end *c**i* times, in this case the line further contains two integers *l**i*,<=*c**i* (1<=≤<=*l**i*<=≤<=105,<=1<=≤<=*c**i*<=≤<=104), *l**i* is the length of the prefix, *c**i* is the number of copyings. It is guaranteed that the length of prefix *l**i* is never larger than the current length of the sequence. The next line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Print the elements that Sereja is interested in, in the order in which their numbers occur in the input.
[ "6\n1 1\n1 2\n2 2 1\n1 3\n2 5 2\n1 4\n16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n" ]
[ "1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4\n" ]
none
[ { "input": "6\n1 1\n1 2\n2 2 1\n1 3\n2 5 2\n1 4\n16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", "output": "1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4" }, { "input": "2\n1 33085\n1 44638\n2\n1 2", "output": "33085 44638" }, { "input": "10\n1 57757\n1 45234\n1 80807\n1 38496\n1 27469\n1 42645\n1 72643\...
77
307,200
0
49,563
938
Max History
[ "combinatorics", "math" ]
null
null
You are given an array *a* of length *n*. We define *f**a* the following way: - Initially *f**a*<==<=0, *M*<==<=1; - for every 2<=≤<=*i*<=≤<=*n* if *a**M*<=&lt;<=*a**i* then we set *f**a*<==<=*f**a*<=+<=*a**M* and then set *M*<==<=*i*. Calculate the sum of *f**a* over all *n*! permutations of the array *a* modulo 109<=+<=7. Note: two elements are considered different if their indices differ, so for every array *a* there are exactly *n*! permutations.
The first line contains integer *n* (1<=≤<=*n*<=≤<=<=1 000 000) — the size of array *a*. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=<=*a**i*<=≤<=<=109).
Print the only integer, the sum of *f**a* over all *n*! permutations of the array *a* modulo 109<=+<=7.
[ "2\n1 3\n", "3\n1 1 2\n" ]
[ "1", "4" ]
For the second example all the permutations are: - *p* = [1, 2, 3] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [1, 3, 2] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [2, 1, 3] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [2, 3, 1] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [3, 1, 2] : *f*<sub class="lower-index">*a*</sub> is equal to 0; - *p* = [3, 2, 1] : *f*<sub class="lower-index">*a*</sub> is equal to 0. Where *p* is the array of the indices of initial array *a*. The sum of *f*<sub class="lower-index">*a*</sub> is equal to 4.
[ { "input": "2\n1 3", "output": "1" }, { "input": "3\n1 1 2", "output": "4" }, { "input": "6\n1 4 5 2 3 3", "output": "2928" }, { "input": "8\n8 7 5 4 6 6 6 6", "output": "351360" }, { "input": "8\n1 2 3 9 100 100 100 100", "output": "109296" }, { "inpu...
0
0
-1
49,874