problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
B. Unnatural Conditionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet s(x) be sum of digits in decimal representation of positive integer x. Given two integers n and m, find some positive integers a and b such that s(a) \ge n, s(b) \ge n, s(a + b) \le m. InputThe only line of input contain two integers n and m (1 \le n, m \le 1129).OutputPrint two lines, one for decimal representation of a and one for decimal representation of b. Both numbers must not contain leading zeros and must have length no more than 2230.ExamplesInput6 5Output6 7Input8 16Output35 53NoteIn the first sample, we have n = 6 and m = 5. One valid solution is a = 6, b = 7. Indeed, we have s(a) = 6 \ge n and s(b) = 7 \ge n, and also s(a + b) = s(13) = 4 \le m.
Input6 5
Output6 7
1 second
256 megabytes
['constructive algorithms', 'math', '*1200']
A. Find Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a table of size n \times m, initially fully white. Rows are numbered 1 through n from top to bottom, columns 1 through m from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.InputThe first line contains two integers n and m (1 \le n, m \le 115) — the number of rows and the number of columns in the table.The i-th of the next n lines contains a string of m characters s_{i1} s_{i2} \ldots s_{im} (s_{ij} is 'W' for white cells and 'B' for black cells), describing the i-th row of the table.OutputOutput two integers r and c (1 \le r \le n, 1 \le c \le m) separated by a space — the row and column numbers of the center of the black square.ExamplesInput5 6WWBBBWWWBBBWWWBBBWWWWWWWWWWWWWOutput2 4Input3 3WWWBWWWWWOutput2 1
Input5 6WWBBBWWWBBBWWWBBBWWWWWWWWWWWWW
Output2 4
1 second
256 megabytes
['implementation', '*800']
G. X-mouse in the Campustime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe campus has m rooms numbered from 0 to m - 1. Also the x-mouse lives in the campus. The x-mouse is not just a mouse: each second x-mouse moves from room i to the room i \cdot x \mod{m} (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the x-mouse is unknown.You are responsible to catch the x-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the x-mouse enters a trapped room, it immediately gets caught.And the only observation you made is \text{GCD} (x, m) = 1.InputThe only line contains two integers m and x (2 \le m \le 10^{14}, 1 \le x < m, \text{GCD} (x, m) = 1) — the number of rooms and the parameter of x-mouse. OutputPrint the only integer — minimum number of traps you need to install to catch the x-mouse.ExamplesInput4 3Output3Input5 2Output2NoteIn the first example you can, for example, put traps in rooms 0, 2, 3. If the x-mouse starts in one of this rooms it will be caught immediately. If x-mouse starts in the 1-st rooms then it will move to the room 3, where it will be caught.In the second example you can put one trap in room 0 and one trap in any other room since x-mouse will visit all rooms 1..m-1 if it will start in any of these rooms.
Input4 3
Output3
1.5 seconds
256 megabytes
['bitmasks', 'math', 'number theory', '*2600']
F. Session in BSUtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp studies in Berland State University. Soon he will have to take his exam. He has to pass exactly n exams.For the each exam i there are known two days: a_i — day of the first opportunity to pass the exam, b_i — day of the second opportunity to pass the exam (a_i < b_i). Polycarp can pass at most one exam during each day. For each exam Polycarp chooses by himself which day he will pass this exam. He has to pass all the n exams.Polycarp wants to pass all the exams as soon as possible. Print the minimum index of day by which Polycarp can pass all the n exams, or print -1 if he cannot pass all the exams at all.InputThe first line of the input contains one integer n (1 \le n \le 10^6) — the number of exams.The next n lines contain two integers each: a_i and b_i (1 \le a_i < b_i \le 10^9), where a_i is the number of day of the first passing the i-th exam and b_i is the number of day of the second passing the i-th exam.OutputIf Polycarp cannot pass all the n exams, print -1. Otherwise print the minimum index of day by which Polycarp can do that.ExamplesInput21 51 7Output5Input35 131 51 7Output7Input310 4040 8010 80Output80Input399 10099 10099 100Output-1
Input21 51 7
Output5
4 seconds
256 megabytes
['binary search', 'dfs and similar', 'dsu', 'graph matchings', 'graphs', '*2400']
E. Inverse Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a square board, consisting of n rows and n columns. Each tile in it should be colored either white or black.Let's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well.Let's call some coloring suitable if it is beautiful and there is no rectangle of the single color, consisting of at least k tiles.Your task is to count the number of suitable colorings of the board of the given size.Since the answer can be very large, print it modulo 998244353.InputA single line contains two integers n and k (1 \le n \le 500, 1 \le k \le n^2) — the number of rows and columns of the board and the maximum number of tiles inside the rectangle of the single color, respectively.OutputPrint a single integer — the number of suitable colorings of the board of the given size modulo 998244353.ExamplesInput1 1Output0Input2 3Output6Input49 1808Output359087121NoteBoard of size 1 \times 1 is either a single black tile or a single white tile. Both of them include a rectangle of a single color, consisting of 1 tile.Here are the beautiful colorings of a board of size 2 \times 2 that don't include rectangles of a single color, consisting of at least 3 tiles: The rest of beautiful colorings of a board of size 2 \times 2 are the following:
Input1 1
Output0
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2100']
D. Mouse Hunttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMedicine faculty of Berland State University has just finished their admission campaign. As usual, about 80\% of applicants are girls and majority of them are going to live in the university dormitory for the next 4 (hopefully) years.The dormitory consists of n rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number i costs c_i burles. Rooms are numbered from 1 to n.Mouse doesn't sit in place all the time, it constantly runs. If it is in room i in second t then it will run to room a_i in second t + 1 without visiting any other rooms inbetween (i = a_i means that mouse won't leave room i). It's second 0 in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from 1 to n at second 0.What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?InputThe first line contains as single integers n (1 \le n \le 2 \cdot 10^5) — the number of rooms in the dormitory.The second line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^4) — c_i is the cost of setting the trap in room number i.The third line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — a_i is the room the mouse will run to the next second after being in room i.OutputPrint a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.ExamplesInput51 2 3 2 101 3 4 3 3Output3Input41 10 2 102 4 2 2Output10Input71 1 1 1 1 1 12 2 2 3 6 7 6Output2NoteIn the first example it is enough to set mouse trap in rooms 1 and 4. If mouse starts in room 1 then it gets caught immideately. If mouse starts in any other room then it eventually comes to room 4.In the second example it is enough to set mouse trap in room 2. If mouse starts in room 2 then it gets caught immideately. If mouse starts in any other room then it runs to room 2 in second 1.Here are the paths of the mouse from different starts from the third example: 1 \rightarrow 2 \rightarrow 2 \rightarrow \dots; 2 \rightarrow 2 \rightarrow \dots; 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots; 4 \rightarrow 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots; 5 \rightarrow 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots; 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots; 7 \rightarrow 6 \rightarrow 7 \rightarrow \dots; So it's enough to set traps in rooms 2 and 6.
Input51 2 3 2 101 3 4 3 3
Output3
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*1700']
C. Minimum Value Rectangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n sticks of the given lengths.Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks.Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value \frac{P^2}{S} minimal possible. The value is taken without any rounding.If there are multiple answers, print any of them.Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately.InputThe first line contains a single integer T (T \ge 1) — the number of lists of sticks in the testcase.Then 2T lines follow — lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 \le n \le 10^6) — the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, \dots, a_n (1 \le a_j \le 10^4) — lengths of the sticks in the i-th list.It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle.The total number of sticks in all T lists doesn't exceed 10^6 in each testcase.OutputPrint T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value \frac{P^2}{S} of this rectangle is minimal possible. You can print these four lengths in arbitrary order.If there are multiple answers, print any of them.ExampleInput347 2 2 782 8 1 4 8 2 1 555 5 5 5 5Output2 7 7 22 2 1 15 5 5 5NoteThere is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 \cdot 7 = 14, perimeter is 2(2 + 7) = 18. \frac{18^2}{14} \approx 23.143.The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are \frac{6^2}{2} = 18, \frac{20^2}{16} = 25 and \frac{18^2}{8} = 40.5, respectively. The minimal one of them is the rectangle (1, 2).You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5).
Input347 2 2 782 8 1 4 8 2 1 555 5 5 5 5
Output2 7 7 22 2 1 15 5 5 5
2 seconds
256 megabytes
['greedy', '*1600']
B. Numbers on the Chessboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a chessboard of size n \times n. It is filled with numbers from 1 to n^2 in the following way: the first \lceil \frac{n^2}{2} \rceil numbers from 1 to \lceil \frac{n^2}{2} \rceil are written in the cells with even sum of coordinates from left to right from top to bottom. The rest n^2 - \lceil \frac{n^2}{2} \rceil numbers from \lceil \frac{n^2}{2} \rceil + 1 to n^2 are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation \lceil\frac{x}{y}\rceil means division x by y rounded up.For example, the left board on the following picture is the chessboard which is given for n=4 and the right board is the chessboard which is given for n=5. You are given q queries. The i-th query is described as a pair x_i, y_i. The answer to the i-th query is the number written in the cell x_i, y_i (x_i is the row, y_i is the column). Rows and columns are numbered from 1 to n.InputThe first line contains two integers n and q (1 \le n \le 10^9, 1 \le q \le 10^5) — the size of the board and the number of queries.The next q lines contain two integers each. The i-th line contains two integers x_i, y_i (1 \le x_i, y_i \le n) — description of the i-th query.OutputFor each query from 1 to q print the answer to this query. The answer to the i-th query is the number written in the cell x_i, y_i (x_i is the row, y_i is the column). Rows and columns are numbered from 1 to n. Queries are numbered from 1 to q in order of the input.ExamplesInput4 51 14 44 33 22 4Output1816134Input5 42 14 23 33 4Output169720NoteAnswers to the queries from examples are on the board in the picture from the problem statement.
Input4 51 14 44 33 22 4
Output1816134
1 second
256 megabytes
['implementation', 'math', '*1200']
A. Palindromic Twisttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n lowercase Latin letters. n is even.For each position i (1 \le i \le n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' \rightarrow 'd', 'o' \rightarrow 'p', 'd' \rightarrow 'e', 'e' \rightarrow 'd', 'f' \rightarrow 'e', 'o' \rightarrow 'p', 'r' \rightarrow 'q', 'c' \rightarrow 'b', 'e' \rightarrow 'f', 's' \rightarrow 't').String s is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not.Your goal is to check if it's possible to make string s a palindrome by applying the aforementioned changes to every position. Print "YES" if string s can be transformed to a palindrome and "NO" otherwise.Each testcase contains several strings, for each of them you are required to solve the problem separately.InputThe first line contains a single integer T (1 \le T \le 50) — the number of strings in a testcase.Then 2T lines follow — lines (2i - 1) and 2i of them describe the i-th string. The first line of the pair contains a single integer n (2 \le n \le 100, n is even) — the length of the corresponding string. The second line of the pair contains a string s, consisting of n lowercase Latin letters.OutputPrint T lines. The i-th line should contain the answer to the i-th string of the input. Print "YES" if it's possible to make the i-th string a palindrome by applying the aforementioned changes to every position. Print "NO" otherwise.ExampleInput56abccba2cf4adfa8abaazaba2mlOutputYESNOYESNONONoteThe first string of the example can be changed to "bcbbcb", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters.The second string can be changed to "be", "bg", "de", "dg", but none of these resulting strings are palindromes.The third string can be changed to "beeb" which is a palindrome.The fifth string can be changed to "lk", "lm", "nk", "nm", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings "ll" or "mm".
Input56abccba2cf4adfa8abaazaba2ml
OutputYESNOYESNONO
2 seconds
256 megabytes
['implementation', 'strings', '*1000']
G. Company Acquisitionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup.The following steps happen until there is exactly one active startup. The following sequence of steps takes exactly 1 day. Two distinct active startups A, B, are chosen uniformly at random. A fair coin is flipped, and with equal probability, A acquires B or B acquires A (i.e. if A acquires B, then that means B's state changes from active to acquired, and its starts following A). When a startup changes from active to acquired, all of its previously acquired startups become active. For example, the following scenario can happen: Let's say A, B are active startups. C, D, E are acquired startups under A, and F, G are acquired startups under B: Active startups are shown in red. If A acquires B, then the state will be A, F, G are active startups. C, D, E, B are acquired startups under A. F and G have no acquired startups: If instead, B acquires A, then the state will be B, C, D, E are active startups. F, G, A are acquired startups under B. C, D, E have no acquired startups: You are given the initial state of the startups. For each startup, you are told if it is either acquired or active. If it is acquired, you are also given the index of the active startup that it is following.You're now wondering, what is the expected number of days needed for this process to finish with exactly one active startup at the end.It can be shown the expected number of days can be written as a rational number P/Q, where P and Q are co-prime integers, and Q \not= 0 \pmod{10^9+7}. Return the value of P \cdot Q^{-1} modulo 10^9+7.InputThe first line contains a single integer n (2 \leq n \leq 500), the number of startups.The next line will contain n space-separated integers a_1, a_2, \ldots, a_n (a_i = -1 or 1 \leq a_i \leq n). If a_i = -1, then that means startup i is active. Otherwise, if 1 \leq a_i \leq n, then startup i is acquired, and it is currently following startup a_i. It is guaranteed if a_i \not= -1, then a_{a_i} =-1 (that is, all startups that are being followed are active).OutputPrint a single integer, the expected number of days needed for the process to end with exactly one active startup, modulo 10^9+7.ExamplesInput3-1 -1 -1Output3Input22 -1Output0Input403 3 -1 -1 4 4 -1 -1 -1 -1 -1 10 10 10 10 10 10 4 20 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 3 3 3 3 3 3 3 3Output755808950NoteIn the first sample, there are three active startups labeled 1, 2 and 3, and zero acquired startups. Here's an example of how one scenario can happen Startup 1 acquires startup 2 (This state can be represented by the array [-1, 1, -1]) Startup 3 acquires startup 1 (This state can be represented by the array [3, -1, -1]) Startup 2 acquires startup 3 (This state can be represented by the array [-1, -1, 2]). Startup 2 acquires startup 1 (This state can be represented by the array [2, -1, 2]). At this point, there is only one active startup, and this sequence of steps took 4 days. It can be shown the expected number of days is 3.For the second sample, there is only one active startup, so we need zero days.For the last sample, remember to take the answer modulo 10^9+7.
Input3-1 -1 -1
Output3
1 second
256 megabytes
['constructive algorithms', 'math', '*3200']
F. Disjoint Trianglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA point belongs to a triangle if it lies inside the triangle or on one of its sides. Two triangles are disjoint if there is no point on the plane that belongs to both triangles.You are given n points on the plane. No two points coincide and no three points are collinear.Find the number of different ways to choose two disjoint triangles with vertices in the given points. Two ways which differ only in order of triangles or in order of vertices inside triangles are considered equal.InputThe first line of the input contains an integer n (6 \le n \le 2000) – the number of points.Each of the next n lines contains two integers x_i and y_i (|x_i|, |y_i| \le 10^9) – the coordinates of a point.No two points coincide and no three points are collinear.OutputPrint one integer – the number of ways to choose two disjoint triangles.ExamplesInput61 12 24 64 57 25 3Output6Input70 -1000000000-5 -55 -5-5 05 0-2 22 2Output21NoteIn the first example there are six pairs of disjoint triangles, they are shown on the picture below. All other pairs of triangles are not disjoint, for example the following pair:
Input61 12 24 64 57 25 3
Output6
2 seconds
256 megabytes
['geometry', '*2700']
E. Colored Cubestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya passes all exams! Despite expectations, Vasya is not tired, moreover, he is ready for new challenges. However, he does not want to work too hard on difficult problems.Vasya remembered that he has a not-so-hard puzzle: m colored cubes are placed on a chessboard of size n \times n. The fact is that m \leq n and all cubes have distinct colors. Each cube occupies exactly one cell. Also, there is a designated cell for each cube on the board, the puzzle is to place each cube on its place. The cubes are fragile, so in one operation you only can move one cube onto one of four neighboring by side cells, if only it is empty. Vasya wants to be careful, so each operation takes exactly one second. Vasya used to train hard for VK Cup Final, so he can focus his attention on the puzzle for at most 3 hours, that is 10800 seconds. Help Vasya find such a sequence of operations that all cubes will be moved onto their designated places, and Vasya won't lose his attention.InputThe first line contains two integers n and m (1 \leq m \leq n \leq 50).Each of the next m lines contains two integers x_i, y_i (1 \leq x_i, y_i \leq n), the initial positions of the cubes.The next m lines describe the designated places for the cubes in the same format and order. It is guaranteed that all initial positions are distinct and all designated places are distinct, however, it is possible that some initial positions coincide with some final positions.OutputIn the first line print a single integer k (0 \le k \leq 10800) — the number of operations Vasya should make.In each of the next k lines you should describe one operation: print four integers x_1, y_1, x_2, y_2, where x_1, y_1 is the position of the cube Vasya should move, and x_2, y_2 is the new position of the cube. The cells x_1, y_1 and x_2, y_2 should have a common side, the cell x_2, y_2 should be empty before the operation.We can show that there always exists at least one solution. If there are multiple solutions, print any of them.ExamplesInput2 11 12 2Output21 1 1 21 2 2 2Input2 21 12 21 22 1Output22 2 2 11 1 1 2Input2 22 12 22 22 1Output42 1 1 12 2 2 11 1 1 21 2 2 2Input4 32 22 33 33 22 22 3Output92 2 1 21 2 1 12 3 2 23 3 2 32 2 1 21 1 2 12 1 3 13 1 3 21 2 2 2NoteIn the fourth example the printed sequence of movements (shown on the picture below) is valid, but not shortest. There is a solution in 3 operations.
Input2 11 12 2
Output21 1 1 21 2 2 2
1 second
256 megabytes
['constructive algorithms', 'implementation', 'matrices', '*2700']
D. Recovering BSTtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset. To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed 1.Help Dima construct such a binary search tree or determine that it's impossible. The definition and properties of a binary search tree can be found here.InputThe first line contains the number of vertices n (2 \le n \le 700).The second line features n distinct integers a_i (2 \le a_i \le 10^9) — the values of vertices in ascending order.OutputIf it is possible to reassemble the binary search tree, such that the greatest common divisor of any two vertices connected by the edge is greater than 1, print "Yes" (quotes for clarity).Otherwise, print "No" (quotes for clarity).ExamplesInput63 6 9 18 36 108OutputYesInput27 17OutputNoInput94 8 10 12 15 18 33 44 81OutputYesNoteThe picture below illustrates one of the possible trees for the first example. The picture below illustrates one of the possible trees for the third example.
Input63 6 9 18 36 108
OutputYes
1 second
256 megabytes
['brute force', 'dp', 'math', 'number theory', 'trees', '*2100']
C. Plasticine zebratime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIs there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras. Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now wants to select several consequent (contiguous) pieces of alternating colors to create a zebra. Let's call the number of selected pieces the length of the zebra.Before assembling the zebra Grisha can make the following operation 0 or more times. He splits the sequence in some place into two parts, then reverses each of them and sticks them together again. For example, if Grisha has pieces in the order "bwbbw" (here 'b' denotes a black strip, and 'w' denotes a white strip), then he can split the sequence as bw|bbw (here the vertical bar represents the cut), reverse both parts and obtain "wbwbb".Determine the maximum possible length of the zebra that Grisha can produce.InputThe only line contains a string s (1 \le |s| \le 10^5, where |s| denotes the length of the string s) comprised of lowercase English letters 'b' and 'w' only, where 'w' denotes a white piece and 'b' denotes a black piece.OutputPrint a single integer — the maximum possible zebra length.ExamplesInputbwwwbwwbwOutput5InputbwwbwwbOutput3NoteIn the first example one of the possible sequence of operations is bwwwbww|bw \to w|wbwwwbwb \to wbwbwwwbw, that gives the answer equal to 5.In the second example no operation can increase the answer.
Inputbwwwbwwbw
Output5
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1600']
B. Weakened Common Divisortime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.For a given list of pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) their WCD is arbitrary integer greater than 1, such that it divides at least one element in each pair. WCD may not exist for some lists.For example, if the list looks like [(12, 15), (25, 18), (10, 24)], then their WCD can be equal to 2, 3, 5 or 6 (each of these numbers is strictly greater than 1 and divides at least one number in each pair).You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.InputThe first line contains a single integer n (1 \le n \le 150\,000) — the number of pairs.Each of the next n lines contains two integer values a_i, b_i (2 \le a_i, b_i \le 2 \cdot 10^9).OutputPrint a single integer — the WCD of the set of pairs. If there are multiple possible answers, output any; if there is no answer, print -1.ExamplesInput317 1815 2412 15Output6Input210 167 17Output-1Input590 10845 10575 40165 17533 30Output5NoteIn the first example the answer is 6 since it divides 18 from the first pair, 24 from the second and 12 from the third ones. Note that other valid answers will also be accepted.In the second example there are no integers greater than 1 satisfying the conditions.In the third example one of the possible answers is 5. Note that, for example, 15 is also allowed, but it's not necessary to maximize the output.
Input317 1815 2412 15
Output6
1.5 seconds
256 megabytes
['brute force', 'greedy', 'number theory', '*1600']
A. Doggo Recoloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPanic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color x such that there are currently at least two puppies of color x and recolor all puppies of the color x into some arbitrary color y. Luckily, this operation can be applied multiple times (including zero).For example, if the number of puppies is 7 and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose x='c' right now, because currently only one puppy has the color 'c'.Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of puppies.The second line contains a string s of length n consisting of lowercase Latin letters, where the i-th symbol denotes the i-th puppy's color.OutputIf it's possible to recolor all puppies into one color, print "Yes".Otherwise print "No".Output the answer without quotation signs.ExamplesInput6aabddcOutputYesInput3abcOutputNoInput3jjjOutputYesNoteIn the first example Slava can perform the following steps: take all puppies of color 'a' (a total of two) and recolor them into 'b'; take all puppies of color 'd' (a total of two) and recolor them into 'c'; take all puppies of color 'b' (three puppies for now) and recolor them into 'c'. In the second example it's impossible to recolor any of the puppies.In the third example all the puppies' colors are the same; thus there's no need to recolor anything.
Input6aabddc
OutputYes
1 second
256 megabytes
['implementation', 'sortings', '*900']
G. Piscestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA group of researchers are studying fish population in a natural system of lakes and rivers. The system contains n lakes connected by n - 1 rivers. Each river has integer length (in kilometers) and can be traversed in both directions. It is possible to travel between any pair of lakes by traversing the rivers (that is, the network of lakes and rivers form a tree).There is an unknown number of indistinguishable fish living in the lakes. On day 1, fish can be at arbitrary lakes. Fish can travel between lakes by swimming the rivers. Each fish can swim a river l kilometers long in any direction in l days. Further, each fish can stay any number of days in any particular lake it visits. No fish ever appear or disappear from the lake system. Each lake can accomodate any number of fish at any time.The researchers made several observations. The j-th of these observations is "on day d_j there were at least f_j distinct fish in the lake p_j". Help the researchers in determining the smallest possible total number of fish living in the lake system that doesn't contradict the observations.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of lakes in the system.The next n - 1 lines describe the rivers. The i-th of these lines contains three integers u_i, v_i, l_i (1 \leq u_i, v_i \leq n, u_i \neq v_i, 1 \leq l_i \leq 10^3) — 1-based indices of lakes connected by the i-th river, and the length of this river.The next line contains a single integer k (1 \leq k \leq 10^5) — the number of observations.The next k lines describe the observations. The j-th of these lines contains three integers d_j, f_j, p_j (1 \leq d_j \leq 10^8, 1 \leq f_j \leq 10^4, 1 \leq p_j \leq n) — the day, the number of fish, and the lake index of the j-th observation. No two observations happen on the same day at the same lake simultaneously.OutputPrint one integer — the smallest total number of fish not contradicting the observations.ExamplesInput41 2 11 3 11 4 151 1 21 1 32 2 13 1 43 1 2Output2Input51 2 11 3 11 4 11 5 141 1 22 1 33 1 44 1 5Output2Input52 5 15 1 12 4 15 3 365 2 42 1 12 1 32 2 44 7 54 1 2Output10NoteIn the first example, there could be one fish swimming through lakes 2, 1, and 4, and the second fish swimming through lakes 3, 1, and 2.In the second example a single fish can not possibly be part of all observations simultaneously, but two fish swimming 2 \to 1 \to 4 and 3 \to 1 \to 5 can.In the third example one fish can move from lake 1 to lake 5, others staying in their lakes during all time: two fish in lake 4, six fish in lake 5, one fish in lake 3. The system of lakes is shown on the picture.
Input41 2 11 3 11 4 151 1 21 1 32 2 13 1 43 1 2
Output2
5 seconds
512 megabytes
['data structures', 'flows', 'trees', '*3400']
F. Mobile Phone Networktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are managing a mobile phone network, and want to offer competitive prices to connect a network.The network has n nodes.Your competitor has already offered some connections between some nodes, with some fixed prices. These connections are bidirectional. There are initially m connections the competitor is offering. The i-th connection your competitor is offering will connect nodes fa_i and fb_i and costs fw_i. You have a list of k connections that you want to offer. It is guaranteed that this set of connection does not form any cycle. The j-th of these connections will connect nodes ga_j and gb_j. These connections are also bidirectional. The cost of these connections have not been decided yet.You can set the prices of these connections to any arbitrary integer value. These prices are set independently for each connection. After setting the prices, the customer will choose such n - 1 connections that all nodes are connected in a single network and the total cost of chosen connections is minimum possible. If there are multiple ways to choose such networks, the customer will choose an arbitrary one that also maximizes the number of your connections in it.You want to set prices in such a way such that all your k connections are chosen by the customer, and the sum of prices of your connections is maximized.Print the maximum profit you can achieve, or -1 if it is unbounded.InputThe first line of input will contain three integers n, k and m (1 \leq n, k, m \leq 5 \cdot 10^5, k \leq n-1), the number of nodes, the number of your connections, and the number of competitor connections, respectively.The next k lines contain two integers ga_i and gb_i (1 \leq ga_i, gb_i \leq n, ga_i \not= gb_i), representing one of your connections between nodes ga_i and gb_i. Your set of connections is guaranteed to be acyclic.The next m lines contain three integers each, fa_i, fb_i and fw_i (1 \leq fa_i, fb_i \leq n, fa_i \not= fb_i, 1 \leq fw_i \leq 10^9), denoting one of your competitor's connections between nodes fa_i and fb_i with cost fw_i. None of these connections connects a node to itself, and no pair of these connections connect the same pair of nodes. In addition, these connections are given by non-decreasing order of cost (that is, fw_{i-1} \leq fw_i for all valid i).Note that there may be some connections that appear in both your set and your competitor's set (though no connection will appear twice in one of this sets).It is guaranteed that the union of all of your connections and your competitor's connections form a connected network.OutputPrint a single integer, the maximum possible profit you can achieve if you set the prices on your connections appropriately. If the profit is unbounded, print -1.ExamplesInput4 3 61 23 41 32 3 33 1 41 2 44 2 84 3 84 1 10Output14Input3 2 11 22 31 2 30Output-1Input4 3 31 21 31 44 1 10000000004 2 10000000004 3 1000000000Output3000000000NoteIn the first sample, it's optimal to give connection 1-3 cost 3, connection 1-2 cost 3, and connection 3-4 cost 8. In this case, the cheapest connected network has cost 14, and the customer will choose one that chooses all of your connections.In the second sample, as long as your first connection costs 30 or less, the customer chooses both your connections no matter what is the cost of the second connection, so you can get unbounded profit in this case.
Input4 3 61 23 41 32 3 33 1 41 2 44 2 84 3 84 1 10
Output14
3 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'trees', '*2600']
E. Down or Righttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Bob lives in a square grid of size n \times n, with rows numbered 1 through n from top to bottom, and columns numbered 1 through n from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer n.Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed.You can ask at most 4 \cdot n queries of form "? r_1 c_1 r_2 c_2" (1 \le r_1 \le r_2 \le n, 1 \le c_1 \le c_2 \le n). The answer will be "YES" if Bob can get from a cell (r_1, c_1) to a cell (r_2, c_2), and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least n - 1, i.e. the following condition must be satisfied: (r_2 - r_1) + (c_2 - c_1) \ge n - 1.It's guaranteed that Bob can get from the top-left corner (1, 1) to the bottom-right corner (n, n) and your task is to find a way to do it. You should print the answer in form "! S" where S is a string of length 2 \cdot n - 2 consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by 1, the right move increases the second coordinate by 1. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.InputThe only line of the input contains an integer n (2 \le n \le 500) — the size of the grid.OutputWhen you are ready to print the answer, print a single line containing "! S" where where S is a string of length 2 \cdot n - 2 consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell (1, 1) to the cell (n, n) passing only through allowed cells.InteractionYou can ask at most 4 \cdot n queries. To ask a query, print a line containing "? r_1 c_1 r_2 c_2" (1 \le r_1 \le r_2 \le n, 1 \le c_1 \le c_2 \le n). After that you should read a single line containing "YES" or "NO" depending on the answer of the query. "YES" means Bob can go from the cell (r_1, c_1) to the cell (r_2, c_2), "NO" means the opposite.Note that the grid is fixed before the start of your solution and does not depend on your queries.After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded or other negative verdict. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Answer "BAD" instead of "YES" or "NO" means that you made an invalid query. Exit immediately after receiving "BAD" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.ExampleInput4 YES NO YES YES Output ? 1 1 4 4 ? 1 2 4 3 ? 4 1 4 4 ? 1 4 4 4 ! RDRRDDNoteThe first example is shown on the picture below. To hack, use the following input format:The first line should contain a single integer n (2 \le n \le 500) — the size of the grid.Each of the next n lines should contain a string of n characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell.For example, the following text encodes the example shown above:4..#.#...###.....
Input4 YES NO YES YES 
Output ? 1 1 4 4 ? 1 2 4 3 ? 4 1 4 4 ? 1 4 4 4 ! RDRRDD
1 second
256 megabytes
['constructive algorithms', 'interactive', 'matrices', '*2100']
D. Array Restorationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInitially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 \le l_i \le r_i \le n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.If there are multiple possible arrays then print any of them.InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the number of elements of the array and the number of queries perfomed on it.The second line contains n integer numbers a_1, a_2, \dots, a_n (0 \le a_i \le q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.OutputPrint "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 \le l_i \le r_i \le n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment. Otherwise print "NO".If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.If there are multiple possible arrays then print any of them.ExamplesInput4 31 0 2 3OutputYES1 2 2 3Input3 1010 10 10OutputYES10 10 10 Input5 66 5 6 2 2OutputNOInput3 50 0 0OutputYES5 4 2NoteIn the first example you can also replace 0 with 1 but not with 3.In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.There is a lot of correct resulting arrays for the fourth example.
Input4 31 0 2 3
OutputYES1 2 2 3
1 second
256 megabytes
['constructive algorithms', 'data structures', '*1700']
C. Bracket Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given a regular bracket sequence s and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s.It is guaranteed that such sequence always exists.InputThe first line contains two integers n and k (2 \le k \le n \le 2 \cdot 10^5, both n and k are even) — the length of s and the length of the sequence you are asked to find.The second line is a string s — regular bracket sequence of length n.OutputPrint a single string — a regular bracket sequence of length exactly k such that it is also a subsequence of s.It is guaranteed that such sequence always exists.ExamplesInput6 4()(())Output()()Input8 8(()(()))Output(()(()))
Input6 4()(())
Output()()
2 seconds
256 megabytes
['greedy', '*1200']
B. Pair of Toystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have?Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed.InputThe first line of the input contains two integers n, k (1 \le n, k \le 10^{14}) — the number of toys and the expected total cost of the pair of toys.OutputPrint the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles.ExamplesInput8 5Output2Input8 15Output1Input7 20Output0Input1000000000000 1000000000001Output500000000000NoteIn the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3).In the second example Tanechka can choose only the pair of toys (7, 8).In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0.In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000.
Input8 5
Output2
1 second
256 megabytes
['math', '*1000']
A. Single Wildcard Pattern Matchingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".If the given string t matches the given string s, print "YES", otherwise print "NO".InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^5) — the length of the string s and the length of the string t, respectively.The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.The third line contains string t of length m, which consists only of lowercase Latin letters.OutputPrint "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).ExamplesInput6 10code*scodeforcesOutputYESInput6 5vk*cupvkcupOutputYESInput1 1vkOutputNOInput9 6gfgf*gfgfgfgfgfOutputNONoteIn the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO".
Input6 10code*scodeforces
OutputYES
1 second
256 megabytes
['brute force', 'implementation', 'strings', '*1200']
B. Badgetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick. Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, however, claimed that the main culprit is some other student p_a.After that, the teacher came to student p_a and made a hole in his badge as well. The student in reply said that the main culprit was student p_{p_a}.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers p_i. Your task is to find out for every student a, who would be the student with two holes in the badge if the first caught student was a.InputThe first line of the input contains the only integer n (1 \le n \le 1000) — the number of the naughty students.The second line contains n integers p_1, ..., p_n (1 \le p_i \le n), where p_i indicates the student who was reported to the teacher by student i.OutputFor every student a from 1 to n print which student would receive two holes in the badge, if a was the first student caught by the teacher.ExamplesInput32 3 2Output2 2 3 Input31 2 3Output1 2 3 NoteThe picture corresponds to the first example test case. When a = 1, the teacher comes to students 1, 2, 3, 2, in this order, and the student 2 is the one who receives a second hole in his badge.When a = 2, the teacher comes to students 2, 3, 2, and the student 2 gets a second hole in his badge. When a = 3, the teacher will visit students 3, 2, 3 with student 3 getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
Input32 3 2
Output2 2 3
1 second
256 megabytes
['brute force', 'dfs and similar', 'graphs', '*1000']
A. New Building for SIStime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.InputThe first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 108), h: the number of floors in each tower (1 ≤ h ≤ 108), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 104). Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.OutputFor each query print a single integer: the minimum walking time between the locations in minutes.ExampleInput3 6 2 3 31 2 1 31 4 3 41 2 2 3Output142
Input3 6 2 3 31 2 1 31 4 3 41 2 2 3
Output142
1 second
256 megabytes
['math', '*1000']
E. Raining seasontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBy the year 3018, Summer Informatics School has greatly grown. Hotel «Berendeetronik» has been chosen as a location of the school. The camp consists of n houses with n-1 pathways between them. It is possible to reach every house from each other using the pathways.Everything had been perfect until the rains started. The weather forecast promises that rains will continue for m days. A special squad of teachers was able to measure that the i-th pathway, connecting houses u_i and v_i, before the rain could be passed in b_i seconds. Unfortunately, the rain erodes the roads, so with every day the time to pass the road will increase by a_i seconds. In other words, on the t-th (from zero) day after the start of the rain, it will take a_i \cdot t + b_i seconds to pass through this road.Unfortunately, despite all the efforts of teachers, even in the year 3018 not all the students are in their houses by midnight. As by midnight all students have to go to bed, it is important to find the maximal time between all the pairs of houses for each day, so every student would know the time when he has to run to his house.Find all the maximal times of paths between every pairs of houses after t=0, t=1, ..., t=m-1 days.InputIn the first line you are given two integers n and m — the number of houses in the camp and the number of raining days (1 \le n \le 100\,000; 1 \le m \le 1\,000\,000).In the next n-1 lines you are given the integers u_i, v_i, a_i, b_i — description of pathways (1 \le u_i, v_i \le n; 0 \le a_i \le 10^5; 0 \le b_i \le 10^9). i-th pathway connects houses u_i and v_i, and in day t requires a_i \cdot t + b_i seconds to pass through.It is guaranteed that every two houses are connected by a sequence of pathways.OutputPrint m integers — the lengths of the longest path in the camp after a t=0, t=1, \ldots, t=m-1 days after the start of the rain.ExampleInput5 101 2 0 1001 3 0 1001 4 10 801 5 20 0Output200 200 200 210 220 230 260 290 320 350NoteLet's consider the first example.In the first three days (0 \le t \le 2) the longest path is between 2nd and 3rd houses, and its length is equal to 100+100=200 seconds.In the third day (t=2) the road between houses 1 and 4 has length 100 and keeps increasing. So, in days t=2, 3, 4, 5 the longest path is between vertices 4 and (1 or 2), and has length 180+10t. Notice, that in the day t=2 there are three pathways with length 100, so there are three maximal paths of equal length.In the sixth day (t=5) pathway between first and fifth houses get length 100. So in every day with t=5 and further the longest path is between houses 4 and 5 and has length 80+30t.
Input5 101 2 0 1001 3 0 1001 4 10 801 5 20 0
Output200 200 200 210 220 230 260 290 320 350
3 seconds
256 megabytes
['data structures', 'divide and conquer', 'trees', '*3200']
D. Large Triangletime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a strange peculiarity: if you connect the cities of Rostov, Taganrog and Shakhty, peculiarly, you get a triangle«Unbelievable But True»Students from many different parts of Russia and abroad come to Summer Informatics School. You marked the hometowns of the SIS participants on a map.Now you decided to prepare an interesting infographic based on this map. The first thing you chose to do is to find three cities on this map, such that they form a triangle with area S.InputThe first line of input contains two integers n and S (3 \le n \le 2000, 1 \le S \le 2 \cdot 10^{18}) — the number of cities on the map and the area of the triangle to be found.The next n lines contain descriptions of the cities, one per line. Each city is described by its integer coordinates x_i, y_i (-10^9 \le x_i, y_i \le 10^9). It is guaranteed that all cities are located at distinct points. It is also guaranteed that no three cities lie on the same line.OutputIf the solution doesn't exist — print «No».Otherwise, print «Yes», followed by three pairs of coordinates (x, y) — the locations of the three cities, which form the triangle of area S.ExamplesInput3 70 03 00 4OutputNoInput4 30 02 01 21 3OutputYes0 01 32 0
Input3 70 03 00 4
OutputNo
3 seconds
256 megabytes
['binary search', 'geometry', 'sortings', '*2700']
C. Sergey's problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree. Today he celebrates his birthday again! He found a directed graph without loops as a present from his parents.Since Sergey is a very curious boy, he immediately came up with a thing to do. He decided to find a set Q of vertices in this graph, such that no two vertices x, y \in Q are connected by an edge, and it is possible to reach any vertex z \notin Q from some vertex of Q in no more than two moves.  After a little thought, Sergey was able to solve this task. Can you solve it too?A vertex y is reachable from a vertex x in at most two moves if either there is a directed edge (x,y), or there exist two directed edges (x,z) and (z, y) for some vertex z.InputThe first line of input contains two positive integers n and m (1 \le n \le 1\,000\,000, 1 \le m \le 1\,000\,000) — the number of vertices and the number of edges in the directed graph.Each of the following m lines describes a corresponding edge. Each one contains two integers a_i and b_i (1 \le a_i, b_i \le n, a_i \ne b_i) — the beginning and the end of the i-th edge. The graph may contain multiple edges between the same pair of vertices.OutputFirst print the number k — the number of selected vertices. Then print k distinct integers — the indices of the selected vertices.If multiple answers exist you can output any of them. In particular, you don't have to minimize the number of vertices in the set. It is guaranteed, that there is always at least one valid set.ExamplesInput5 41 22 32 42 5Output41 3 4 5 Input3 31 22 33 1Output13 NoteIn the first sample, the vertices 1, 3, 4, 5 are not connected. The vertex 2 is reachable from vertex 1 by one edge.In the second sample, it is possible to reach the vertex 1 in one move and the vertex 2 in two moves.The following pictures illustrate sample tests and their answers.    
Input5 41 22 32 42 5
Output41 3 4 5
2 seconds
256 megabytes
['constructive algorithms', 'graphs', '*3000']
B. The hattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions.InputAt the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students.You are allowed to ask no more than 60 questions.OutputTo ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109).When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program.The query that contains your answer is not counted towards the limit of 60 queries.Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language.HackingUse the following format for hacking:In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students.In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or  - 1.The hacked solution will not have direct access to the sequence ai.ExamplesInput822Output? 4? 8! 4Input6123 210Output? 1? 2? 3? 4? 5? 6! -1NoteInput-output in statements illustrates example interaction.In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2In the second sample the selection sequence is 1, 2, 3, 2, 1, 0.
Input822
Output? 4? 8! 4
1 second
256 megabytes
['binary search', 'interactive', '*2000']
A. Electionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.Elections are coming. You know the number of voters and the number of parties — n and m respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give i-th voter c_i bytecoins you can ask him to vote for any other party you choose.The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.InputThe first line of input contains two integers n and m (1 \le n, m \le 3000) — the number of voters and the number of parties respectively.Each of the following n lines contains two integers p_i and c_i (1 \le p_i \le m, 1 \le c_i \le 10^9) — the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision.The United Party of Berland has the index 1.OutputPrint a single number — the minimum number of bytecoins needed for The United Party of Berland to win the elections.ExamplesInput1 21 100Output0Input5 52 1003 2004 3005 4005 900Output500Input5 52 1003 2004 3005 8005 900Output600NoteIn the first sample, The United Party wins the elections even without buying extra votes.In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties 3, 4 and 5 get one vote and party number 2 gets no votes.In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party.
Input1 21 100
Output0
2 seconds
256 megabytes
['brute force', 'greedy', '*1700']
H. The Filmstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn "The Man in the High Castle" world, there are m different film endings. Abendsen owns a storage and a shelf. At first, he has n ordered films on the shelf. In the i-th month he will do: Empty the storage. Put k_i \cdot m films into the storage, k_i films for each ending. He will think about a question: if he puts all the films from the shelf into the storage, then randomly picks n films (from all the films in the storage) and rearranges them on the shelf, what is the probability that sequence of endings in [l_i, r_i] on the shelf will not be changed? Notice, he just thinks about this question, so the shelf will not actually be changed.Answer all Abendsen's questions.Let the probability be fraction P_i. Let's say that the total number of ways to take n films from the storage for i-th month is A_i, so P_i \cdot A_i is always an integer. Print for each month P_i \cdot A_i \pmod {998244353}.998244353 is a prime number and it is equal to 119 \cdot 2^{23} + 1.It is guaranteed that there will be only no more than 100 different k values.InputThe first line contains three integers n, m, and q (1 \le n, m, q \le 10^5, n+q\leq 10^5) — the number of films on the shelf initially, the number of endings, and the number of months.The second line contains n integers e_1, e_2, \ldots, e_n (1\leq e_i\leq m) — the ending of the i-th film on the shelf.Each of the next q lines contains three integers l_i, r_i, and k_i (1 \le l_i \le r_i \le n, 0 \le k_i \le 10^5) — the i-th query.It is guaranteed that there will be only no more than 100 different k values.OutputPrint the answer for each question in a separate line.ExamplesInput6 4 41 2 3 4 4 41 4 01 3 21 4 21 5 2Output626730121504860Input5 5 31 2 3 4 51 2 1000001 4 43 5 5Output49494221813125151632NoteIn the first sample in the second query, after adding 2 \cdot m films into the storage, the storage will look like this: \{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4\}.There are 26730 total ways of choosing the films so that e_l, e_{l+1}, \ldots, e_r will not be changed, for example, [1, 2, 3, 2, 2] and [1, 2, 3, 4, 3] are such ways.There are 2162160 total ways of choosing the films, so you're asked to print (\frac{26730}{2162160} \cdot 2162160) \mod 998244353 = 26730.
Input6 4 41 2 3 4 4 41 4 01 3 21 4 21 5 2
Output626730121504860
5 seconds
512 megabytes
['brute force', '*3300']
G. The Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAbendsen assigned a mission to Juliana. In this mission, Juliana has a rooted tree with n vertices. Vertex number 1 is the root of this tree. Each vertex can be either black or white. At first, all vertices are white. Juliana is asked to process q queries. Each query is one of three types: If vertex v is white, mark it as black; otherwise, perform this operation on all direct sons of v instead. Mark all vertices in the subtree of v (including v) as white. Find the color of the i-th vertex. An example of operation "1 1" (corresponds to the first example test). The vertices 1 and 2 are already black, so the operation goes to their sons instead. Can you help Juliana to process all these queries?InputThe first line contains two integers n and q (2\leq n\leq 10^5, 1\leq q\leq 10^5) — the number of vertices and the number of queries.The second line contains n-1 integers p_2, p_3, \ldots, p_n (1\leq p_i<i), where p_i means that there is an edge between vertices i and p_i. Each of the next q lines contains two integers t_i and v_i (1\leq t_i\leq 3, 1\leq v_i\leq n) — the type of the i-th query and the vertex of the i-th query.It is guaranteed that the given graph is a tree.OutputFor each query of type 3, print "black" if the vertex is black; otherwise, print "white".ExamplesInput8 101 2 1 2 5 4 51 23 23 11 11 13 53 73 42 23 5OutputblackwhiteblackwhiteblackwhiteInput8 111 1 2 3 3 6 61 11 11 33 23 43 63 72 31 63 73 6OutputblackwhiteblackwhitewhiteblackNoteThe first example is shown on the picture below. The second example is shown on the picture below.
Input8 101 2 1 2 5 4 51 23 23 11 11 13 53 73 42 23 5
Outputblackwhiteblackwhiteblackwhite
3 seconds
256 megabytes
['data structures', '*3200']
F. The Neutral Zonetime limit per test5 secondsmemory limit per test16 megabytesinputstandard inputoutputstandard outputNotice: unusual memory limit!After the war, destroyed cities in the neutral zone were restored. And children went back to school.The war changed the world, as well as education. In those hard days, a new math concept was created.As we all know, logarithm function can be described as: \log(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 \log p_1 + a_2 \log p_2 + ... + a_k \log p_k Where p_1^{a_1}p_2^{a_2}...p_k^{a_2} is the prime factorization of a integer. A problem is that the function uses itself in the definition. That is why it is hard to calculate.So, the mathematicians from the neutral zone invented this: \text{exlog}_f(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 f(p_1) + a_2 f(p_2) + ... + a_k f(p_k) Notice that \text{exlog}_f(1) is always equal to 0.This concept for any function f was too hard for children. So teachers told them that f can only be a polynomial of degree no more than 3 in daily uses (i.e., f(x) = Ax^3+Bx^2+Cx+D)."Class is over! Don't forget to do your homework!" Here it is: \sum_{i=1}^n \text{exlog}_f(i) Help children to do their homework. Since the value can be very big, you need to find the answer modulo 2^{32}.InputThe only line contains five integers n, A, B, C, and D (1 \le n \le 3 \cdot 10^8, 0 \le A,B,C,D \le 10^6).OutputPrint the answer modulo 2^{32}.ExamplesInput12 0 0 1 0Output63Input4 1 2 3 4Output136NoteIn the first sample:\text{exlog}_f(1) = 0\text{exlog}_f(2) = 2\text{exlog}_f(3) = 3\text{exlog}_f(4) = 2 + 2 = 4\text{exlog}_f(5) = 5\text{exlog}_f(6) = 2 + 3 = 5\text{exlog}_f(7) = 7\text{exlog}_f(8) = 2 + 2 + 2 = 6\text{exlog}_f(9) = 3 + 3 = 6\text{exlog}_f(10) = 2 + 5 = 7\text{exlog}_f(11) = 11\text{exlog}_f(12) = 2 + 2 + 3 = 7 \sum_{i=1}^{12} \text{exlog}_f(i)=63 In the second sample:\text{exlog}_f(1) = 0\text{exlog}_f(2) = (1 \times 2^3 + 2 \times 2^2 + 3 \times 2 + 4) = 26\text{exlog}_f(3) = (1 \times 3^3 + 2 \times 3^2 + 3 \times 3 + 4) = 58\text{exlog}_f(4) = 2 \times \text{exlog}_f(2) = 52 \sum_{i=1}^4 \text{exlog}_f(i)=0+26+58+52=136
Input12 0 0 1 0
Output63
5 seconds
16 megabytes
['brute force', 'math', '*2500']
E. The Supersonic Rockettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the war, the supersonic rocket became the most common public transportation.Each supersonic rocket consists of two "engines". Each engine is a set of "power sources". The first engine has n power sources, and the second one has m power sources. A power source can be described as a point (x_i, y_i) on a 2-D plane. All points in each engine are different.You can manipulate each engine separately. There are two operations that you can do with each engine. You can do each operation as many times as you want. For every power source as a whole in that engine: (x_i, y_i) becomes (x_i+a, y_i+b), a and b can be any real numbers. In other words, all power sources will be shifted. For every power source as a whole in that engine: (x_i, y_i) becomes (x_i \cos \theta - y_i \sin \theta, x_i \sin \theta + y_i \cos \theta), \theta can be any real number. In other words, all power sources will be rotated.The engines work as follows: after the two engines are powered, their power sources are being combined (here power sources of different engines may coincide). If two power sources A(x_a, y_a) and B(x_b, y_b) exist, then for all real number k that 0 \lt k \lt 1, a new power source will be created C_k(kx_a+(1-k)x_b,ky_a+(1-k)y_b). Then, this procedure will be repeated again with all new and old power sources. After that, the "power field" from all power sources will be generated (can be considered as an infinite set of all power sources occurred).A supersonic rocket is "safe" if and only if after you manipulate the engines, destroying any power source and then power the engine, the power field generated won't be changed (comparing to the situation where no power source erased). Two power fields are considered the same if and only if any power source in one field belongs to the other one as well.Given a supersonic rocket, check whether it is safe or not.InputThe first line contains two integers n, m (3 \le n, m \le 10^5) — the number of power sources in each engine.Each of the next n lines contains two integers x_i and y_i (0\leq x_i, y_i\leq 10^8) — the coordinates of the i-th power source in the first engine.Each of the next m lines contains two integers x_i and y_i (0\leq x_i, y_i\leq 10^8) — the coordinates of the i-th power source in the second engine.It is guaranteed that there are no two or more power sources that are located in the same point in each engine.OutputPrint "YES" if the supersonic rocket is safe, otherwise "NO".You can print each letter in an arbitrary case (upper or lower).ExamplesInput3 40 00 22 00 22 22 01 1OutputYESInput3 40 00 22 00 22 22 00 0OutputNONoteThe first sample: Those near pairs of blue and orange points actually coincide. First, manipulate the first engine: use the second operation with \theta = \pi (to rotate all power sources 180 degrees).The power sources in the first engine become (0, 0), (0, -2), and (-2, 0). Second, manipulate the second engine: use the first operation with a = b = -2.The power sources in the second engine become (-2, 0), (0, 0), (0, -2), and (-1, -1). You can examine that destroying any point, the power field formed by the two engines are always the solid triangle (0, 0), (-2, 0), (0, -2).In the second sample, no matter how you manipulate the engines, there always exists a power source in the second engine that power field will shrink if you destroy it.
Input3 40 00 22 00 22 22 01 1
OutputYES
1 second
256 megabytes
['geometry', 'hashing', 'strings', '*2400']
D. The Wutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChildan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.This "personal treasure" is a multiset S of m "01-strings".A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.Note that the multiset S can contain equal elements.Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k. Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1\leq i\leq n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.InputThe first line contains three integers n, m, and q (1\leq n\leq 12, 1\leq q, m\leq 5\cdot 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.The second line contains n integers w_1, w_2, \ldots, w_n (0 \le w_i \le 100) — the value of the i-th caracter.Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.Each of the next q lines contains the "01-string" t of length n and integer k (0\leq k\leq 100) — the query.OutputFor each query, print the answer for this query.ExamplesInput2 4 540 200101101100 2000 4011 2011 4011 60Output24234Input1 2 4100010 00 1001 01 100Output1212NoteIn the first example, we can get:"Wu" of ("01", "00") is 40."Wu" of ("10", "00") is 20."Wu" of ("11", "00") is 0."Wu" of ("01", "11") is 20."Wu" of ("10", "11") is 40."Wu" of ("11", "11") is 60.In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.In the second query, all strings satisfy the condition.In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too.
Input2 4 540 200101101100 2000 4011 2011 4011 60
Output24234
2 seconds
256 megabytes
['bitmasks', 'brute force', 'data structures', '*1900']
C. The Phone Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence a_{i_1}, a_{i_2}, \ldots, a_{i_k} where 1\leq i_1 < i_2 < \ldots < i_k\leq n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.InputThe only line contains one integer n (1 \le n \le 10^5) — the length of permutation that you need to build.OutputPrint a permutation that gives a minimum sum of lengths of LIS and LDS. If there are multiple answers, print any.ExamplesInput4Output3 4 1 2Input2Output2 1NoteIn the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Input4
Output3 4 1 2
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1600']
B. The Bitstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise OR of a and b, you need to find the number of ways of swapping two bits in a so that bitwise OR will not be equal to c.Note that binary numbers can contain leading zeros so that length of each number is exactly n.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, 01010_2 OR 10011_2 = 11011_2.Well, to your surprise, you are not Rudolf, and you don't need to help him\ldots You are the security staff! Please find the number of ways of swapping two bits in a so that bitwise OR will be changed.InputThe first line contains one integer n (2\leq n\leq 10^5) — the number of bits in each number.The second line contains a binary number a of length n.The third line contains a binary number b of length n.OutputPrint the number of ways to swap two bits in a so that bitwise OR will be changed.ExamplesInput50101111001Output4Input6011000010011Output6NoteIn the first sample, you can swap bits that have indexes (1, 4), (2, 3), (3, 4), and (3, 5).In the second example, you can swap bits that have indexes (1, 2), (1, 3), (2, 4), (3, 4), (3, 5), and (3, 6).
Input50101111001
Output4
2 seconds
256 megabytes
['implementation', 'math', '*1200']
A. The Ranktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. InputThe first line contains a single integer n (1 \le n \le 1000) — the number of students.Each of the next n lines contains four integers a_i, b_i, c_i, and d_i (0\leq a_i, b_i, c_i, d_i\leq 100) — the grades of the i-th student on English, German, Math, and History. The id of the i-th student is equal to i.OutputPrint the rank of Thomas Smith. Thomas's id is 1.ExamplesInput5100 98 100 100100 100 100 100100 100 99 9990 99 90 100100 98 60 99Output2Input6100 80 90 9960 60 60 6090 60 100 6060 100 60 80100 100 0 1000 0 0 0Output1NoteIn the first sample, the students got total scores: 398, 400, 398, 379, and 357. Among the 5 students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is 2.In the second sample, the students got total scores: 369, 240, 310, 300, 300, and 0. Among the 6 students, Thomas got the highest score, so his rank is 1.
Input5100 98 100 100100 100 100 100100 100 99 9990 99 90 100100 98 60 99
Output2
1 second
256 megabytes
['implementation', '*800']
G. Appropriate Teamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince next season are coming, you'd like to form a team from two or three participants. There are n candidates, the i-th candidate has rank a_i. But you have weird requirements for your teammates: if you have rank v and have chosen the i-th and j-th candidate, then GCD(v, a_i) = X and LCM(v, a_j) = Y must be met.You are very experienced, so you can change your rank to any non-negative integer but X and Y are tied with your birthdate, so they are fixed.Now you want to know, how many are there pairs (i, j) such that there exists an integer v meeting the following constraints: GCD(v, a_i) = X and LCM(v, a_j) = Y. It's possible that i = j and you form a team of two.GCD is the greatest common divisor of two number, LCM — the least common multiple.InputFirst line contains three integers n, X and Y (1 \le n \le 2 \cdot 10^5, 1 \le X \le Y \le 10^{18}) — the number of candidates and corresponding constants.Second line contains n space separated integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{18}) — ranks of candidates.OutputPrint the only integer — the number of pairs (i, j) such that there exists an integer v meeting the following constraints: GCD(v, a_i) = X and LCM(v, a_j) = Y. It's possible that i = j.ExamplesInput12 2 21 2 3 4 5 6 7 8 9 10 11 12Output12Input12 1 61 3 5 7 9 11 12 10 8 6 4 2Output30NoteIn the first example next pairs are valid: a_j = 1 and a_i = [2, 4, 6, 8, 10, 12] or a_j = 2 and a_i = [2, 4, 6, 8, 10, 12]. The v in both cases can be equal to 2.In the second example next pairs are valid: a_j = 1 and a_i = [1, 5, 7, 11]; a_j = 2 and a_i = [1, 5, 7, 11, 10, 8, 4, 2]; a_j = 3 and a_i = [1, 3, 5, 7, 9, 11]; a_j = 6 and a_i = [1, 3, 5, 7, 9, 11, 12, 10, 8, 6, 4, 2].
Input12 2 21 2 3 4 5 6 7 8 9 10 11 12
Output12
2 seconds
256 megabytes
['bitmasks', 'math', 'number theory', '*2700']
F. Road Projectstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from 1 to n.The travelling time between some cities v and u is the total length of the roads on the shortest path from v to u. The two most important cities in Berland are cities 1 and n.The Berland Ministry of Transport decided to build a single new road to decrease the traffic between the most important cities. However, lots of people are used to the current travelling time between the most important cities, so the new road shouldn't change it too much. The new road can only be built between such cities v and u that v \neq u and v and u aren't already connected by some road.They came up with m possible projects. Each project is just the length x of the new road.Polycarp works as a head analyst at the Berland Ministry of Transport and it's his job to deal with all those m projects. For the i-th project he is required to choose some cities v and u to build the new road of length x_i between such that the travelling time between the most important cities is maximal possible. Unfortunately, Polycarp is not a programmer and no analyst in the world is capable to process all projects using only pen and paper. Thus, he asks you to help him to calculate the maximal possible travelling time between the most important cities for each project. Note that the choice of v and u can differ for different projects.InputThe first line contains two integers n and m (3 \le n \le 3 \cdot 10^5, 1 \le m \le 3 \cdot 10^5) — the number of cities and the number of projects, respectively.Each of the next n - 1 lines contains three integers v_i, u_i and w_i (1 \le v_i, u_i \le n, 1 \le w_i \le 10^9) — the description of the i-th road. It is guaranteed that there exists exactly one path, which visits each road no more than once, between every pair of cities.Each of the next m lines contains a single integer x_j (1 \le x_j \le 10^9) — the length of the road for the j-th project.OutputPrint m lines, the j-th line should contain a single integer — the maximal possible travelling time between the most important cities for the j-th project.ExampleInput7 21 2 182 3 223 4 244 7 242 6 43 5 121100Output8388NoteThe road network from the first example:You can build the road with length 1 between cities 5 and 6 to get 83 as the travelling time between 1 and 7 (1 \rightarrow 2 \rightarrow 6 \rightarrow 5 \rightarrow 3 \rightarrow 4 \rightarrow 7 = 18 + 4 + 1 + 12 + 24 + 24 = 83). Other possible pairs of cities will give answers less or equal to 83.
Input7 21 2 182 3 223 4 244 7 242 6 43 5 121100
Output8388
2 seconds
256 megabytes
['dfs and similar', 'dp', 'trees', '*2600']
E. Rest In The Shadestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point (a, s_y) to the (b, s_y) (s_y < 0) with speed equal to 1 unit per second. The trajectory of this light source is a straight segment connecting these two points. There is also a fence on OX axis represented as n segments (l_i, r_i) (so the actual coordinates of endpoints of each segment are (l_i, 0) and (r_i, 0)). The point (x, y) is in the shade if segment connecting (x,y) and the current position of the light source intersects or touches with any segment of the fence. You are given q points. For each point calculate total time of this point being in the shade, while the light source is moving from (a, s_y) to the (b, s_y).InputFirst line contains three space separated integers s_y, a and b (-10^9 \le s_y < 0, 1 \le a < b \le 10^9) — corresponding coordinates of the light source.Second line contains single integer n (1 \le n \le 2 \cdot 10^5) — number of segments in the fence.Next n lines contain two integers per line: l_i and r_i (1 \le l_i < r_i \le 10^9, r_{i - 1} < l_i) — segments in the fence in increasing order. Segments don't intersect or touch each other.Next line contains single integer q (1 \le q \le 2 \cdot 10^5) — number of points to check.Next q lines contain two integers per line: x_i and y_i (1 \le x_i, y_i \le 10^9) — points to process.OutputPrint q lines. The i-th line should contain one real number — total time of the i-th point being in the shade, while the light source is moving from (a, s_y) to the (b, s_y). The answer is considered as correct if its absolute of relative error doesn't exceed 10^{-6}.ExampleInput-3 1 622 46 753 11 36 16 47 6Output5.0000000000000003.0000000000000000.0000000000000001.5000000000000002.000000000000000Note The 1-st point is always in the shade; the 2-nd point is in the shade while light source is moving from (3, -3) to (6, -3); the 3-rd point is in the shade while light source is at point (6, -3). the 4-th point is in the shade while light source is moving from (1, -3) to (2.5, -3) and at point (6, -3); the 5-th point is in the shade while light source is moving from (1, -3) to (2.5, -3) and from (5.5, -3) to (6, -3);
Input-3 1 622 46 753 11 36 16 47 6
Output5.0000000000000003.0000000000000000.0000000000000001.5000000000000002.000000000000000
2 seconds
256 megabytes
['binary search', 'geometry', '*2400']
D. Vasya And The Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.InputThe first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix.The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i.The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i.OutputIf there is no matrix satisfying the given constraints in the first line, output "NO".Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix.If there are several suitable matrices, it is allowed to print any of them.ExamplesInput2 32 95 3 13OutputYES3 4 56 7 8Input3 31 7 62 15 12OutputNO
Input2 32 95 3 13
OutputYES3 4 56 7 8
2 seconds
256 megabytes
['constructive algorithms', 'flows', 'math', '*1800']
C. Vasya And The Mushroomstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.InputThe first line contains the number n (1 ≤ n ≤ 3·105) — the length of the glade.The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the growth rate of mushrooms in the first row of the glade.The third line contains n numbers b1, b2, ..., bn (1 ≤ bi ≤ 106) is the growth rate of mushrooms in the second row of the glade.OutputOutput one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.ExamplesInput31 2 36 5 4Output70Input31 1000 1000010 100 100000Output543210NoteIn the first test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.In the second test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.
Input31 2 36 5 4
Output70
2 seconds
256 megabytes
['dp', 'implementation', '*1800']
B. Segment Occurrencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t, both consisting only of lowercase Latin letters.The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, \dots, s_r without changing the order.Each of the occurrences of string a in a string b is a position i (1 \le i \le |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a).You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i].InputThe first line contains three integer numbers n, m and q (1 \le n, m \le 10^3, 1 \le q \le 10^5) — the length of string s, the length of string t and the number of queries, respectively.The second line is a string s (|s| = n), consisting only of lowercase Latin letters.The third line is a string t (|t| = m), consisting only of lowercase Latin letters.Each of the next q lines contains two integer numbers l_i and r_i (1 \le l_i \le r_i \le n) — the arguments for the i-th query.OutputPrint q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i].ExamplesInput10 3 4codeforcesfor1 33 105 65 7Output0101Input15 2 3abacabadabacababa1 153 42 14Output403Input3 5 2aaabaaab1 31 1Output00NoteIn the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively.
Input10 3 4codeforcesfor1 33 105 65 7
Output0101
2 seconds
256 megabytes
['brute force', 'implementation', '*1300']
A. Death Notetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly m names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from 1 to n.InputThe first line of the input contains two integers n, m (1 \le n \le 2 \cdot 10^5, 1 \le m \le 10^9) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i means the number of names you will write in the notebook during the i-th day.OutputPrint exactly n integers t_1, t_2, \dots, t_n, where t_i is the number of times you will turn the page during the i-th day.ExamplesInput3 53 7 9Output0 2 1 Input4 2010 9 19 2Output0 0 1 1 Input1 10099Output0 NoteIn the first example pages of the Death Note will look like this [1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.
Input3 53 7 9
Output0 2 1
2 seconds
256 megabytes
['greedy', 'implementation', 'math', '*900']
F. Bracket Substringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a bracket sequence s (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'.A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.Your problem is to calculate the number of regular bracket sequences of length 2n containing the given bracket sequence s as a substring (consecutive sequence of characters) modulo 10^9+7 (1000000007).InputThe first line of the input contains one integer n (1 \le n \le 100) — the half-length of the resulting regular bracket sequences (the resulting sequences must have length equal to 2n).The second line of the input contains one string s (1 \le |s| \le 200) — the string s that should be a substring in each of the resulting regular bracket sequences (|s| is the length of s).OutputPrint only one integer — the number of regular bracket sequences containing the given bracket sequence s as a substring. Since this number can be huge, print it modulo 10^9+7 (1000000007).ExamplesInput5()))()Output5Input3(()Output4Input2(((Output0NoteAll regular bracket sequences satisfying the conditions above for the first example: "(((()))())"; "((()()))()"; "((()))()()"; "(()(()))()"; "()((()))()". All regular bracket sequences satisfying the conditions above for the second example: "((()))"; "(()())"; "(())()"; "()(())". And there is no regular bracket sequences of length 4 containing "(((" as a substring in the third example.
Input5()))()
Output5
1 second
256 megabytes
['dp', 'strings', '*2300']
E2. Stars Drawing (Hard Edition)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars: The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3. You are given a rectangular grid of size n \times m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n \cdot m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n \cdot m stars.InputThe first line of the input contains two integers n and m (3 \le n, m \le 1000) — the sizes of the given grid.The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.OutputIf it is impossible to draw the given grid using stars only, print "-1".Otherwise in the first line print one integer k (0 \le k \le n \cdot m) — the number of stars needed to draw the given grid. The next k lines should contain three integers each — x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid.ExamplesInput6 8....*......**.....*****....**.......*...........Output33 4 13 5 23 5 1Input5 5.*...****..****..**......Output32 2 13 3 13 4 1Input5 5.*...***...*....*........Output-1Input3 3*.*.*.*.*Output-1NoteIn the first example the output 23 4 13 5 2is also correct.
Input6 8....*......**.....*****....**.......*...........
Output33 4 13 5 23 5 1
3 seconds
256 megabytes
['binary search', 'dp', 'greedy', '*1900']
E1. Stars Drawing (Easy Edition)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars: The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3. You are given a rectangular grid of size n \times m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n \cdot m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n \cdot m stars.InputThe first line of the input contains two integers n and m (3 \le n, m \le 100) — the sizes of the given grid.The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.OutputIf it is impossible to draw the given grid using stars only, print "-1".Otherwise in the first line print one integer k (0 \le k \le n \cdot m) — the number of stars needed to draw the given grid. The next k lines should contain three integers each — x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid.ExamplesInput6 8....*......**.....*****....**.......*...........Output33 4 13 5 23 5 1Input5 5.*...****..****..**......Output32 2 13 3 13 4 1Input5 5.*...***...*....*........Output-1Input3 3*.*.*.*.*Output-1NoteIn the first example the output 23 4 13 5 2is also correct.
Input6 8....*......**.....*****....**.......*...........
Output33 4 13 5 23 5 1
3 seconds
256 megabytes
['brute force', 'dp', 'greedy', '*1700']
D. Walking Between Housestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n houses in a row. They are numbered from 1 to n in order from left to right. Initially you are in the house 1.You have to perform k moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house x to the house y, the total distance you walked increases by |x-y| units of distance, where |a| is the absolute value of a. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).Your goal is to walk exactly s units of distance in total.If it is impossible, print "NO". Otherwise print "YES" and any of the ways to do that. Remember that you should do exactly k moves.InputThe first line of the input contains three integers n, k, s (2 \le n \le 10^9, 1 \le k \le 2 \cdot 10^5, 1 \le s \le 10^{18}) — the number of houses, the number of moves and the total distance you want to walk.OutputIf you cannot perform k moves with total walking distance equal to s, print "NO".Otherwise print "YES" on the first line and then print exactly k integers h_i (1 \le h_i \le n) on the second line, where h_i is the house you visit on the i-th move.For each j from 1 to k-1 the following condition should be satisfied: h_j \ne h_{j + 1}. Also h_1 \ne 1 should be satisfied.ExamplesInput10 2 15OutputYES10 4 Input10 9 45OutputYES10 1 10 1 2 1 2 1 6 Input10 9 81OutputYES10 1 10 1 10 1 10 1 10 Input10 9 82OutputNO
Input10 2 15
OutputYES10 4
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1600']
C. Songs Compressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty.Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduces from a_i to b_i bytes (b_i < a_i).Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most m. He can compress any subset of the songs (not necessarily contiguous).Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to m).If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress.InputThe first line of the input contains two integers n and m (1 \le n \le 10^5, 1 \le m \le 10^9) — the number of the songs on Ivan's phone and the capacity of Ivan's flash drive.The next n lines contain two integers each: the i-th line contains two integers a_i and b_i (1 \le a_i, b_i \le 10^9, a_i > b_i) — the initial size of the i-th song and the size of the i-th song after compression.OutputIf it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print "-1". Otherwise print the minimum number of the songs to compress.ExamplesInput4 2110 87 43 15 4Output2Input4 1610 87 43 15 4Output-1NoteIn the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to 8 + 7 + 1 + 5 = 21 \le 21. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal 8 + 4 + 3 + 5 = 20 \le 21. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to 10 + 4 + 3 + 5 = 22 > 21).In the second example even if Ivan compresses all the songs the sum of sizes will be equal 8 + 4 + 1 + 4 = 17 > 16.
Input4 2110 87 43 15 4
Output2
1 second
256 megabytes
['sortings', '*1100']
B. Obtaining the Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n.You can successively perform the following move any number of times (possibly, zero): swap any two adjacent (neighboring) characters of s (i.e. for any i = \{1, 2, \dots, n - 1\} you can swap s_i and s_{i + 1}). You can't apply a move to the string t. The moves are applied to the string s one after another.Your task is to obtain the string t from the string s. Find any way to do it with at most 10^4 such moves.You do not have to minimize the number of moves, just find any sequence of moves of length 10^4 or less to transform s into t.InputThe first line of the input contains one integer n (1 \le n \le 50) — the length of strings s and t.The second line of the input contains the string s consisting of n lowercase Latin letters.The third line of the input contains the string t consisting of n lowercase Latin letters.OutputIf it is impossible to obtain the string t using moves, print "-1".Otherwise in the first line print one integer k — the number of moves to transform s to t. Note that k must be an integer number between 0 and 10^4 inclusive.In the second line print k integers c_j (1 \le c_j < n), where c_j means that on the j-th move you swap characters s_{c_j} and s_{c_j + 1}.If you do not need to apply any moves, print a single integer 0 in the first line and either leave the second line empty or do not print it at all.ExamplesInput6abcdefabdfecOutput43 5 4 5 Input4abcdaccdOutput-1NoteIn the first example the string s changes as follows: "abcdef" \rightarrow "abdcef" \rightarrow "abdcfe" \rightarrow "abdfce" \rightarrow "abdfec".In the second example there is no way to transform the string s into the string t through any allowed moves.
Input6abcdefabdfec
Output43 5 4 5
1 second
256 megabytes
['implementation', '*1200']
A. Points in Segmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 \le l_i \le r_i \le m) — coordinates of the left and of the right endpoints. Consider all integer points between 1 and m inclusive. Your task is to print all such points that don't belong to any segment. The point x belongs to the segment [l; r] if and only if l \le x \le r.InputThe first line of the input contains two integers n and m (1 \le n, m \le 100) — the number of segments and the upper bound for coordinates.The next n lines contain two integers each l_i and r_i (1 \le l_i \le r_i \le m) — the endpoints of the i-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that l_i=r_i, i.e. a segment can degenerate to a point.OutputIn the first line print one integer k — the number of points that don't belong to any segment.In the second line print exactly k integers in any order — the points that don't belong to any segment. All points you print should be distinct.If there are no such points at all, print a single integer 0 in the first line and either leave the second line empty or do not print it at all.ExamplesInput3 52 21 25 5Output23 4 Input1 71 7Output0NoteIn the first example the point 1 belongs to the second segment, the point 2 belongs to the first and the second segments and the point 5 belongs to the third segment. The points 3 and 4 do not belong to any segment.In the second example all the points from 1 to 7 belong to the first segment.
Input3 52 21 25 5
Output23 4
1 second
256 megabytes
['implementation', '*800']
B. Andtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.InputThe first line contains integers n and x (2 ≤ n ≤ 100 000, 1 ≤ x ≤ 100 000), number of elements in the array and the number to and with.The second line contains n integers ai (1 ≤ ai ≤ 100 000), the elements of the array.OutputPrint a single integer denoting the minimal number of operations to do, or -1, if it is impossible.ExamplesInput4 31 2 3 7Output1Input2 2281 1Output0Input3 71 2 3Output-1NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Input4 31 2 3 7
Output1
1 second
256 megabytes
['greedy', '*1200']
A. Piles With Stonestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a beautiful garden of stones in Innopolis.Its most beautiful place is the n piles with stones numbered from 1 to n.EJOI participants have visited this place twice. When they first visited it, the number of stones in piles was x_1, x_2, \ldots, x_n, correspondingly. One of the participants wrote down this sequence in a notebook. They visited it again the following day, and the number of stones in piles was equal to y_1, y_2, \ldots, y_n. One of the participants also wrote it down in a notebook.It is well known that every member of the EJOI jury during the night either sits in the room 108 or comes to the place with stones. Each jury member who comes there either takes one stone for himself or moves one stone from one pile to another. We can assume that there is an unlimited number of jury members. No one except the jury goes to the place with stones at night.Participants want to know whether their notes can be correct or they are sure to have made a mistake.InputThe first line of the input file contains a single integer n, the number of piles with stones in the garden (1 \leq n \leq 50).The second line contains n integers separated by spaces x_1, x_2, \ldots, x_n, the number of stones in piles recorded in the notebook when the participants came to the place with stones for the first time (0 \leq x_i \leq 1000).The third line contains n integers separated by spaces y_1, y_2, \ldots, y_n, the number of stones in piles recorded in the notebook when the participants came to the place with stones for the second time (0 \leq y_i \leq 1000).OutputIf the records can be consistent output "Yes", otherwise output "No" (quotes for clarity).ExamplesInput51 2 3 4 52 1 4 3 5OutputYesInput51 1 1 1 11 0 1 0 1OutputYesInput32 3 91 7 9OutputNoNoteIn the first example, the following could have happened during the night: one of the jury members moved one stone from the second pile to the first pile, and the other jury member moved one stone from the fourth pile to the third pile.In the second example, the jury took stones from the second and fourth piles.It can be proved that it is impossible for the jury members to move and took stones to convert the first array into the second array.
Input51 2 3 4 52 1 4 3 5
OutputYes
1 second
256 megabytes
['math', '*800']
F. Passportstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGleb is a famous competitive programming teacher from Innopolis. He is planning a trip to N programming camps in the nearest future. Each camp will be held in a different country. For each of them, Gleb needs to apply for a visa. For each of these trips Gleb knows three integers: the number of the first day of the trip si, the length of the trip in days leni, and the number of days ti this country's consulate will take to process a visa application and stick a visa in a passport. Gleb has P (1 ≤ P ≤ 2) valid passports and is able to decide which visa he wants to put in which passport.For each trip, Gleb will have a flight to that country early in the morning of the day si and will return back late in the evening of the day si + leni - 1.To apply for a visa on the day d, Gleb needs to be in Innopolis in the middle of this day. So he can't apply for a visa while he is on a trip, including the first and the last days. If a trip starts the next day after the end of the other one, Gleb can't apply for a visa between them as well. The earliest Gleb can apply for a visa is day 1.After applying for a visa of country i on day d, Gleb will get his passport back in the middle of the day d + ti. Consulates use delivery services, so Gleb can get his passport back even if he is not in Innopolis on this day. Gleb can apply for another visa on the same day he received his passport back, if he is in Innopolis this day. Gleb will not be able to start his trip on day si if he doesn't has a passport with a visa for the corresponding country in the morning of day si. In particular, the passport should not be in another country's consulate for visa processing.Help Gleb to decide which visas he needs to receive in which passport, and when he should apply for each visa. InputIn the first line of the input there are two integers N (1 ≤ N ≤ 22) and P (1 ≤ P ≤ 2)—the number of trips and the number of passports Gleb has, respectively.The next N lines describe Gleb's trips. Each line contains three positive integers si, leni, ti (1 ≤ si, leni, ti ≤ 109)—the first day of the trip, the length of the trip and number of days the consulate of this country needs to process a visa application. It is guaranteed that no two trips intersect.OutputIf it is impossible to get all visas on time, just print "NO" (quotes for clarity). Otherwise, print "YES" and N lines describing trips. For each trip, first print number of the passport Gleb should put this country's visa in, and then print number of the day he should apply for it. Print trips in the same order as they appear in the input. Days are numbered from 1, starting with tomorrow—the first day you can apply for a visa. Passports are numbered from 1 to P.If there are several possible answers, print any of them.ExamplesInput2 13 1 16 1 1OutputYES1 11 4Input3 113 2 27 3 119 3 4OutputYES1 101 11 2Input7 215 1 114 1 118 1 121 1 19 4 622 2 55 4 3OutputYES2 131 11 161 191 22 162 1Input3 17 3 113 2 319 3 4OutputNONoteExamples with answer "YES" are depicted below.Each cell of the stripe represents a single day. Rectangles represent trips, each trip starts in the morning and ends in the evening. Rectangles with angled corners represent visa applications. Each application starts in the middle of a day and ends ti days after. The trip and the visa application for the same country have the same color.In examples with two passports, visa applications and trips depicted above the time stripe are made using the first passport, visa applications and trips depicted below the time stripe are made using the second passport.Example 1: Example 2: Example 3:
Input2 13 1 16 1 1
OutputYES1 11 4
2 seconds
512 megabytes
['dp', 'implementation', '*3400']
E. Cycle sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n positive integers a_1, a_2, \dots, a_n. You can perform the following operation any number of times: select several distinct indices i_1, i_2, \dots, i_k (1 \le i_j \le n) and move the number standing at the position i_1 to the position i_2, the number at the position i_2 to the position i_3, ..., the number at the position i_k to the position i_1. In other words, the operation cyclically shifts elements: i_1 \to i_2 \to \ldots i_k \to i_1.For example, if you have n=4, an array a_1=10, a_2=20, a_3=30, a_4=40, and you choose three indices i_1=2, i_2=1, i_3=4, then the resulting array would become a_1=20, a_2=40, a_3=30, a_4=10.Your goal is to make the array sorted in non-decreasing order with the minimum number of operations. The additional constraint is that the sum of cycle lengths over all operations should be less than or equal to a number s. If it's impossible to sort the array while satisfying that constraint, your solution should report that as well.InputThe first line of the input contains two integers n and s (1 \leq n \leq 200\,000, 0 \leq s \leq 200\,000)—the number of elements in the array and the upper bound on the sum of cycle lengths.The next line contains n integers a_1, a_2, \dots, a_n—elements of the array (1 \leq a_i \leq 10^9).OutputIf it's impossible to sort the array using cycles of total length not exceeding s, print a single number "-1" (quotes for clarity).Otherwise, print a single number q— the minimum number of operations required to sort the array.On the next 2 \cdot q lines print descriptions of operations in the order they are applied to the array. The description of i-th operation begins with a single line containing one integer k (1 \le k \le n)—the length of the cycle (that is, the number of selected indices). The next line should contain k distinct integers i_1, i_2, \dots, i_k (1 \le i_j \le n)—the indices of the cycle.The sum of lengths of these cycles should be less than or equal to s, and the array should be sorted after applying these q operations.If there are several possible answers with the optimal q, print any of them.ExamplesInput5 53 2 3 1 1Output151 4 2 3 5 Input4 32 1 4 3Output-1Input2 02 2Output0NoteIn the first example, it's also possible to sort the array with two operations of total length 5: first apply the cycle 1 \to 4 \to 1 (of length 2), then apply the cycle 2 \to 3 \to 5 \to 2 (of length 3). However, it would be wrong answer as you're asked to use the minimal possible number of operations, which is 1 in that case.In the second example, it's possible to the sort the array with two cycles of total length 4 (1 \to 2 \to 1 and 3 \to 4 \to 3). However, it's impossible to achieve the same using shorter cycles, which is required by s=3.In the third example, the array is already sorted, so no operations are needed. Total length of empty set of cycles is considered to be zero.
Input5 53 2 3 1 1
Output151 4 2 3 5
2 seconds
256 megabytes
['dsu', 'math', '*3100']
D. AB-Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be minimized.InputThe first line contains a string s (1 ≤ |s| ≤ 2·105).The second line contains a string t (1 ≤ |t| ≤ 2·105).Here |s| and |t| denote the lengths of s and t, respectively. It is guaranteed that at least one of the strings contains at least one a letter and at least one of the strings contains at least one b letter.OutputThe first line should contain a single integer n (0 ≤ n ≤ 5·105) — the number of operations.Each of the next n lines should contain two space-separated integers ai, bi — the lengths of prefixes of s and t to swap, respectively.If there are multiple possible solutions, you can print any of them. It's guaranteed that a solution with given constraints exists.ExamplesInputbabbbOutput21 01 3InputbbbbaaaOutput0NoteIn the first example, you can solve the problem in two operations: Swap the prefix of the first string with length 1 and the prefix of the second string with length 0. After this swap, you'll have strings ab and bbb. Swap the prefix of the first string with length 1 and the prefix of the second string with length 3. After this swap, you'll have strings bbbb and a. In the second example, the strings are already appropriate, so no operations are needed.
Inputbabbb
Output21 01 3
1 second
256 megabytes
['constructive algorithms', 'strings', '*2800']
C. Hillstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputWelcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5, 4, 6, 2, then houses could be built on hills with heights 5 and 6 only.The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?However, the exact value of k is not yet determined, so could you please calculate answers for all k in range ? Here denotes n divided by two, rounded up.InputThe first line of input contains the only integer n (1 ≤ n ≤ 5000)—the number of the hills in the sequence.Second line contains n integers ai (1 ≤ ai ≤ 100 000)—the heights of the hills in the sequence.OutputPrint exactly numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses.ExamplesInput51 1 1 1 1Output1 2 2 Input31 2 3Output0 2 Input51 2 3 2 2Output0 1 3 NoteIn the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1, 0, 1, 1, 1 and the first hill becomes suitable for construction.In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1, 0, 1, 0, 1, and hills 1, 3, 5 become suitable for construction.
Input51 1 1 1 1
Output1 2 2
1 second
512 megabytes
['dp', '*1900']
B. Chemical tabletime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputInnopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2). Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.InputThe first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have.The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.OutputPrint the minimal number of elements to be purchased.ExamplesInput2 2 31 22 22 1Output0Input1 5 31 31 11 5Output2Input4 3 61 21 32 22 33 13 3Output1NoteFor each example you have a picture which illustrates it.The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.Test 1We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything. Test 2We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements. Test 3There are several possible solutions. One of them is illustrated below.Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.
Input2 2 31 22 22 1
Output0
1 second
512 megabytes
['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'matrices', '*1900']
A. Photo of The Skytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 \leq x \leq x_2 and y_1 \leq y \leq y_2, where (x_1, y_1) and (x_2, y_2) are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of n of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.InputThe first line of the input contains an only integer n (1 \leq n \leq 100\,000), the number of points in Pavel's records.The second line contains 2 \cdot n integers a_1, a_2, ..., a_{2 \cdot n} (1 \leq a_i \leq 10^9), coordinates, written by Pavel in some order.OutputPrint the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.ExamplesInput44 1 3 2 3 2 1 3Output1Input35 8 5 5 7 5Output0NoteIn the first sample stars in Pavel's records can be (1, 3), (1, 3), (2, 3), (2, 4). In this case, the minimal area of the rectangle, which contains all these points is 1 (rectangle with corners at (1, 3) and (2, 4)).
Input44 1 3 2 3 2 1 3
Output1
1 second
256 megabytes
['brute force', 'implementation', 'math', 'sortings', '*1500']
B. Planning The Expeditiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNatasha is planning an expedition to Mars for n people. One of the important tasks is to provide food for each participant.The warehouse has m daily food packages. Each package has some food type a_i.Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food.Formally, for each participant j Natasha should select his food type b_j and each day j-th participant will eat one food package of type b_j. The values b_j for different participants may be different.What is the maximum possible number of days the expedition can last, following the requirements above?InputThe first line contains two integers n and m (1 \le n \le 100, 1 \le m \le 100) — the number of the expedition participants and the number of the daily food packages available.The second line contains sequence of integers a_1, a_2, \dots, a_m (1 \le a_i \le 100), where a_i is the type of i-th food package.OutputPrint the single integer — the number of days the expedition can last. If it is not possible to plan the expedition for even one day, print 0.ExamplesInput4 101 5 2 1 1 1 2 5 7 2Output2Input100 11Output0Input2 55 4 3 2 1Output1Input3 942 42 42 42 42 42 42 42 42Output3NoteIn the first example, Natasha can assign type 1 food to the first participant, the same type 1 to the second, type 5 to the third and type 2 to the fourth. In this case, the expedition can last for 2 days, since each participant can get two food packages of his food type (there will be used 4 packages of type 1, two packages of type 2 and two packages of type 5).In the second example, there are 100 participants and only 1 food package. In this case, the expedition can't last even 1 day.
Input4 101 5 2 1 1 1 2 5 7 2
Output2
1 second
256 megabytes
['binary search', 'brute force', 'implementation', '*1200']
A. Stagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNatasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.There are n stages available. The rocket must contain exactly k of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — 26 tons.Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.InputThe first line of input contains two integers — n and k (1 \le k \le n \le 50) – the number of available stages and the number of stages to use in the rocket.The second line contains string s, which consists of exactly n lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.OutputPrint a single integer — the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.ExamplesInput5 3xyabdOutput29Input7 4problemOutput34Input2 2abOutput-1Input12 1abaabbaaabbbOutput1NoteIn the first example, the following rockets satisfy the condition: "adx" (weight is 1+4+24=29); "ady" (weight is 1+4+25=30); "bdx" (weight is 2+4+24=30); "bdy" (weight is 2+4+25=31).Rocket "adx" has the minimal weight, so the answer is 29.In the second example, target rocket is "belo". Its weight is 2+5+12+15=34.In the third example, n=k=2, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
Input5 3xyabd
Output29
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*900']
F. Treetime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Main Martian Tree grows on Mars. It is a binary tree (a rooted tree, with no more than two sons at each vertex) with n vertices, where the root vertex has the number 1. Its fruits are the Main Martian Fruits. It's summer now, so this tree does not have any fruit yet.Autumn is coming soon, and leaves and branches will begin to fall off the tree. It is clear, that if a vertex falls off the tree, then its entire subtree will fall off too. In addition, the root will remain on the tree. Formally: the tree will have some connected subset of vertices containing the root.After that, the fruits will grow on the tree (only at those vertices which remain). Exactly x fruits will grow in the root. The number of fruits in each remaining vertex will be not less than the sum of the numbers of fruits in the remaining sons of this vertex. It is allowed, that some vertices will not have any fruits.Natasha wondered how many tree configurations can be after the described changes. Since this number can be very large, output it modulo 998244353.Two configurations of the resulting tree are considered different if one of these two conditions is true: they have different subsets of remaining vertices; they have the same subset of remaining vertices, but there is a vertex in this subset where they have a different amount of fruits.InputThe first line contains two integers: n and x (1 \le n \le 10^5, 0 \le x \le 10^{18}) — the size of the tree and the number of fruits in the root.The i-th of the following (n-1) lines contains two integers a_i and b_i (1 \le a_i, b_i \le n) — vertices connected by the i-th edge of the tree.It is guaranteed that the input data describes a correct binary tree with the root at the vertex 1.OutputPrint one number — the number of configurations of the resulting tree modulo 998244353.ExamplesInput3 21 21 3Output13Input2 51 2Output7Input4 101 21 33 4Output441NoteConsider the first example. There are 2 fruits at the vertex 1. The following 13 options are possible: there is no vertex 2, there is no vertex 3; there is no vertex 2, there are no fruits at the vertex 3; there is no vertex 2, there is 1 fruit at the vertex 3; there is no vertex 2, there are 2 fruits at the vertex 3; there are no fruits at the vertex 2, there is no vertex 3; there are no fruits at the vertex 2, there are no fruits at the vertex 3; there are no fruits at the vertex 2, there is 1 fruit at the vertex 3; there are no fruits at the vertex 2, there are 2 fruits at the vertex 3; there is 1 fruit at the vertex 2, there is no vertex 3; there is 1 fruit at the vertex 2, there are no fruits at the vertex 3; there is 1 fruit at the vertex 2, there is 1 fruit at the vertex 3; there are 2 fruits at the vertex 2, there is no vertex 3; there are 2 fruits at the vertex 2, there are no fruits at the vertex 3. Consider the second example. There are 5 fruits at the vertex 1. The following 7 options are possible: there is no vertex 2; there are no fruits at the vertex 2; there is 1 fruit at the vertex 2; there are 2 fruits at the vertex 2; there are 3 fruits at the vertex 2; there are 4 fruits at the vertex 2; there are 5 fruits at the vertex 2.
Input3 21 21 3
Output13
7 seconds
256 megabytes
['fft', 'graphs', 'trees', '*3400']
E. Storetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNatasha was already going to fly back to Earth when she remembered that she needs to go to the Martian store to buy Martian souvenirs for her friends.It is known, that the Martian year lasts x_{max} months, month lasts y_{max} days, day lasts z_{max} seconds. Natasha also knows that this store works according to the following schedule: 2 months in a year were selected: x_l and x_r (1\le x_l\le x_r\le x_{max}), 2 days in a month: y_l and y_r (1\le y_l\le y_r\le y_{max}) and 2 seconds in a day: z_l and z_r (1\le z_l\le z_r\le z_{max}). The store works at all such moments (month x, day y, second z), when simultaneously x_l\le x\le x_r, y_l\le y\le y_r and z_l\le z\le z_r.Unfortunately, Natasha does not know the numbers x_l,x_r,y_l,y_r,z_l,z_r.One Martian told Natasha: "I went to this store (n+m) times. n times of them it was opened, and m times — closed." He also described his every trip to the store: the month, day, second of the trip and whether the store was open or closed at that moment.Natasha can go to the store k times. For each of them, determine whether the store at the time of the trip is open, closed, or this information is unknown.InputThe first line contains 6 integers x_{max}, y_{max}, z_{max}, n, m, k (1\le x_{max},y_{max},z_{max}\le 10^5, 1\le n\le 10^5, 0\le m\le 10^5, 1\le k\le 10^5) — number of months in a year, days in a month, seconds in a day, times when the store (according to a Martian) was opened, when it was closed and Natasha's queries.The i-th of the next n lines contains 3 integers x_i, y_i, z_i (1\le x_i\le x_{max}, 1\le y_i\le y_{max}, 1\le z_i\le z_{max}) — month, day and second of i-th time, when the store, according to the Martian, was opened.The i-th of the next m lines contains 3 integers x_i, y_i, z_i (1\le x_i\le x_{max}, 1\le y_i\le y_{max}, 1\le z_i\le z_{max}) — month, day and second of i-th time, when the store, according to the Martian, was closed.The i-th of the next k lines contains 3 integers x_i, y_i, z_i (1\le x_i\le x_{max}, 1\le y_i\le y_{max}, 1\le z_i\le z_{max}) — month, day and second of i-th Natasha's query.OutputIf the Martian was mistaken and his information about when the store is open and when it is closed is inconsistent, print a single line "INCORRECT" (without quotes).Otherwise, print the first line "CORRECT" (without quotes). Next output k lines: in i-th of them, output an answer to i-th Natasha's query: "OPEN" (without quotes), if the store was opened at the moment of this query, "CLOSED" (without quotes), if it was closed, or "UNKNOWN" (without quotes), if this information can not be determined on the basis of available data.ExamplesInput10 10 10 3 1 32 6 24 2 46 4 69 9 93 3 310 10 108 8 8OutputCORRECTOPENCLOSEDUNKNOWNInput10 10 10 1 1 12 5 72 5 78 9 10OutputINCORRECTNoteConsider the first test case.There are 10 months in a year, 10 days in a month, and 10 seconds in a day.The store was opened in 3 moments: month 2, day 6, second 2; month 4, day 2, second 4; month 6, day 4, second 6.The store was closed at the time: month 9, day 9, second 9.Queries: month 3, day 3, second 3 — open ("OPEN") (since the store opens no later than month 2, day 2, second 2 and closes no earlier than in month 6, day 6, second 6); month 10, day 10, second 10 — closed ("CLOSED") (since it is closed even in the month 9, day 9, second 9); month 8, day 8, second 8 — unknown ("UNKNOWN") (because the schedule in which the store is open at this moment exists, and the schedule in which the store is closed at this moment exists as well).In the second test case, the store was closed and opened at the same time — contradiction ("INCORRECT").
Input10 10 10 3 1 32 6 24 2 46 4 69 9 93 3 310 10 108 8 8
OutputCORRECTOPENCLOSEDUNKNOWN
2 seconds
256 megabytes
['data structures', '*2700']
D. Mars rovertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNatasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex 1, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output.There are four types of logical elements: AND (2 inputs), OR (2 inputs), XOR (2 inputs), NOT (1 input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input.For each input, determine what the output will be if Natasha changes this input.InputThe first line contains a single integer n (2 \le n \le 10^6) — the number of vertices in the graph (both inputs and elements).The i-th of the next n lines contains a description of i-th vertex: the first word "AND", "OR", "XOR", "NOT" or "IN" (means the input of the scheme) is the vertex type. If this vertex is "IN", then the value of this input follows (0 or 1), otherwise follow the indices of input vertices of this element: "AND", "OR", "XOR" have 2 inputs, whereas "NOT" has 1 input. The vertices are numbered from one.It is guaranteed that input data contains a correct logical scheme with an output produced by the vertex 1.OutputPrint a string of characters '0' and '1' (without quotes) — answers to the problem for each input in the ascending order of their vertex indices.ExampleInput10AND 9 4IN 1IN 1XOR 6 5AND 3 7IN 0NOT 10IN 1IN 1AND 2 8Output10110NoteThe original scheme from the example (before the input is changed):Green indicates bits '1', yellow indicates bits '0'.If Natasha changes the input bit 2 to 0, then the output will be 1.If Natasha changes the input bit 3 to 0, then the output will be 0.If Natasha changes the input bit 6 to 1, then the output will be 1.If Natasha changes the input bit 8 to 0, then the output will be 1.If Natasha changes the input bit 9 to 0, then the output will be 0.
Input10AND 9 4IN 1IN 1XOR 6 5AND 3 7IN 0NOT 10IN 1IN 1AND 2 8
Output10110
5 seconds
256 megabytes
['dfs and similar', 'graphs', 'implementation', 'trees', '*2000']
C. Bordertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAstronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.There are n banknote denominations on Mars: the value of i-th banknote is a_i. Natasha has an infinite number of banknotes of each denomination.Martians have k fingers on their hands, so they use a number system with base k. In addition, the Martians consider the digit d (in the number system with base k) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base k is d, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.Determine for which values d Natasha can make the Martians happy.Natasha can use only her banknotes. Martians don't give her change.InputThe first line contains two integers n and k (1 \le n \le 100\,000, 2 \le k \le 100\,000) — the number of denominations of banknotes and the base of the number system on Mars.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — denominations of banknotes on Mars.All numbers are given in decimal notation.OutputOn the first line output the number of values d for which Natasha can make the Martians happy.In the second line, output all these values in increasing order.Print all numbers in decimal notation.ExamplesInput2 812 20Output20 4 Input3 1010 20 30Output10 NoteConsider the first test case. It uses the octal number system.If you take one banknote with the value of 12, you will get 14_8 in octal system. The last digit is 4_8.If you take one banknote with the value of 12 and one banknote with the value of 20, the total value will be 32. In the octal system, it is 40_8. The last digit is 0_8.If you take two banknotes with the value of 20, the total value will be 40, this is 50_8 in the octal system. The last digit is 0_8.No other digits other than 0_8 and 4_8 can be obtained. Digits 0_8 and 4_8 could also be obtained in other ways.The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.
Input2 812 20
Output20 4
1 second
256 megabytes
['number theory', '*1800']
B. Rockettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 \le x \le m, where Natasha knows the number m. Besides, x and m are positive integers.Natasha can ask the rocket questions. Every question is an integer y (1 \le y \le m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, \ldots, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, \ldots, (n-1)-th, n-th, \ldots. If the current element is 1, the rocket answers correctly, if 0 — lies. Natasha doesn't know the sequence p, but she knows its length — n.You can ask the rocket no more than 60 questions.Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).InputThe first line contains two integers m and n (1 \le m \le 10^9, 1 \le n \le 30) — the maximum distance to Mars and the number of elements in the sequence p.InteractionYou can ask the rocket no more than 60 questions.To ask a question, print a number y (1\le y\le m) and an end-of-line character, then do the operation flush and read the answer to the question.If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.To flush the output buffer you can use (after printing a query and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages.HackingUse the following format for hacking:In the first line, print 3 integers m,n,x (1\le x\le m\le 10^9, 1\le n\le 30) — the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.In the second line, enter n numbers, each of which is equal to 0 or 1 — sequence p.The hacked solution will not have access to the number x and sequence p.ExampleInput5 21-1-110Output12453NoteIn the example, hacking would look like this:5 2 31 0This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...Really:on the first query (1) the correct answer is 1, the rocket answered correctly: 1;on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;on the third query (4) the correct answer is -1, the rocket answered correctly: -1;on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;on the fifth query (3) the correct and incorrect answer is 0.
Input5 21-1-110
Output12453
1 second
256 megabytes
['binary search', 'interactive', '*1800']
A. Flytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNatasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 \to 2 \to \ldots n \to 1.Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet \to take-off from the 1-st planet \to landing to the 2-nd planet \to 2-nd planet \to take-off from the 2-nd planet \to \ldots \to landing to the n-th planet \to the n-th planet \to take-off from the n-th planet \to landing to the 1-st planet \to the 1-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet. For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 \cdot 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.InputThe first line contains a single integer n (2 \le n \le 1000) — number of planets.The second line contains the only integer m (1 \le m \le 1000) — weight of the payload.The third line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.The fourth line contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 1000), where b_i is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.OutputIf Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}.ExamplesInput21211 87 5Output10.0000000000Input311 4 12 5 3Output-1Input624 6 3 3 5 62 6 3 6 5 3Output85.4800000000NoteLet's consider the first example.Initially, the mass of a rocket with fuel is 22 tons. At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons. During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Input21211 87 5
Output10.0000000000
1 second
256 megabytes
['binary search', 'math', '*1500']
G. Allowed Letterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp 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".InputThe 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.OutputIf 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.ExamplesInputbedefead52 e1 dc5 b7 ef6 efOutputdeadbeefInputabacaba0OutputaaaabbcInputfc21 cfab2 fOutputcf
Inputbedefead52 e1 dc5 b7 ef6 ef
Outputdeadbeef
2 seconds
256 megabytes
['bitmasks', 'flows', 'graph matchings', 'graphs', 'greedy', '*2400']
F. Dominant Indicestime limit per test4.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a rooted undirected tree consisting of n vertices. Vertex 1 is the root.Let's denote a depth array of vertex x as an infinite sequence [d_{x, 0}, d_{x, 1}, d_{x, 2}, \dots], where d_{x, i} is the number of vertices y such that both conditions hold: x is an ancestor of y; the simple path from x to y traverses exactly i edges. The dominant index of a depth array of vertex x (or, shortly, the dominant index of vertex x) is an index j such that: for every k < j, d_{x, k} < d_{x, j}; for every k > j, d_{x, k} \le d_{x, j}. For every vertex in the tree calculate its dominant index.InputThe first line contains one integer n (1 \le n \le 10^6) — the number of vertices in a tree.Then n - 1 lines follow, each containing two integers x and y (1 \le x, y \le n, x \ne y). This line denotes an edge of the tree.It is guaranteed that these edges form a tree.OutputOutput n numbers. i-th number should be equal to the dominant index of vertex i.ExamplesInput41 22 33 4Output0000Input41 21 31 4Output1000Input41 22 32 4Output2100
Input41 22 33 4
Output0000
4.5 seconds
512 megabytes
['data structures', 'dsu', 'trees', '*2300']
E. Intercity Travellingtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is n km. Let's say that Moscow is situated at the point with coordinate 0 km, and Saratov — at coordinate n km.Driving for a long time may be really difficult. Formally, if Leha has already covered i kilometers since he stopped to have a rest, he considers the difficulty of covering (i + 1)-th kilometer as a_{i + 1}. It is guaranteed that for every i \in [1, n - 1] a_i \le a_{i + 1}. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from 1 to n - 1 may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty a_1, the kilometer after it — difficulty a_2, and so on.For example, if n = 5 and there is a rest site in coordinate 2, the difficulty of journey will be 2a_1 + 2a_2 + a_3: the first kilometer will have difficulty a_1, the second one — a_2, then Leha will have a rest, and the third kilometer will have difficulty a_1, the fourth — a_2, and the last one — a_3. Another example: if n = 7 and there are rest sites in coordinates 1 and 5, the difficulty of Leha's journey is 3a_1 + 2a_2 + a_3 + a_4.Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are 2^{n - 1} different distributions of rest sites (two distributions are different if there exists some point x such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate p — the expected value of difficulty of his journey.Obviously, p \cdot 2^{n - 1} is an integer number. You have to calculate it modulo 998244353.InputThe first line contains one number n (1 \le n \le 10^6) — the distance from Moscow to Saratov.The second line contains n integer numbers a_1, a_2, ..., a_n (1 \le a_1 \le a_2 \le \dots \le a_n \le 10^6), where a_i is the difficulty of i-th kilometer after Leha has rested.OutputPrint one number — p \cdot 2^{n - 1}, taken modulo 998244353.ExamplesInput21 2Output5Input41 3 3 7Output60
Input21 2
Output5
1.5 seconds
256 megabytes
['combinatorics', 'math', 'probabilities', '*2000']
D. Relatively Prime Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an undirected graph G = (V, E) relatively prime if and only if for each edge (v, u) \in E  GCD(v, u) = 1 (the greatest common divisor of v and u is 1). If there is no edge between some pair of vertices v and u then the value of GCD(v, u) doesn't matter. The vertices are numbered from 1 to |V|.Construct a relatively prime graph with n vertices and m edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.InputThe only line contains two integers n and m (1 \le n, m \le 10^5) — the number of vertices and the number of edges.OutputIf there exists no valid graph with the given number of vertices and edges then output "Impossible".Otherwise print the answer in the following format:The first line should contain the word "Possible".The i-th of the next m lines should contain the i-th edge (v_i, u_i) of the resulting graph (1 \le v_i, u_i \le n, v_i \neq u_i). For each pair (v, u) there can be no more pairs (v, u) or (u, v). The vertices are numbered from 1 to n.If there are multiple answers then print any of them.ExamplesInput5 6OutputPossible2 53 25 13 44 15 4Input6 12OutputImpossibleNoteHere is the representation of the graph from the first example:
Input5 6
OutputPossible2 53 25 13 44 15 4
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'graphs', 'greedy', 'math', '*1700']
C. Annoying Presenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice got an array of length n as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.Bob has chosen m changes of the following form. For some integer numbers x and d, he chooses an arbitrary position i (1 \le i \le n) and for every j \in [1, n] adds x + d \cdot dist(i, j) to the value of the j-th cell. dist(i, j) is the distance between positions i and j (i.e. dist(i, j) = |i - j|, where |x| is an absolute value of x).For example, if Alice currently has an array [2, 1, 2, 2] and Bob chooses position 3 for x = -1 and d = 2 then the array will become [2 - 1 + 2 \cdot 2,~1 - 1 + 2 \cdot 1,~2 - 1 + 2 \cdot 0,~2 - 1 + 2 \cdot 1] = [5, 2, 1, 3]. Note that Bob can't choose position i outside of the array (that is, smaller than 1 or greater than n).Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.What is the maximum arithmetic mean value Bob can achieve?InputThe first line contains two integers n and m (1 \le n, m \le 10^5) — the number of elements of the array and the number of changes.Each of the next m lines contains two integers x_i and d_i (-10^3 \le x_i, d_i \le 10^3) — the parameters for the i-th change.OutputPrint the maximal average arithmetic mean of the elements Bob can achieve.Your answer is considered correct if its absolute or relative error doesn't exceed 10^{-6}.ExamplesInput2 3-1 30 0-1 -4Output-2.500000000000000Input3 20 25 0Output7.000000000000000
Input2 3-1 30 0-1 -4
Output-2.500000000000000
2 seconds
256 megabytes
['greedy', 'math', '*1700']
B. Minimum Ternary Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a ternary string (it is a string which consists only of characters '0', '1' and '2').You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).For example, for string "010210" we can perform the following moves: "010210" \rightarrow "100210"; "010210" \rightarrow "001210"; "010210" \rightarrow "010120"; "010210" \rightarrow "010201". Note than you cannot swap "02" \rightarrow "20" and vice versa. You cannot perform any other operations with the given string excluding described above.You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 \le i \le |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.InputThe first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).OutputPrint a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).ExamplesInput100210Output001120Input11222121Output11112222Input20Output20
Input100210
Output001120
1 second
256 megabytes
['greedy', 'implementation', '*1400']
A. Game Shoppingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMaxim wants to buy some games at the local game shop. There are n games in the shop, the i-th game costs c_i.Maxim has a wallet which can be represented as an array of integers. His wallet contains m bills, the j-th bill has value a_j.Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.When Maxim stands at the position i in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the i-th game using this bill. After Maxim tried to buy the n-th game, he leaves the shop.Maxim buys the i-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the i-th game. If he successfully buys the i-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.For example, for array c = [2, 4, 5, 2, 4] and array a = [5, 3, 4, 6] the following process takes place: Maxim buys the first game using the first bill (its value is 5), the bill disappears, after that the second bill (with value 3) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because c_2 > a_2, the same with the third game, then he buys the fourth game using the bill of value a_2 (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value a_3.Your task is to get the number of games Maxim will buy.InputThe first line of the input contains two integers n and m (1 \le n, m \le 1000) — the number of games and the number of bills in Maxim's wallet.The second line of the input contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le 1000), where c_i is the cost of the i-th game.The third line of the input contains m integers a_1, a_2, \dots, a_m (1 \le a_j \le 1000), where a_j is the value of the j-th bill from the Maxim's wallet.OutputPrint a single integer — the number of games Maxim will buy.ExamplesInput5 42 4 5 2 45 3 4 6Output3Input5 220 40 50 20 4019 20Output0Input6 44 8 15 16 23 421000 1000 1000 1000Output4NoteThe first example is described in the problem statement.In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.
Input5 42 4 5 2 45 3 4 6
Output3
1 second
256 megabytes
['implementation', '*800']
B. Turn the Rectanglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such). InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of rectangles.Each of the next n lines contains two integers w_i and h_i (1 \leq w_i, h_i \leq 10^9) — the width and the height of the i-th rectangle.OutputPrint "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".You can print each letter in any case (upper or lower).ExamplesInput33 44 63 5OutputYESInput23 45 5OutputNONoteIn the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].In the second test, there is no way the second rectangle will be not higher than the first one.
Input33 44 63 5
OutputYES
2 seconds
256 megabytes
['greedy', 'sortings', '*1000']
A. Romajitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.Help Vitya find out if a word s is Berlanese.InputThe first line of the input contains the string s consisting of |s| (1\leq |s|\leq 100) lowercase Latin letters.OutputPrint "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO".You can print each letter in any case (upper or lower).ExamplesInputsumimasenOutputYESInputninjaOutputYESInputcodeforcesOutputNONoteIn the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese.In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese.
Inputsumimasen
OutputYES
2 seconds
256 megabytes
['implementation', 'strings', '*900']
E. Mini Metrotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a simplified version of a "Mini Metro" game, there is only one subway line, and all the trains go in the same direction. There are n stations on the line, a_i people are waiting for the train at the i-th station at the beginning of the game. The game starts at the beginning of the 0-th hour. At the end of each hour (couple minutes before the end of the hour), b_i people instantly arrive to the i-th station. If at some moment, the number of people at the i-th station is larger than c_i, you lose.A player has several trains which he can appoint to some hours. The capacity of each train is k passengers. In the middle of the appointed hour, the train goes from the 1-st to the n-th station, taking as many people at each station as it can accommodate. A train can not take people from the i-th station if there are people at the i-1-th station.If multiple trains are appointed to the same hour, their capacities are being added up and they are moving together.The player wants to stay in the game for t hours. Determine the minimum number of trains he will need for it.InputThe first line contains three integers n, t, and k (1 \leq n, t \leq 200, 1 \leq k \leq 10^9) — the number of stations on the line, hours we want to survive, and capacity of each train respectively.Each of the next n lines contains three integers a_i, b_i, and c_i (0 \leq a_i, b_i \leq c_i \leq 10^9) — number of people at the i-th station in the beginning of the game, number of people arriving to i-th station in the end of each hour and maximum number of people at the i-th station allowed respectively.OutputOutput a single integer number — the answer to the problem.ExamplesInput3 3 102 4 103 3 94 2 8Output2Input4 10 51 1 11 0 10 5 82 7 100Output12NoteLet's look at the sample. There are three stations, on the first, there are initially 2 people, 3 people on the second, and 4 people on the third. Maximal capacities of the stations are 10, 9, and 8 respectively.One of the winning strategies is to appoint two trains to the first and the third hours. Then on the first hour, the train takes all of the people from the stations, and at the end of the hour, 4 people arrive at the first station, 3 on the second, and 2 on the third.In the second hour there are no trains appointed, and at the end of it, the same amount of people are arriving again.In the third hour, the train first takes 8 people from the first station, and when it arrives at the second station, it takes only 2 people because it can accommodate no more than 10 people. Then it passes by the third station because it is already full. After it, people arrive at the stations once more, and the game ends.As there was no such moment when the number of people at a station exceeded maximal capacity, we won using two trains.
Input3 3 102 4 103 3 94 2 8
Output2
2 seconds
256 megabytes
['dp', '*3400']
D. Antstime limit per test3 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputThere is a tree with n vertices. There are also m ants living on it. Each ant has its own color. The i-th ant has two favorite pairs of vertices: (a_i, b_i) and (c_i, d_i). You need to tell if it is possible to paint the edges of the tree in m colors so that every ant will be able to walk between vertices from one of its favorite pairs using only edges of his color; if it is possible, you need to print which pair every ant should use.InputThe first line contains a single integer n (2 \leq n \leq 10^5) — the number of vertices.Each of the next n-1 lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n), meaning that there is an edge between vertices u_i and v_i.The next line contains a single integer m (1 \leq m \leq 10^4) — the number of ants.Each of the next m lines contains four integers a_i, b_i, c_i, and d_i (1 \leq a_i, b_i, c_i, d_i \leq n, a_i \neq b_i, c_i \neq d_i), meaning that pairs (a_i, b_i) and (c_i, d_i) are favorite for the i-th ant.OutputPrint "NO" (without quotes) if the wanted painting is impossible.Otherwise, print "YES" (without quotes). Print m lines. On the i-th line, print 1 if the i-th ant will use the first pair and 2 otherwise. If there are multiple answers, print any.ExamplesInput61 23 14 15 26 232 6 3 41 6 6 51 4 5 2OutputYES212Input51 21 31 41 522 3 4 53 4 5 2OutputNONoteIn the sample, the second and the third edge should be painted in the first color, the first and the fifth should be painted in the second color, and the fourth should be painted in the third color.
Input61 23 14 15 26 232 6 3 41 6 6 51 4 5 2
OutputYES212
3 seconds
768 megabytes
['2-sat', 'data structures', 'trees', '*3200']
C. Guess two numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Vasya and Vitya play a game. Vasya thought of two integers a and b from 1 to n and Vitya tries to guess them. Each round he tells Vasya two numbers x and y from 1 to n. If both x=a and y=b then Vitya wins. Else Vasya must say one of the three phrases: x is less than a; y is less than b; x is greater than a or y is greater than b. Vasya can't lie, but if multiple phrases are true, he may choose any of them. For example, if Vasya thought of numbers 2 and 4, then he answers with the phrase 3 to a query (3, 4), and he can answer with the phrase 1 or phrase 3 to a query (1, 5).Help Vitya win in no more than 600 rounds. InputThe first line contains a single integer n (1 \leq n \leq 10^{18}) — the upper limit of the numbers.InteractionFirst, you need to read the number n, after that you can make queries.To make a query, print two integers: x and y (1 \leq x, y \leq n), then flush the output.After each query, read a single integer ans (0 \leq ans \leq 3).If ans > 0, then it is the number of the phrase said by Vasya.If ans = 0, it means that you win and your program should terminate.If you make more than 600 queries or make an incorrect query, you will get Wrong Answer.Your solution will get Idleness Limit Exceeded, if you don't print anything or forget to flush the output.To flush you need to do the following right after printing a query and a line end: fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; For other languages see documentation. Hacks formatFor hacks, use the following format:In the first line, print a single integer n (1 \leq n \leq 10^{18}) — the upper limit of the numbers.In the second line, print two integers a and b (1 \leq a, b \leq n) — the numbers which Vasya thought of.In the third line, print a single integer m (1 \leq m \leq 10^5) — the number of instructions for the interactor.In each of the next m lines, print five integers: x_i, y_i, r^{12}_i, r^{13}_i, and r^{23}_i (1 \leq x_i, y_i \leq n), where r^{ST}_i equals to either number S or number T.While answering the query x\,\, y, the interactor finds a number i from 1 to n with the minimal value |x-x_i| + |y-y_i|. If multiple numbers can be chosen, the least i is preferred. Then the interactor answers to the query, but if there are two phrases S and T that can be given, then r^{ST}_i is chosen.For example, the sample test data file contains the following: 52 422 5 1 1 24 1 2 3 3ExampleInput533210Output4 33 43 31 52 4NoteLet's analyze the sample test. The chosen numbers are 2 and 4. The interactor was given two instructions.For the query (4, 3), it can return 2 or 3. Out of the two instructions the second one is chosen, so the interactor returns a^{23}_2=3.For the query (3, 4), it can return only 3.For the query (3, 3), it can return 2 or 3. Out of the two instructions the first one is chosen (since in case of equal values, the least number is preferred), so the interactor returns a^{23}_1=2.For the query (1, 5), it can return 1 or 3. Out of the two instructions the first one is chosen, so the interactor returns a^{13}_1=1.In the fifth query (2, 4), the numbers are guessed correctly, the player wins.
Input533210
Output4 33 43 31 52 4
2 seconds
256 megabytes
['binary search', 'interactive', '*3000']
B. Pave the Parallelepipedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular parallelepiped with sides of positive integer lengths A, B and C. Find the number of different groups of three integers (a, b, c) such that 1\leq a\leq b\leq c and parallelepiped A\times B\times C can be paved with parallelepipeds a\times b\times c. Note, that all small parallelepipeds have to be rotated in the same direction.For example, parallelepiped 1\times 5\times 6 can be divided into parallelepipeds 1\times 3\times 5, but can not be divided into parallelepipeds 1\times 2\times 3.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases.Each of the next t lines contains three integers A, B and C (1 \leq A, B, C \leq 10^5) — the sizes of the parallelepiped.OutputFor each test case, print the number of different groups of three points that satisfy all given conditions.ExampleInput41 1 11 6 12 2 2100 100 100Output144165NoteIn the first test case, rectangular parallelepiped (1, 1, 1) can be only divided into rectangular parallelepiped with sizes (1, 1, 1).In the second test case, rectangular parallelepiped (1, 6, 1) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 1, 3) and (1, 1, 6).In the third test case, rectangular parallelepiped (2, 2, 2) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 2, 2) and (2, 2, 2).
Input41 1 11 6 12 2 2100 100 100
Output144165
2 seconds
256 megabytes
['bitmasks', 'brute force', 'combinatorics', 'math', 'number theory', '*2400']
A. Reorder the Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.For instance, if we are given an array [10, 20, 30, 40], we can permute it so that it becomes [20, 40, 10, 30]. Then on the first and the second positions the integers became larger (20>10, 40>20) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals 2. Read the note for the first example, there is one more demonstrative test case.Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the elements of the array.OutputPrint a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.ExamplesInput710 1 1 1 5 5 3Output4Input51 1 1 1 1Output0NoteIn the first sample, one of the best permutations is [1, 5, 5, 3, 10, 1, 1]. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
Input710 1 1 1 5 5 3
Output4
2 seconds
256 megabytes
['combinatorics', 'data structures', 'math', 'sortings', 'two pointers', '*1300']
F. Xor-Pathstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a rectangular grid of size n \times m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints: You can move to the right or to the bottom only. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j). The target cell can't be outside of the grid. The xor of all the numbers on the path from the cell (1, 1) to the cell (n, m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal). Find the number of such paths in the given grid.InputThe first line of the input contains three integers n, m and k (1 \le n, m \le 20, 0 \le k \le 10^{18}) — the height and the width of the grid, and the number k.The next n lines contain m integers each, the j-th element in the i-th line is a_{i, j} (0 \le a_{i, j} \le 10^{18}).OutputPrint one integer — the number of paths from (1, 1) to (n, m) with xor sum equal to k.ExamplesInput3 3 112 1 57 10 012 6 4Output3Input3 4 21 3 3 30 3 3 23 0 1 1Output5Input3 4 10000000000000000001 3 3 30 3 3 23 0 1 1Output0NoteAll the paths from the first example: (1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3); (1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3); (1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3). All the paths from the second example: (1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4); (1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4); (1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (3, 4); (1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4); (1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4).
Input3 3 112 1 57 10 012 6 4
Output3
3 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'meet-in-the-middle', '*2100']
E. Military Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you will have to help Berland army with organizing their command delivery system.There are n officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer a is the direct superior of officer b, then we also can say that officer b is a direct subordinate of officer a.Officer x is considered to be a subordinate (direct or indirect) of officer y if one of the following conditions holds: officer y is the direct superior of officer x; the direct superior of officer x is a subordinate of officer y. For example, on the picture below the subordinates of the officer 3 are: 5, 6, 7, 8, 9.The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.Formally, let's represent Berland army as a tree consisting of n vertices, in which vertex u corresponds to officer u. The parent of vertex u corresponds to the direct superior of officer u. The root (which has index 1) corresponds to the commander of the army.Berland War Ministry has ordered you to give answers on q queries, the i-th query is given as (u_i, k_i), where u_i is some officer, and k_i is a positive integer.To process the i-th query imagine how a command from u_i spreads to the subordinates of u_i. Typical DFS (depth first search) algorithm is used here.Suppose the current officer is a and he spreads a command. Officer a chooses b — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then a chooses the one having minimal index. Officer a gives a command to officer b. Afterwards, b uses exactly the same algorithm to spread the command to its subtree. After b finishes spreading the command, officer a chooses the next direct subordinate again (using the same strategy). When officer a cannot choose any direct subordinate who still hasn't received this command, officer a finishes spreading the command.Let's look at the following example: If officer 1 spreads a command, officers receive it in the following order: [1, 2, 3, 5 ,6, 8, 7, 9, 4].If officer 3 spreads a command, officers receive it in the following order: [3, 5, 6, 8, 7, 9].If officer 7 spreads a command, officers receive it in the following order: [7, 9].If officer 9 spreads a command, officers receive it in the following order: [9].To answer the i-th query (u_i, k_i), construct a sequence which describes the order in which officers will receive the command if the u_i-th officer spreads it. Return the k_i-th element of the constructed list or -1 if there are fewer than k_i elements in it.You should process queries independently. A query doesn't affect the following queries.InputThe first line of the input contains two integers n and q (2 \le n \le 2 \cdot 10^5, 1 \le q \le 2 \cdot 10^5) — the number of officers in Berland army and the number of queries.The second line of the input contains n - 1 integers p_2, p_3, \dots, p_n (1 \le p_i < i), where p_i is the index of the direct superior of the officer having the index i. The commander has index 1 and doesn't have any superiors.The next q lines describe the queries. The i-th query is given as a pair (u_i, k_i) (1 \le u_i, k_i \le n), where u_i is the index of the officer which starts spreading a command, and k_i is the index of the required officer in the command spreading sequence.OutputPrint q numbers, where the i-th number is the officer at the position k_i in the list which describes the order in which officers will receive the command if it starts spreading from officer u_i. Print "-1" if the number of officers which receive the command is less than k_i.You should process queries independently. They do not affect each other.ExampleInput9 61 1 1 3 5 3 5 73 11 53 47 31 81 9Output368-194
Input9 61 1 1 3 5 3 5 73 11 53 47 31 81 9
Output368-194
3 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*1600']
D. Two Strings Swapstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive. You are allowed to do the following changes: Choose any index i (1 \le i \le n) and swap characters a_i and b_i; Choose any index i (1 \le i \le n) and swap characters a_i and a_{n - i + 1}; Choose any index i (1 \le i \le n) and swap characters b_i and b_{n - i + 1}. Note that if n is odd, you are formally allowed to swap a_{\lceil\frac{n}{2}\rceil} with a_{\lceil\frac{n}{2}\rceil} (and the same with the string b) but this move is useless. Also you can swap two equal characters but this operation is useless as well.You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.In one preprocess move you can replace a character in a with another character. In other words, in a single preprocess move you can choose any index i (1 \le i \le n), any character c and set a_i := c.Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings a and b equal by applying some number of changes described in the list above.Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string b or make any preprocess moves after the first change is made.InputThe first line of the input contains one integer n (1 \le n \le 10^5) — the length of strings a and b.The second line contains the string a consisting of exactly n lowercase English letters.The third line contains the string b consisting of exactly n lowercase English letters.OutputPrint a single integer — the minimum number of preprocess moves to apply before changes, so that it is possible to make the string a equal to string b with a sequence of changes from the list above.ExamplesInput7abacababacabaaOutput4Input5zcabddbaczOutput0NoteIn the first example preprocess moves are as follows: a_1 := 'b', a_3 := 'c', a_4 := 'a' and a_5:='b'. Afterwards, a = "bbcabba". Then we can obtain equal strings by the following sequence of changes: swap(a_2, b_2) and swap(a_2, a_6). There is no way to use fewer than 4 preprocess moves before a sequence of changes to make string equal, so the answer in this example is 4.In the second example no preprocess moves are required. We can use the following sequence of changes to make a and b equal: swap(b_1, b_5), swap(a_2, a_4).
Input7abacababacabaa
Output4
2 seconds
256 megabytes
['implementation', '*1700']
C. Three Parts of the Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array d_1, d_2, \dots, d_n consisting of n integer numbers.Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be sum_1, the sum of elements of the second part be sum_2 and the sum of elements of the third part be sum_3. Among all possible ways to split the array you have to choose a way such that sum_1 = sum_3 and sum_1 is maximum possible.More formally, if the first part of the array contains a elements, the second part of the array contains b elements and the third part contains c elements, then:sum_1 = \sum\limits_{1 \le i \le a}d_i, sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i, sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.The sum of an empty array is 0.Your task is to find a way to split the array such that sum_1 = sum_3 and sum_1 is maximum possible.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in the array d.The second line of the input contains n integers d_1, d_2, \dots, d_n (1 \le d_i \le 10^9) — the elements of the array d.OutputPrint a single integer — the maximum possible value of sum_1, considering that the condition sum_1 = sum_3 must be met.Obviously, at least one valid way to split the array exists (use a=c=0 and b=n).ExamplesInput51 3 1 1 4Output5Input51 3 2 1 4Output4Input34 1 2Output0NoteIn the first example there is only one possible splitting which maximizes sum_1: [1, 3, 1], [~], [1, 4].In the second example the only way to have sum_1=4 is: [1, 3], [2, 1], [4].In the third example there is only one way to split the array: [~], [4, 1, 2], [~].
Input51 3 1 1 4
Output5
1 second
256 megabytes
['binary search', 'data structures', 'two pointers', '*1200']
B. Polycarp's Practicetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, \dots, a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all n problems in exactly k days.Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in k days he will solve all the n problems.The profit of the j-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the j-th day (i.e. if he solves problems with indices from l to r during a day, then the profit of the day is \max\limits_{l \le i \le r}a_i). The total profit of his practice is the sum of the profits over all k days of his practice.You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all n problems between k days satisfying the conditions above in such a way, that the total profit is maximum.For example, if n = 8, k = 3 and a = [5, 4, 2, 6, 5, 1, 9, 2], one of the possible distributions with maximum total profit is: [5, 4, 2], [6, 5], [1, 9, 2]. Here the total profit equals 5 + 6 + 9 = 20.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 2000) — the number of problems and the number of days, respectively.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2000) — difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).OutputIn the first line of the output print the maximum possible total profit.In the second line print exactly k positive integers t_1, t_2, \dots, t_k (t_1 + t_2 + \dots + t_k must equal n), where t_j means the number of problems Polycarp will solve during the j-th day in order to achieve the maximum possible total profit of his practice.If there are many possible answers, you may print any of them.ExamplesInput8 35 4 2 6 5 1 9 2Output203 2 3Input5 11 1 1 1 1Output15Input4 21 2000 2000 2Output40002 2NoteThe first example is described in the problem statement.In the second example there is only one possible distribution.In the third example the best answer is to distribute problems in the following way: [1, 2000], [2000, 2]. The total profit of this distribution is 2000 + 2000 = 4000.
Input8 35 4 2 6 5 1 9 2
Output203 2 3
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*1200']
A. Adjacent Replacementstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka got an integer array a of length n as a birthday present (what a surprise!).Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: Replace each occurrence of 1 in the array a with 2; Replace each occurrence of 2 in the array a with 1; Replace each occurrence of 3 in the array a with 4; Replace each occurrence of 4 in the array a with 3; Replace each occurrence of 5 in the array a with 6; Replace each occurrence of 6 in the array a with 5; \dots Replace each occurrence of 10^9 - 1 in the array a with 10^9; Replace each occurrence of 10^9 in the array a with 10^9 - 1. Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers (2i - 1, 2i) for each i \in\{1, 2, \ldots, 5 \cdot 10^8\} as described above.For example, for the array a = [1, 2, 4, 5, 10], the following sequence of arrays represents the algorithm: [1, 2, 4, 5, 10] \rightarrow (replace all occurrences of 1 with 2) \rightarrow [2, 2, 4, 5, 10] \rightarrow (replace all occurrences of 2 with 1) \rightarrow [1, 1, 4, 5, 10] \rightarrow (replace all occurrences of 3 with 4) \rightarrow [1, 1, 4, 5, 10] \rightarrow (replace all occurrences of 4 with 3) \rightarrow [1, 1, 3, 5, 10] \rightarrow (replace all occurrences of 5 with 6) \rightarrow [1, 1, 3, 6, 10] \rightarrow (replace all occurrences of 6 with 5) \rightarrow [1, 1, 3, 5, 10] \rightarrow \dots \rightarrow [1, 1, 3, 5, 10] \rightarrow (replace all occurrences of 10 with 9) \rightarrow [1, 1, 3, 5, 9]. The later steps of the algorithm do not change the array.Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.InputThe first line of the input contains one integer number n (1 \le n \le 1000) — the number of elements in Mishka's birthday present (surprisingly, an array).The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the elements of the array.OutputPrint n integers — b_1, b_2, \dots, b_n, where b_i is the final value of the i-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array a. Note that you cannot change the order of elements in the array.ExamplesInput51 2 4 5 10Output1 1 3 5 9Input1010000 10 50605065 1 5 89 5 999999999 60506056 1000000000Output9999 9 50605065 1 5 89 5 999999999 60506055 999999999NoteThe first example is described in the problem statement.
Input51 2 4 5 10
Output1 1 3 5 9
1 second
256 megabytes
['implementation', '*800']
F. Berland and the Shortest Pathstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that: it is possible to travel from the capital to any other city along the n-1 chosen roads, if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + \dots + d_n is minimized (i.e. as minimal as possible). In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.InputThe first line of the input contains integers n, m and k (2 \le n \le 2\cdot10^5, n-1 \le m \le 2\cdot10^5, 1 \le k \le 2\cdot10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m \cdot k \le 10^6.The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 \le a_i, b_i \le n, a_i \ne b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.OutputPrint t (1 \le t \le k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.Since it is guaranteed that m \cdot k \le 10^6, the total length of all the t lines will not exceed 10^6.If there are several answers, output any of them.ExamplesInput4 4 31 22 31 44 3Output211101011Input4 6 31 22 31 44 32 41 3Output1101001Input5 6 21 21 32 42 53 43 5Output2111100110110
Input4 4 31 22 31 44 3
Output211101011
5 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', 'shortest paths', '*2100']
E2. Median on Segments (General Case Edition)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer sequence a_1, a_2, \dots, a_n.Find the number of pairs of indices (l, r) (1 \le l \le r \le n) such that the value of median of a_l, a_{l+1}, \dots, a_r is exactly the given number m.The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if a=[4, 2, 7, 5] then its median is 4 since after sorting the sequence, it will look like [2, 4, 5, 7] and the left of two middle elements is equal to 4. The median of [7, 1, 2, 9, 6] equals 6 since after sorting, the value 6 will be in the middle of the sequence.Write a program to find the number of pairs of indices (l, r) (1 \le l \le r \le n) such that the value of median of a_l, a_{l+1}, \dots, a_r is exactly the given number m.InputThe first line contains integers n and m (1 \le n,m \le 2\cdot10^5) — the length of the given sequence and the required value of the median.The second line contains an integer sequence a_1, a_2, \dots, a_n (1 \le a_i \le 2\cdot10^5).OutputPrint the required number.ExamplesInput5 41 4 5 60 4Output8Input3 11 1 1Output6Input15 21 2 3 1 2 3 1 2 3 1 2 3 1 2 3Output97NoteIn the first example, the suitable pairs of indices are: (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 5), (4, 5) and (5, 5).
Input5 41 4 5 60 4
Output8
3 seconds
256 megabytes
['sortings', '*2400']
E1. Median on Segments (Permutations Edition)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \dots, p_n. A permutation of length n is a sequence such that each integer between 1 and n occurs exactly once in the sequence.Find the number of pairs of indices (l, r) (1 \le l \le r \le n) such that the value of the median of p_l, p_{l+1}, \dots, p_r is exactly the given number m.The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if a=[4, 2, 7, 5] then its median is 4 since after sorting the sequence, it will look like [2, 4, 5, 7] and the left of two middle elements is equal to 4. The median of [7, 1, 2, 9, 6] equals 6 since after sorting, the value 6 will be in the middle of the sequence.Write a program to find the number of pairs of indices (l, r) (1 \le l \le r \le n) such that the value of the median of p_l, p_{l+1}, \dots, p_r is exactly the given number m.InputThe first line contains integers n and m (1 \le n \le 2\cdot10^5, 1 \le m \le n) — the length of the given sequence and the required value of the median.The second line contains a permutation p_1, p_2, \dots, p_n (1 \le p_i \le n). Each integer between 1 and n occurs in p exactly once.OutputPrint the required number.ExamplesInput5 42 4 5 3 1Output4Input5 51 2 3 4 5Output1Input15 81 15 2 14 3 13 4 8 12 5 11 6 10 7 9Output48NoteIn the first example, the suitable pairs of indices are: (1, 3), (2, 2), (2, 3) and (2, 4).
Input5 42 4 5 3 1
Output4
3 seconds
256 megabytes
['sortings', '*1800']
D. Polycarp and Div 3time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp likes numbers that are divisible by 3.He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by 3.For example, if the original number is s=3121, then Polycarp can cut it into three parts with two cuts: 3|1|21. As a result, he will get two numbers that are divisible by 3.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by 3 that Polycarp can obtain?InputThe first line of the input contains a positive integer s. The number of digits of the number s is between 1 and 2\cdot10^5, inclusive. The first (leftmost) digit is not equal to 0.OutputPrint the maximum number of numbers divisible by 3 that Polycarp can get by making vertical cuts in the given number s.ExamplesInput3121Output2Input6Output1Input1000000000000000000000000000000000Output33Input201920181Output4NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by 3.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and 33 digits 0. Each of the 33 digits 0 forms a number that is divisible by 3.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers 0, 9, 201 and 81 are divisible by 3.
Input3121
Output2
3 seconds
256 megabytes
['dp', 'greedy', 'number theory', '*1500']
C. Summarize to the Power of Twotime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence a_1, a_2, \dots, a_n is called good if, for each element a_i, there exists an element a_j (i \ne j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d).For example, the following sequences are good: [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum is a power of two. Similarly, such an element can be found for a_2 and a_3), [1, 1, 1, 1023], [7, 39, 89, 25, 89], []. Note that, by definition, an empty sequence (with a length of 0) is good.For example, the following sequences are not good: [16] (for a_1=16, it is impossible to find another element a_j such that their sum is a power of two), [4, 16] (for a_1=4, it is impossible to find another element a_j such that their sum is a power of two), [1, 3, 2, 8, 8, 8] (for a_3=2, it is impossible to find another element a_j such that their sum is a power of two). You are given a sequence a_1, a_2, \dots, a_n. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.InputThe first line contains the integer n (1 \le n \le 120000) — the length of the given sequence.The second line contains the sequence of integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).OutputPrint the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all n elements, make it empty, and thus get a good sequence.ExamplesInput64 7 1 5 4 9Output1Input51 2 3 4 5Output2Input116Output1Input41 1 1 1023Output0NoteIn the first example, it is enough to delete one element a_4=5. The remaining elements form the sequence [4, 7, 1, 4, 9], which is good.
Input64 7 1 5 4 9
Output1
3 seconds
256 megabytes
['brute force', 'greedy', 'implementation', '*1300']
B. Delete from the Lefttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty.For example: by applying a move to the string "where", the result is the string "here", by applying a move to the string "a", the result is an empty string "". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.Write a program that finds the minimum number of moves to make two given strings s and t equal.InputThe first line of the input contains s. In the second line of the input contains t. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and 2\cdot10^5, inclusive.OutputOutput the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.ExamplesInputtestwestOutput2InputcodeforcesyesOutput9InputtestyesOutput7InputbabOutput1NoteIn the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".In the second example, the move should be applied to the string "codeforces" 8 times. As a result, the string becomes "codeforces" \to "es". The move should be applied to the string "yes" once. The result is the same string "yes" \to "es".In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.In the fourth example, the first character of the second string should be deleted.
Inputtestwest
Output2
1 second
256 megabytes
['brute force', 'implementation', 'strings', '*900']
A. Tanya and Stairwaystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps, she will pronounce the numbers 1, 2, 3, 1, 2, 3, 4.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.InputThe first line contains n (1 \le n \le 1000) — the total number of numbers pronounced by Tanya.The second line contains integers a_1, a_2, \dots, a_n (1 \le a_i \le 1000) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with x steps, she will pronounce the numbers 1, 2, \dots, x in that order.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.OutputIn the first line, output t — the number of stairways that Tanya climbed. In the second line, output t numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.ExamplesInput71 2 3 1 2 3 4Output23 4 Input41 1 1 1Output41 1 1 1 Input51 2 3 4 5Output15 Input51 2 1 2 1Output32 2 1
Input71 2 3 1 2 3 4
Output23 4
1 second
256 megabytes
['implementation', '*800']
F. Sonya and Bitwise ORtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSonya has an array a_1, a_2, \ldots, a_n consisting of n integers and also one non-negative integer x. She has to perform m queries of two types: 1 i y: replace i-th element by value y, i.e. to perform an operation a_{i} := y; 2 l r: find the number of pairs (L, R) that l\leq L\leq R\leq r and bitwise OR of all integers in the range [L, R] is at least x (note that x is a constant for all queries). Can you help Sonya perform all her queries?Bitwise OR is a binary operation on a pair of non-negative integers. To calculate the bitwise OR of two numbers, you need to write both numbers in binary notation. The result is a number, in binary, which contains a one in each digit if there is a one in the binary notation of at least one of the two numbers. For example, 10 OR 19 = 1010_2 OR 10011_2 = 11011_2 = 27.InputThe first line contains three integers n, m, and x (1\leq n, m\leq 10^5, 0\leq x<2^{20}) — the number of numbers, the number of queries, and the constant for all queries.The second line contains n integers a_1, a_2, \ldots, a_n (0\leq a_i<2^{20}) — numbers of the array.The following m lines each describe an query. A line has one of the following formats: 1 i y (1\leq i\leq n, 0\leq y<2^{20}), meaning that you have to replace a_{i} by y; 2 l r (1\leq l\leq r\leq n), meaning that you have to find the number of subarrays on the segment from l to r that the bitwise OR of all numbers there is at least x. OutputFor each query of type 2, print the number of subarrays such that the bitwise OR of all the numbers in the range is at least x.ExamplesInput4 8 70 3 6 12 1 42 3 41 1 72 1 42 1 32 1 11 3 02 1 4Output517414Input5 5 76 0 3 15 22 1 51 4 42 1 52 3 52 1 4Output9724NoteIn the first example, there are an array [0, 3, 6, 1] and queries: on the segment [1\ldots4], you can choose pairs (1, 3), (1, 4), (2, 3), (2, 4), and (3, 4); on the segment [3\ldots4], you can choose pair (3, 4); the first number is being replacing by 7, after this operation, the array will consist of [7, 3, 6, 1]; on the segment [1\ldots4], you can choose pairs (1, 1), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), and (3, 4); on the segment [1\ldots3], you can choose pairs (1, 1), (1, 2), (1, 3), and (2, 3); on the segment [1\ldots1], you can choose pair (1, 1); the third number is being replacing by 0, after this operation, the array will consist of [7, 3, 0, 1]; on the segment [1\ldots4], you can choose pairs (1, 1), (1, 2), (1, 3), and (1, 4). In the second example, there are an array [6, 0, 3, 15, 2] are queries: on the segment [1\ldots5], you can choose pairs (1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), and (4, 5); the fourth number is being replacing by 4, after this operation, the array will consist of [6, 0, 3, 4, 2]; on the segment [1\ldots5], you can choose pairs (1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 4), and (3, 5); on the segment [3\ldots5], you can choose pairs (3, 4) and (3, 5); on the segment [1\ldots4], you can choose pairs (1, 3), (1, 4), (2, 4), and (3, 4).
Input4 8 70 3 6 12 1 42 3 41 1 72 1 42 1 32 1 11 3 02 1 4
Output517414
4 seconds
512 megabytes
['bitmasks', 'data structures', 'divide and conquer', '*2600']
E. Sonya and Ice Creamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSonya likes ice cream very much. She eats it even during programming competitions. That is why the girl decided that she wants to open her own ice cream shops.Sonya lives in a city with n junctions and n-1 streets between them. All streets are two-way and connect two junctions. It is possible to travel from any junction to any other using one or more streets. City Hall allows opening shops only on junctions. The girl cannot open shops in the middle of streets. Sonya has exactly k friends whom she can trust. If she opens a shop, one of her friends has to work there and not to allow anybody to eat an ice cream not paying for it. Since Sonya does not want to skip an important competition, she will not work in shops personally.Sonya wants all her ice cream shops to form a simple path of the length r (1 \le r \le k), i.e. to be located in different junctions f_1, f_2, \dots, f_r and there is street between f_i and f_{i+1} for each i from 1 to r-1.The girl takes care of potential buyers, so she also wants to minimize the maximum distance between the junctions to the nearest ice cream shop. The distance between two junctions a and b is equal to the sum of all the street lengths that you need to pass to get from the junction a to the junction b. So Sonya wants to minimize\max_{a} \min_{1 \le i \le r} d_{a,f_i}where a takes a value of all possible n junctions, f_i — the junction where the i-th Sonya's shop is located, and d_{x,y} — the distance between the junctions x and y.Sonya is not sure that she can find the optimal shops locations, that is why she is asking you to help her to open not more than k shops that will form a simple path and the maximum distance between any junction and the nearest shop would be minimal. InputThe first line contains two integers n and k (1\leq k\leq n\leq 10^5) — the number of junctions and friends respectively.Each of the next n-1 lines contains three integers u_i, v_i, and d_i (1\leq u_i, v_i\leq n, v_i\neq u_i, 1\leq d\leq 10^4) — junctions that are connected by a street and the length of this street. It is guaranteed that each pair of junctions is connected by at most one street. It is guaranteed that you can get from any junctions to any other.OutputPrint one number — the minimal possible maximum distance that you need to pass to get from any junction to the nearest ice cream shop. Sonya's shops must form a simple path and the number of shops must be at most k.ExamplesInput6 21 2 32 3 44 5 24 6 32 4 6Output4Input10 31 2 55 7 23 2 610 6 33 8 16 4 24 1 66 9 45 2 5Output7NoteIn the first example, you can choose the path 2-4, so the answer will be 4. The first example. In the second example, you can choose the path 4-1-2, so the answer will be 7. The second example.
Input6 21 2 32 3 44 5 24 6 32 4 6
Output4
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'greedy', 'shortest paths', 'trees', '*2400']
D. Sonya and Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince Sonya has just learned the basics of matrices, she decided to play with them a little bit.Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3. Example of a rhombic matrix. Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.She drew a n\times m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of n\cdot m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.Write a program that finds such an n\times m rhombic matrix whose elements are the same as the elements in the sequence in some order.InputThe first line contains a single integer t (1\leq t\leq 10^6) — the number of cells in the matrix.The second line contains t integers a_1, a_2, \ldots, a_t (0\leq a_i< t) — the values in the cells in arbitrary order.OutputIn the first line, print two positive integers n and m (n \times m = t) — the size of the matrix.In the second line, print two integers x and y (1\leq x\leq n, 1\leq y\leq m) — the row number and the column number where the cell with 0 is located.If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.ExamplesInput201 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4Output4 52 2Input182 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1Output3 62 3Input62 1 0 2 1 2Output-1NoteYou can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5\times 4 matrix with zero at (4, 2).In the second example, there is a 3\times 6 matrix, where the zero is located at (2, 3) there.In the third example, a solution does not exist.
Input201 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output4 52 2
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', '*2300']
C. Sonya and Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.Sonya has drawn n numbers in a row, a_i is located in the i-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position.Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one.For example, if the numbers [1, 5, 4, 1, 3] are written, and Sonya gives the number 1 to the first robot and the number 4 to the second one, the first robot will stop in the 1-st position while the second one in the 3-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number 4 to the first robot and the number 5 to the second one, they will meet since the first robot will stop in the 3-rd position while the second one is in the 2-nd position.Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot.Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs (p, q), where she will give p to the first robot and q to the second one. Pairs (p_i, q_i) and (p_j, q_j) are different if p_i\neq p_j or q_i\neq q_j.Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet.InputThe first line contains a single integer n (1\leq n\leq 10^5) — the number of numbers in a row.The second line contains n integers a_1, a_2, \ldots, a_n (1\leq a_i\leq 10^5) — the numbers in a row.OutputPrint one number — the number of possible pairs that Sonya can give to robots so that they will not meet.ExamplesInput51 5 4 1 3Output9Input71 2 1 1 1 3 2Output7NoteIn the first example, Sonya can give pairs (1, 1), (1, 3), (1, 4), (1, 5), (4, 1), (4, 3), (5, 1), (5, 3), and (5, 4).In the second example, Sonya can give pairs (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), and (3, 2).
Input51 5 4 1 3
Output9
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1400']
B. Sonya and Exhibitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should contain exactly one flower: a rose or a lily.She knows that exactly m people will visit this exhibition. The i-th visitor will visit all flowers from l_i to r_i inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.InputThe first line contains two integers n and m (1\leq n, m\leq 10^3) — the number of flowers and visitors respectively.Each of the next m lines contains two integers l_i and r_i (1\leq l_i\leq r_i\leq n), meaning that i-th visitor will visit all flowers from l_i to r_i inclusive.OutputPrint the string of n characters. The i-th symbol should be «0» if you want to put a rose in the i-th position, otherwise «1» if you want to put a lily.If there are multiple answers, print any.ExamplesInput5 31 32 42 5Output01100Input6 35 61 44 6Output110010NoteIn the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions; in the segment [1\ldots3], there are one rose and two lilies, so the beauty is equal to 1\cdot 2=2; in the segment [2\ldots4], there are one rose and two lilies, so the beauty is equal to 1\cdot 2=2; in the segment [2\ldots5], there are two roses and two lilies, so the beauty is equal to 2\cdot 2=4. The total beauty is equal to 2+2+4=8.In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions; in the segment [5\ldots6], there are one rose and one lily, so the beauty is equal to 1\cdot 1=1; in the segment [1\ldots4], there are two roses and two lilies, so the beauty is equal to 2\cdot 2=4; in the segment [4\ldots6], there are two roses and one lily, so the beauty is equal to 2\cdot 1=2. The total beauty is equal to 1+4+2=7.
Input5 31 32 42 5
Output01100
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*1300']