contest_id
int32
1
2.13k
index
stringclasses
62 values
problem_id
stringlengths
2
6
title
stringlengths
0
67
rating
int32
0
3.5k
tags
stringlengths
0
139
statement
stringlengths
0
6.96k
input_spec
stringlengths
0
2.32k
output_spec
stringlengths
0
1.52k
note
stringlengths
0
5.06k
sample_tests
stringlengths
0
1.02k
difficulty_category
stringclasses
6 values
tag_count
int8
0
11
statement_length
int32
0
6.96k
input_spec_length
int16
0
2.32k
output_spec_length
int16
0
1.52k
contest_year
int16
0
21
374
C
374C
C. Inna and Dima
1,900
dfs and similar; dp; graphs; implementation
Inna and Dima bought a table of size n Γ— m in the shop. Each cell of the table contains a single letter: ""D"", ""I"", ""M"", ""A"".Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: initially, Inna chooses some cell of the table where letter ""D"" is written; then Inna can move to some side-adjacent table cell that contains letter ""I""; then from this cell she can go to one of the side-adjacent table cells that contains the written letter ""M""; then she can go to a side-adjacent cell that contains letter ""A"". Then Inna assumes that she has gone through her sweetheart's name; Inna's next move can be going to one of the side-adjacent table cells that contains letter ""D"" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter ""D"" she always goes to the letter ""I"", from the letter ""I"" she always goes the to letter ""M"", from the letter ""M"" she always goes to the letter ""A"", and from the letter ""A"" she always goes to the letter ""D"". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 103). Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: ""D"", ""I"", ""M"", ""A"". Note that it is not guaranteed that the table contains at least one letter ""D"".
If Inna cannot go through name DIMA once, print on a single line ""Poor Dima!"" without the quotes. If there is the infinite number of names DIMA Inna can go through, print ""Poor Inna!"" without the quotes. Otherwise print a single integer β€” the maximum number of times Inna can go through name DIMA.
Notes to the samples:In the first test sample, Inna cannot go through name DIMA a single time.In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner.In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.
Input: 1 2DI | Output: Poor Dima!
Hard
4
1,377
331
301
3
1,872
G
1872G
G. Replace With Product
2,000
brute force; greedy; math
Given an array \(a\) of \(n\) positive integers. You need to perform the following operation exactly once: Choose \(2\) integers \(l\) and \(r\) (\(1 \le l \le r \le n\)) and replace the subarray \(a[l \ldots r]\) with the single element: the product of all elements in the subarray \((a_l \cdot \ldots \cdot a_r)\).For example, if an operation with parameters \(l = 2, r = 4\) is applied to the array \([5, 4, 3, 2, 1]\), the array will turn into \([5, 24, 1]\).Your task is to maximize the sum of the array after applying this operation. Find the optimal subarray to apply this operation.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. This is followed by the description of the test cases.The first line of each test case contains a single number \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the length of the array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)).It is guaranteed that the sum of the values of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output \(2\) integers \(l\) and \(r\) (\(1 \le l \le r \le n\)) β€” the boundaries of the subarray to be replaced with the product.If there are multiple solutions, output any of them.
In the first test case, after applying the operation with parameters \(l = 2, r = 4\), the array \([1, 3, 1, 3]\) turns into \([1, 9]\), with a sum equal to \(10\). It is easy to see that by replacing any other segment with a product, the sum will be less than \(10\).In the second test case, after applying the operation with parameters \(l = 3, r = 4\), the array \([1, 1, 2, 3]\) turns into \([1, 1, 6]\), with a sum equal to \(8\). It is easy to see that by replacing any other segment with a product, the sum will be less than \(8\).In the third test case, it will be optimal to choose any operation with \(l = r\), then the sum of the array will remain \(5\), and when applying any other operation, the sum of the array will decrease.
Input: 941 3 1 341 1 2 351 1 1 1 1510 1 10 1 101122 232 1 242 1 1 362 1 2 1 1 3 | Output: 2 4 3 4 1 1 1 5 1 1 1 2 2 2 4 4 1 6
Hard
3
590
536
201
18
1,940
B
1940B
0
*special; constructive algorithms; implementation; sortings
Beginner
4
0
0
0
19
1,313
C2
1313C2
C2. Skyscrapers (hard version)
1,900
data structures; dp; greedy
This is a harder version of the problem. In this version \(n \le 500\,000\)The outskirts of the capital are being actively built up in Berland. The company ""Kernel Panic"" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought \(n\) plots along the highway and is preparing to build \(n\) skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from \(1\) to \(n\). Then if the skyscraper on the \(i\)-th plot has \(a_i\) floors, it must hold that \(a_i\) is at most \(m_i\) (\(1 \le a_i \le m_i\)). Also there mustn't be integers \(j\) and \(k\) such that \(j < i < k\) and \(a_j > a_i < a_k\). Plots \(j\) and \(k\) are not required to be adjacent to \(i\).The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
The first line contains a single integer \(n\) (\(1 \leq n \leq 500\,000\)) β€” the number of plots.The second line contains the integers \(m_1, m_2, \ldots, m_n\) (\(1 \leq m_i \leq 10^9\)) β€” the limit on the number of floors for every possible number of floors for a skyscraper on each plot.
Print \(n\) integers \(a_i\) β€” the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.
In the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer \([10, 6, 6]\) is optimal. Note that the answer of \([6, 6, 8]\) also satisfies all restrictions, but is not optimal.
Input: 51 2 3 2 1 | Output: 1 2 3 2 1
Hard
3
1,509
291
253
13
130
G
130G
G. CAPS LOCK ON
1,700
*special
You are given a string which consists of letters and other characters. Convert it to uppercase, i.e., replace all lowercase letters with corresponding uppercase ones. Keep the rest of characters unchanged.
The only line of input contains a string between 1 and 100 characters long. Each character of the string has ASCII-code between 33 (exclamation mark) and 126 (tilde), inclusive.
Output the given string, converted to uppercase.
Input: cOdEfOrCeS | Output: CODEFORCES
Medium
1
205
177
48
1
2,131
F
2131F
F. Unjust Binary Life
0
binary search; data structures; greedy; greedy; math; sortings; two pointers
Yuri is given two binary strings \(a\) and \(b\), both of which are of length \(n\). The two strings dynamically define an \(n \times n\) grid. Let \((i, j)\) denote the cell in the \(i\)-th row and \(j\)-th column. The initial value of cell \((i, j)\) has the value of \(a_i \oplus b_j\), where \(\oplus\) denotes the bitwise XOR operation. .Yuri's journey always starts at cell \((1, 1)\). From a cell \((i, j)\), she can only move down to \((i + 1, j)\) or right to \((i, j + 1)\). Her journey is possible if there exists a valid path such that all cells on the path, including \((1, 1)\), have a value of 0.Before her departure, she can do the following operation for any number of times: Choose one index \(1 \le i \le n\), and flip the value of either \(a_i\) or \(b_i\) (\(0\) becomes \(1\), and \(1\) becomes \(0\)). The grid will also change accordingly. Let \(f(x, y)\) denote the minimum required operations so that Yuri can make her journey to the cell \((x,y)\). You must determine the sum of \(f(x, y)\) over all \(1 \leq x, y \leq n\).Note that each of these \(n^2\) cases is independent, meaning you need to assume the grid is in its original state in each case (i.e., no actual operations are performed).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)).The second line of each test case contains a binary string \(a\) (\(|a| = n\), \(a_i \in \{0, 1\}\)).The third line of each test case contains a binary string \(b\) (\(|b| = n\), \(b_i \in \{0, 1\}\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output one integer β€” the sum of minimum operations over all possible cells.
In the first test case, the \(2 \times 2\) grid is shown below.$$$\( 11 \\ 11 \)\(In the initial state, Yuri cannot reach any cell.Yuri can flip \)a_1\( so that the grid becomes:\)\( 00 \\ 11 \)\(and Yuri can travel to cells \)(1,1)\( and \)(1,2)\(.On the other hand, Yuri can flip \)b_1\( so that the grid becomes:\)\( 01 \\ 01 \)\(and Yuri can travel to cells \)(1,1)\( and \)(2,1)\(.To move to the cell \)(2,2)\(, it can be shown that she must perform at least two operations. For example, she can flip both \)a_1\( and \)a_2\( so that the grid becomes:\)\( 00 \\ 00 \)\(Therefore, the answer is \)1+1+1+2=5$$$.
Input: 32110020101410101101 | Output: 5 4 24
Beginner
7
1,221
546
95
21
838
C
838C
C. Future Failure
2,800
dp; games
Alice and Bob are playing a game with a string of characters, with Alice going first. The string consists n characters, each of which is one of the first k letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if there is at least one character). In addition, their resulting word cannot have appeared before throughout the entire game. The player unable to make a valid move loses the game.Given n, k, p, find the number of words with exactly n characters consisting of the first k letters of the alphabet such that Alice will win if both Alice and Bob play optimally. Return this number modulo the prime number p.
The first line of input will contain three integers n, k, p (1 ≀ n ≀ 250 000, 1 ≀ k ≀ 26, 108 ≀ p ≀ 109 + 100, p will be prime).
Print a single integer, the number of winning words for Alice, modulo p.
There are 14 strings that that Alice can win with. For example, some strings are ""bbaa"" and ""baaa"". Alice will lose on strings like ""aaaa"" or ""bbbb"".
Input: 4 2 100000007 | Output: 14
Master
2
716
128
72
8
372
E
372E
E. Drawing Circles is Fun
3,000
combinatorics; geometry
There are a set of points S on the plane. This set doesn't contain the origin O(0, 0), and for each two distinct points in the set A and B, the triangle OAB has strictly positive area.Consider a set of pairs of points (P1, P2), (P3, P4), ..., (P2k - 1, P2k). We'll call the set good if and only if: k β‰₯ 2. All Pi are distinct, and each Pi is an element of S. For any two pairs (P2i - 1, P2i) and (P2j - 1, P2j), the circumcircles of triangles OP2i - 1P2j - 1 and OP2iP2j have a single common point, and the circumcircle of triangles OP2i - 1P2j and OP2iP2j - 1 have a single common point. Calculate the number of good sets of pairs modulo 1000000007 (109 + 7).
The first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of points in S. Each of the next n lines contains four integers ai, bi, ci, di (0 ≀ |ai|, |ci| ≀ 50; 1 ≀ bi, di ≀ 50; (ai, ci) β‰  (0, 0)). These integers represent a point .No two points coincide.
Print a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).
Input: 10-46 46 0 360 20 -24 48-50 50 -49 49-20 50 8 40-15 30 14 284 10 -4 56 15 8 10-20 50 -3 154 34 -16 3416 34 2 17 | Output: 2
Master
2
660
266
79
3
1,209
E2
1209E2
E2. Rotate Columns (hard version)
2,500
bitmasks; dp; greedy; sortings
This is a harder version of the problem. The difference is only in constraints.You are given a rectangular \(n \times m\) matrix \(a\). In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for \(i\)-th row it is equal \(r_i\). What is the maximal possible value of \(r_1+r_2+\ldots+r_n\)?
The first line contains an integer \(t\) (\(1 \le t \le 40\)), the number of test cases in the input.The first line of each test case contains integers \(n\) and \(m\) (\(1 \le n \le 12\), \(1 \le m \le 2000\)) β€” the number of rows and the number of columns in the given matrix \(a\). Each of the following \(n\) lines contains \(m\) integers, the elements of \(a\) (\(1 \le a_{i, j} \le 10^5\)).
Print \(t\) integers: answers for all test cases in the order they are given in the input.
In the first test case you can shift the third column down by one, this way there will be \(r_1 = 5\) and \(r_2 = 7\).In the second case you can don't rotate anything at all, this way there will be \(r_1 = r_2 = 10\) and \(r_3 = 9\).
Input: 3 2 3 2 5 7 4 2 4 3 6 4 1 5 2 10 4 8 6 6 4 9 10 5 4 9 5 8 7 3 3 9 9 9 1 1 1 1 1 1 | Output: 12 29 27
Expert
4
556
396
90
12
262
A
262A
A. Roma and Lucky Numbers
800
implementation
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.
The first line contains two integers n, k (1 ≀ n, k ≀ 100). The second line contains n integers ai (1 ≀ ai ≀ 109) β€” the numbers that Roma has. The numbers in the lines are separated by single spaces.
In a single line print a single integer β€” the answer to the problem.
In the first sample all numbers contain at most four lucky digits, so the answer is 3.In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2.
Input: 3 41 2 4 | Output: 3
Beginner
1
443
199
68
2
1,702
C
1702C
C. Train and Queries
1,100
data structures; greedy
Along the railroad there are stations indexed from \(1\) to \(10^9\). An express train always travels along a route consisting of \(n\) stations with indices \(u_1, u_2, \dots, u_n\), where (\(1 \le u_i \le 10^9\)). The train travels along the route from left to right. It starts at station \(u_1\), then stops at station \(u_2\), then at \(u_3\), and so on. Station \(u_n\) β€” the terminus.It is possible that the train will visit the same station more than once. That is, there may be duplicates among the values \(u_1, u_2, \dots, u_n\).You are given \(k\) queries, each containing two different integers \(a_j\) and \(b_j\) (\(1 \le a_j, b_j \le 10^9\)). For each query, determine whether it is possible to travel by train from the station with index \(a_j\) to the station with index \(b_j\).For example, let the train route consist of \(6\) of stations with indices [\(3, 7, 1, 5, 1, 4\)] and give \(3\) of the following queries: \(a_1 = 3\), \(b_1 = 5\)It is possible to travel from station \(3\) to station \(5\) by taking a section of the route consisting of stations [\(3, 7, 1, 5\)]. Answer: YES. \(a_2 = 1\), \(b_2 = 7\)You cannot travel from station \(1\) to station \(7\) because the train cannot travel in the opposite direction. Answer: NO. \(a_3 = 3\), \(b_3 = 10\)It is not possible to travel from station \(3\) to station \(10\) because station \(10\) is not part of the train's route. Answer: NO.
The first line of the input contains an integer \(t\) (\(1 \le t \le 10^4\)) β€”the number of test cases in the test.The descriptions of the test cases follow.The first line of each test case is empty.The second line of each test case contains two integers: \(n\) and \(k\) (\(1 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5\)) β€”the number of stations the train route consists of and the number of queries.The third line of each test case contains exactly \(n\) integers \(u_1, u_2, \dots, u_n\) (\(1 \le u_i \le 10^9\)). The values \(u_1, u_2, \dots, u_n\) are not necessarily different.The following \(k\) lines contain two different integers \(a_j\) and \(b_j\) (\(1 \le a_j, b_j \le 10^9\)) describing the query with index \(j\).It is guaranteed that the sum of \(n\) values over all test cases in the test does not exceed \(2 \cdot 10^5\). Similarly, it is guaranteed that the sum of \(k\) values over all test cases in the test also does not exceed \(2 \cdot 10^5\)
For each test case, output on a separate line: YES, if you can travel by train from the station with index \(a_j\) to the station with index \(b_j\) NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
The first test case is explained in the problem statement.
Input: 36 33 7 1 5 1 43 51 73 103 31 2 12 11 24 57 52 1 1 1 2 4 41 31 42 14 11 2 | Output: YES NO NO YES YES NO NO YES YES NO YES
Easy
2
1,415
972
288
17
2,087
A
2087A
A. Password Generator
0
*special
Monocarp is going to register on the Codeforces website, but he can't come up with a sufficiently secure password. The requirements that his password must meet are as follows: the password must consist of digits, as well as uppercase and lowercase letters of the Latin alphabet; there must be exactly \(a\) digits, exactly \(b\) uppercase letters, and exactly \(c\) lowercase letters; for security, no two adjacent characters in the password should be the same. The lowercase and uppercase versions of the same letter are considered different characters. Write a program that generates a password that meets all the requirements.
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.Each test case consists of one line containing three integers \(a\), \(b\), and \(c\) (\(1 \le a, b, c \le 10\)).
For each test case, output one line containing any suitable password. It can be shown that there is always at least one password that meets the requirements.
Input: 22 1 63 3 6 | Output: abaCaba42 b3sTpAs5w0rD
Beginner
1
629
210
157
20
362
E
362E
E. Petya and Pipes
2,300
flows; graphs; shortest paths
A little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in.The Berland capital has n water tanks numbered from 1 to n. These tanks are connected by unidirectional pipes in some manner. Any pair of water tanks is connected by at most one pipe in each direction. Each pipe has a strictly positive integer width. Width determines the number of liters of water per a unit of time this pipe can transport. The water goes to the city from the main water tank (its number is 1). The water must go through some pipe path and get to the sewer tank with cleaning system (its number is n). Petya wants to increase the width of some subset of pipes by at most k units in total so that the width of each pipe remains integer. Help him determine the maximum amount of water that can be transmitted per a unit of time from the main tank to the sewer tank after such operation is completed.
The first line contains two space-separated integers n and k (2 ≀ n ≀ 50, 0 ≀ k ≀ 1000). Then follow n lines, each line contains n integers separated by single spaces. The i + 1-th row and j-th column contain number cij β€” the width of the pipe that goes from tank i to tank j (0 ≀ cij ≀ 106, cii = 0). If cij = 0, then there is no pipe from tank i to tank j.
Print a single integer β€” the maximum amount of water that can be transmitted from the main tank to the sewer tank per a unit of time.
In the first test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 7 units.In the second test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 4 units, from the 2nd to the 3rd water tank by 3 units, from the 3rd to the 4th water tank by 2 units and from the 4th to 5th water tank by 1 unit.
Input: 5 70 1 0 2 00 0 4 10 00 0 0 0 50 0 0 0 100 0 0 0 0 | Output: 10
Expert
3
1,099
358
133
3
457
A
457A
A. Golden System
1,700
math; meet-in-the-middle
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it ""golden system"". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.
Input consists of two lines β€” one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.
Print "">"" if the first number is larger, ""<"" if it is smaller and ""="" if they are equal.
In the first example first number equals to , while second number is approximately 1.6180339882 + 1.618033988 + 1 β‰ˆ 5.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is β‰ˆ 2.618.
Input: 1000111 | Output: <
Medium
2
762
174
94
4
101
C
101C
C. Vectors
2,000
implementation; math
At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector А: Turn the vector by 90 degrees clockwise. Add to the vector a certain vector C.Operations could be performed in any order any number of times.Can Gerald cope with the task?
The first line contains integers x1 ΠΈ y1 β€” the coordinates of the vector A ( - 108 ≀ x1, y1 ≀ 108). The second and the third line contain in the similar manner vectors B and C (their coordinates are integers; their absolute value does not exceed 108).
Print ""YES"" (without the quotes) if it is possible to get vector B using the given operations. Otherwise print ""NO"" (without the quotes).
Input: 0 01 10 1 | Output: YES
Hard
2
336
251
141
1
926
J
926J
J. Segments
2,100
data structures
There is a straight line colored in white. n black segments are added on it one by one.After each segment is added, determine the number of connected components of black segments (i. e. the number of black segments in the union of the black segments). In particular, if one segment ends in a point x, and another segment starts in the point x, these two segments belong to the same connected component.
The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of segments.The i-th of the next n lines contains two integers li and ri (1 ≀ li < ri ≀ 109) β€” the coordinates of the left and the right ends of the i-th segment. The segments are listed in the order they are added on the white line.
Print n integers β€” the number of connected components of black segments after each segment is added.
In the first example there are two components after the addition of the first two segments, because these segments do not intersect. The third added segment intersects the left segment and touches the right segment at the point 4 (these segments belong to the same component, according to the statements). Thus the number of connected components of black segments is equal to 1 after that.
Input: 31 34 52 4 | Output: 1 2 1
Hard
1
402
307
100
9
816
A
816A
A. Karen and Morning
1,000
brute force; implementation
Karen is getting ready for a new school day! It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
The first and only line of input contains a single string in the format hh:mm (00 ≀ hh ≀ 23, 00 ≀ mm ≀ 59).
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Input: 05:39 | Output: 11
Beginner
2
556
107
148
8
2,119
E
2119E
E. And Constraint
2,600
bitmasks; dp; greedy
wowaka & Hatsune Miku - Tosenbo You are given a sequence \(a\) of length \(n-1\) and a sequence \(b\) of length \(n\). You can perform the following operation any number of times (possibly zero): choose an index \(1 \le i \le n\) and increment \(b_i\) by \(1\) (i.e., set \(b_i \leftarrow b_i + 1\)). Your goal is to perform the minimum number of operations such that for every \(1 \le i \le n-1\), the condition \(b_i \, \& \, b_{i+1} = a_i\) holds, where \(\&\) denotes the bitwise AND operation. If it is impossible to satisfy the condition, report it as well.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line contains a single integer \(n\) (\(2 \le n \le 10^5\)).The second line contains \(n-1\) integers \(a_1, a_2, \ldots, a_{n-1}\) (\(0 \le a_i < 2^{29}\)).The third line contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(0 \le b_i < 2^{29}\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
For each test case, you need to output only one integer.If the goal can be achieved, output one integer β€” the minimum number of operations required. Otherwise, output \(-1\).
In the first test case, one of the optimal strategies is to use \(4\) operations to make \(b = [1,5,4,4]\), which satisfies all the conditions. We can prove that it is impossible to use fewer than \(4\) operations.In the second test case, since \(b_1 \, \& \, b_2 = 4\) and \(b_2 \, \& \, b_3 =0\), then \(b_3 \, \& \, 4 =0\). However, we require that \(b_3 \, \& \, b_4 =4\), which means it is impossible to satisfy all the conditions.
Input: 741 4 41 2 3 444 0 41 1 1 1210 031 10 1 261 2 3 4 51 1 4 5 1 4200 040 1 0536870911 536870911 536870911 536870911 | Output: 4 -1 2 2 -1 0 536870916
Expert
3
563
510
174
21
33
D
33D
D. Knights
2,000
geometry; graphs; shortest paths; sortings
Berland is facing dark times again. The army of evil lord Van de Mart is going to conquer the whole kingdom. To the council of war called by the Berland's king Valery the Severe came n knights. After long discussions it became clear that the kingdom has exactly n control points (if the enemy conquers at least one of these points, the war is lost) and each knight will occupy one of these points. Berland is divided into m + 1 regions with m fences, and the only way to get from one region to another is to climb over the fence. Each fence is a circle on a plane, no two fences have common points, and no control point is on the fence. You are given k pairs of numbers ai, bi. For each pair you have to find out: how many fences a knight from control point with index ai has to climb over to reach control point bi (in case when Van de Mart attacks control point bi first). As each knight rides a horse (it is very difficult to throw a horse over a fence), you are to find out for each pair the minimum amount of fences to climb over.
The first input line contains three integers n, m, k (1 ≀ n, m ≀ 1000, 0 ≀ k ≀ 100000). Then follow n lines, each containing two integers Kxi, Kyi ( - 109 ≀ Kxi, Kyi ≀ 109) β€” coordinates of control point with index i. Control points can coincide.Each of the following m lines describes fence with index i with three integers ri, Cxi, Cyi (1 ≀ ri ≀ 109, - 109 ≀ Cxi, Cyi ≀ 109) β€” radius and center of the circle where the corresponding fence is situated.Then follow k pairs of integers ai, bi (1 ≀ ai, bi ≀ n), each in a separate line β€” requests that you have to answer. ai and bi can coincide.
Output exactly k lines, each containing one integer β€” the answer to the corresponding request.
Input: 2 1 10 03 32 0 01 2 | Output: 1
Hard
4
1,035
593
94
0
2,056
E
2056E
E. Nested Segments
2,500
combinatorics; dfs and similar; dp; dsu; math
A set \(A\) consisting of pairwise distinct segments \([l, r]\) with integer endpoints is called good if \(1\le l\le r\le n\), and for any pair of distinct segments \([l_i, r_i], [l_j, r_j]\) in \(A\), exactly one of the following conditions holds: \(r_i < l_j\) or \(r_j < l_i\) (the segments do not intersect) \(l_i \le l_j \le r_j \le r_i\) or \(l_j \le l_i \le r_i \le r_j\) (one segment is fully contained within the other) You are given a good set \(S\) consisting of \(m\) pairwise distinct segments \([l_i, r_i]\) with integer endpoints. You want to add as many additional segments to the set \(S\) as possible while ensuring that set \(S\) remains good. Since this task is too easy, you need to determine the number of different ways to add the maximum number of additional segments to \(S\), ensuring that the set remains good. Two ways are considered different if there exists a segment that is being added in one of the ways, but not in the other.Formally, you need to find the number of good sets \(T\) of distinct segments, such that \(S\) is a subset of \(T\) and \(T\) has the maximum possible size. Since the result might be very large, compute the answer modulo \(998\,244\,353\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n \le 2 \cdot 10^5\), \(0 \le m \le 2 \cdot 10^5\)) β€” the maximum right endpoint of the segments, and the size of \(S\).The \(i\)-th of the next \(m\) lines contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le n\)) β€” the boundaries of the segments in set \(S\).It is guaranteed that the given set \(S\) is good, and the segments in set \(S\) are pairwise distinct.It is guaranteed that both the sum of \(n\) and the sum of \(m\) over all test cases do not exceed \(2 \cdot 10^5\).
For each test case, output a single integer representing the number of different ways, modulo \(998\,244\,353\), that you can add the maximum number of additional segments to set \(S\) while ensuring that set \(S\) remains good.
In the first example, the only possible segment is \([1, 1]\), so \(T = \{[1, 1]\}\) has the maximum size, and it is the only solution.In the second example, it is not possible to add any additional segments to set \(S\). Hence, the only way to add segments to \(S\) is adding nothing.In the third example, it is possible to add \(7\) additional segments to \(S\) while ensuring that the set remains good. It can be proven that adding more than \(7\) additional segments to \(S\) is not possible. There are exactly \(2\) different ways to add these \(7\) segments to \(S\), and their respective sets \(T\) are shown below: \(\{[1, 1], [1, 3], [1, 4], [1, 5], [2, 2], [2, 3], [3, 3], [4, 4], [5, 5]\}\) \(\{[1, 1], [1, 3], [1, 5], [2, 2], [2, 3], [3, 3], [4, 4], [4, 5], [5, 5]\}\). In the fourth example, there are exactly \(5\) different ways to add a maximum of \(6\) additional segments to \(S\), and their respective sets \(T\) are shown below: \(\{[1, 1], [1, 2], [1, 3], [1, 4], [2, 2], [3, 3], [4, 4]\}\) \(\{[1, 1], [1, 2], [1, 4], [2, 2], [3, 3], [3, 4], [4, 4]\}\) \(\{[1, 1], [1, 3], [1, 4], [2, 2], [2, 3], [3, 3], [4, 4]\}\) \(\{[1, 1], [1, 4], [2, 2], [2, 3], [2, 4], [3, 3], [4, 4]\}\) \(\{[1, 1], [1, 4], [2, 2], [2, 4], [3, 3], [3, 4], [4, 4]\}\)
Input: 61 02 31 12 21 25 21 32 34 11 16 21 34 62300 0 | Output: 1 1 2 5 4 187997613
Expert
5
1,198
736
228
20
1,925
A
1925A
A. We Got Everything Covered!
800
constructive algorithms; greedy; strings
You are given two positive integers \(n\) and \(k\). Your task is to find a string \(s\) such that all possible strings of length \(n\) that can be formed using the first \(k\) lowercase English alphabets occur as a subsequence of \(s\). If there are multiple answers, print the one with the smallest length. If there are still multiple answers, you may print any of them.Note: A string \(a\) is called a subsequence of another string \(b\) if \(a\) can be obtained by deleting some (possibly zero) characters from \(b\) without changing the order of the remaining characters.
The first line of input contains a single integer \(t\) (\(1\leq t\leq 676\)) denoting the number of test cases.Each test case consists of a single line of input containing two integers \(n\) (\(1\leq n\leq 26\)) and \(k\) (\(1\leq k\leq 26\)).
For each test case, print a single line containing a single string \(s\) which satisfies the above property. If there are multiple answers, print the one with the smallest length. If there are still multiple answers, you may print any of them.
For the first test case, there are two strings of length \(1\) which can be formed using the first \(2\) lowercase English alphabets, and they are present in \(s\) as a subsequence as follows: \(\texttt{a}: {\color{red}{\texttt{a}}}\texttt{b}\) \(\texttt{b}: \texttt{a}{\color{red}{\texttt{b}}}\) For the second test case, there is only one string of length \(2\) which can be formed using the first lowercase English alphabet, and it is present in \(s\) as a subsequence as follows: \(\texttt{aa}: {\color{red}{\texttt{aa}}}\) For the third test case, there are \(4\) strings of length \(2\) which can be formed using the first \(2\) lowercase English alphabets, and they are present in \(s\) as a subsequence as follows: \(\texttt{aa}: \texttt{b}{\color{red}{\texttt{aa}}}\texttt{b}\) \(\texttt{ab}: \texttt{ba}{\color{red}{\texttt{ab}}}\) \(\texttt{ba}: {\color{red}{\texttt{ba}}}\texttt{ab}\) \(\texttt{bb}: {\color{red}{\texttt{b}}}\texttt{aa}{\color{red}{\texttt{b}}}\) For the fourth test case, there are \(9\) strings of length \(2\) which can be formed using the first \(3\) lowercase English alphabets, and they are present in \(s\) as a subsequence as follows: \(\texttt{aa}: {\color{red}{\texttt{a}}}\texttt{bcb}{\color{red}{\texttt{a}}}\texttt{c}\) \(\texttt{ab}: {\color{red}{\texttt{ab}}}\texttt{cbac}\) \(\texttt{ac}: \texttt{abcb}{\color{red}{\texttt{ac}}}\) \(\texttt{ba}: \texttt{abc}{\color{red}{\texttt{ba}}}\texttt{c}\) \(\texttt{bb}: \texttt{a}{\color{red}{\texttt{b}}}\texttt{c}{\color{red}{\texttt{b}}}\texttt{ac}\) \(\texttt{bc}: \texttt{a}{\color{red}{\texttt{bc}}}\texttt{bac}\) \(\texttt{ca}: \texttt{ab}{\color{red}{\texttt{c}}}\texttt{b}{\color{red}{\texttt{a}}}\texttt{c}\) \(\texttt{cb}: \texttt{ab}{\color{red}{\texttt{cb}}}\texttt{ac}\) \(\texttt{cc}: \texttt{ab}{\color{red}{\texttt{c}}}\texttt{ba}{\color{red}{\texttt{c}}}\)
Input: 41 22 12 22 3 | Output: ab aa baab abcbac
Beginner
3
576
244
243
19
29
D
29D
D. Ant on the Tree
2,000
constructive algorithms; dfs and similar; trees
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
The first line contains integer n (3 ≀ n ≀ 300) β€” amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers β€” indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Input: 31 22 33 | Output: 1 2 3 2 1
Hard
3
621
528
160
0
1,034
B
1034B
B. Little C Loves 3 II
2,200
brute force; constructive algorithms; flows; graph matchings
Little C loves number Β«3Β» very much. He loves all things about it.Now he is playing a game on a chessboard of size \(n \times m\). The cell in the \(x\)-th row and in the \(y\)-th column is called \((x,y)\). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly \(3\). The Manhattan distance between two cells \((x_i,y_i)\) and \((x_j,y_j)\) is defined as \(|x_i-x_j|+|y_i-y_j|\).He want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place.
A single line contains two integers \(n\) and \(m\) (\(1 \leq n,m \leq 10^9\)) β€” the number of rows and the number of columns of the chessboard.
Print one integer β€” the maximum number of chessmen Little C can place.
In the first example, the Manhattan distance between any two cells is smaller than \(3\), so the answer is \(0\).In the second example, a possible solution is \((1,1)(3,2)\), \((1,2)(3,3)\), \((2,1)(1,3)\), \((3,1)(2,3)\).
Input: 2 2 | Output: 0
Hard
4
604
144
70
10
1,415
A
1415A
A. Prison Break
800
brute force; math
There is a prison that can be represented as a rectangular matrix with \(n\) rows and \(m\) columns. Therefore, there are \(n \cdot m\) prison cells. There are also \(n \cdot m\) prisoners, one in each prison cell. Let's denote the cell in the \(i\)-th row and the \(j\)-th column as \((i, j)\).There's a secret tunnel in the cell \((r, c)\), that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell \((i, j)\) can move to cells \(( i - 1 , j )\) , \(( i + 1 , j )\) , \(( i , j - 1 )\) , or \(( i , j + 1 )\), as long as the target cell is inside the prison. They can also choose to stay in cell \((i, j)\).The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell \(( r , c )\) if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
The first line contains an integer \(t\) \((1 \le t \le 10^4)\), the number of test cases.Each of the next \(t\) lines contains four space-separated integers \(n\), \(m\), \(r\), \(c\) (\(1 \le r \le n \le 10^9\), \(1 \le c \le m \le 10^9\)).
Print \(t\) lines, the answers for each test case.
Input: 3 10 10 1 1 3 5 2 4 10 2 5 1 | Output: 18 4 6
Beginner
2
1,051
242
50
14
1,954
E
1954E
E. Chain Reaction
2,200
binary search; data structures; dsu; greedy; implementation; math; number theory
There are \(n\) monsters standing in a row. The \(i\)-th monster has \(a_i\) health points.Every second, you can choose one alive monster and launch a chain lightning at it. The lightning deals \(k\) damage to it, and also spreads to the left (towards decreasing \(i\)) and to the right (towards increasing \(i\)) to alive monsters, dealing \(k\) damage to each. When the lightning reaches a dead monster or the beginning/end of the row, it stops. A monster is considered alive if its health points are strictly greater than \(0\).For example, consider the following scenario: there are three monsters with health equal to \([5, 2, 7]\), and \(k = 3\). You can kill them all in \(4\) seconds: launch a chain lightning at the \(3\)-rd monster, then their health values are \([2, -1, 4]\); launch a chain lightning at the \(1\)-st monster, then their health values are \([-1, -1, 4]\); launch a chain lightning at the \(3\)-rd monster, then their health values are \([-1, -1, 1]\); launch a chain lightning at the \(3\)-th monster, then their health values are \([-1, -1, -2]\). For each \(k\) from \(1\) to \(\max(a_1, a_2, \dots, a_n)\), calculate the minimum number of seconds it takes to kill all the monsters.
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) β€” the number of monsters.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^5\)) β€” the health points of the \(i\)-th monster.
For each \(k\) from \(1\) to \(\max(a_1, a_2, \dots, a_n)\), output the minimum number of seconds it takes to kill all the monsters.
Input: 35 2 7 | Output: 10 6 4 3 2 2 1
Hard
7
1,212
229
132
19
978
D
978D
D. Almost Arithmetic Progression
1,500
brute force; implementation; math
Polycarp likes arithmetic progressions. A sequence \([a_1, a_2, \dots, a_n]\) is called an arithmetic progression if for each \(i\) (\(1 \le i < n\)) the value \(a_{i+1} - a_i\) is the same. For example, the sequences \([42]\), \([5, 5, 5]\), \([2, 11, 20, 29]\) and \([3, 2, 1, 0]\) are arithmetic progressions, but \([1, 0, 1]\), \([1, 3, 9]\) and \([2, 3, 1]\) are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers \([b_1, b_2, \dots, b_n]\). He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by \(1\), an element can be increased by \(1\), an element can be left unchanged.Determine a minimum possible number of elements in \(b\) which can be changed (by exactly one), so that the sequence \(b\) becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals \(0\).
The first line contains a single integer \(n\) \((1 \le n \le 100\,000)\) β€” the number of elements in \(b\).The second line contains a sequence \(b_1, b_2, \dots, b_n\) \((1 \le b_i \le 10^{9})\).
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer β€” the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
In the first example Polycarp should increase the first number on \(1\), decrease the second number on \(1\), increase the third number on \(1\), and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to \([25, 20, 15, 10]\), which is an arithmetic progression.In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.In the third example it is impossible to make an arithmetic progression.In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like \([0, 3, 6, 9, 12]\), which is an arithmetic progression.
Input: 424 21 14 10 | Output: 3
Medium
3
1,040
196
360
9
117
E
117E
E. Tree or not Tree
2,900
data structures; divide and conquer; graphs; implementation; trees
You are given an undirected connected graph G consisting of n vertexes and n edges. G contains no self-loops or multiple edges. Let each edge has two states: on and off. Initially all edges are switched off.You are also given m queries represented as (v, u) β€” change the state of all edges on the shortest path from vertex v to vertex u in graph G. If there are several such paths, the lexicographically minimal one is chosen. More formally, let us consider all shortest paths from vertex v to vertex u as the sequences of vertexes v, v1, v2, ..., u. Among such sequences we choose the lexicographically minimal one.After each query you should tell how many connected components has the graph whose vertexes coincide with the vertexes of graph G and edges coincide with the switched on edges of graph G.
The first line contains two integers n and m (3 ≀ n ≀ 105, 1 ≀ m ≀ 105). Then n lines describe the graph edges as a b (1 ≀ a, b ≀ n). Next m lines contain the queries as v u (1 ≀ v, u ≀ n). It is guaranteed that the graph is connected, does not have any self-loops or multiple edges.
Print m lines, each containing one integer β€” the query results.
Let's consider the first sample. We'll highlight the switched on edges blue on the image. The graph before applying any operations. No graph edges are switched on, that's why there initially are 5 connected components. The graph after query v = 5, u = 4. We can see that the graph has three components if we only consider the switched on edges. The graph after query v = 1, u = 5. We can see that the graph has three components if we only consider the switched on edges. Lexicographical comparison of two sequences of equal length of k numbers should be done as follows. Sequence x is lexicographically less than sequence y if exists such i (1 ≀ i ≀ k), so that xi < yi, and for any j (1 ≀ j < i) xj = yj.
Input: 5 22 14 32 42 54 15 41 5 | Output: 33
Master
5
803
283
63
1
1,466
D
1466D
D. 13th Labour of Heracles
1,500
data structures; greedy; sortings; trees
You've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve this task. But will you manage?In this problem, you are given a tree with \(n\) weighted vertices. A tree is a connected graph with \(n - 1\) edges.Let us define its \(k\)-coloring as an assignment of \(k\) colors to the edges so that each edge has exactly one color assigned to it. Note that you don't have to use all \(k\) colors.A subgraph of color \(x\) consists of these edges from the original tree, which are assigned color \(x\), and only those vertices that are adjacent to at least one such edge. So there are no vertices of degree \(0\) in such a subgraph.The value of a connected component is the sum of weights of its vertices. Let us define the value of a subgraph as a maximum of values of its connected components. We will assume that the value of an empty subgraph equals \(0\).There is also a value of a \(k\)-coloring, which equals the sum of values of subgraphs of all \(k\) colors. Given a tree, for each \(k\) from \(1\) to \(n - 1\) calculate the maximal value of a \(k\)-coloring.
In the first line of input, there is a single integer \(t\) (\(1 \leq t \leq 10^5\)) denoting the number of test cases. Then \(t\) test cases follow. First line of each test case contains a single integer \(n\) (\(2 \leq n \leq 10^5\)). The second line consists of \(n\) integers \(w_1, w_2, \dots, w_n\) (\(0 \leq w_i \leq 10^9\)), \(w_i\) equals the weight of \(i\)-th vertex. In each of the following \(n - 1\) lines, there are two integers \(u\), \(v\) (\(1 \leq u,v \leq n\)) describing an edge between vertices \(u\) and \(v\). It is guaranteed that these edges form a tree. The sum of \(n\) in all test cases will not exceed \(2 \cdot 10^5\).
For every test case, your program should print one line containing \(n - 1\) integers separated with a single space. The \(i\)-th number in a line should be the maximal value of a \(i\)-coloring of the tree.
The optimal \(k\)-colorings from the first test case are the following: In the \(1\)-coloring all edges are given the same color. The subgraph of color \(1\) contains all the edges and vertices from the original graph. Hence, its value equals \(3 + 5 + 4 + 6 = 18\). In an optimal \(2\)-coloring edges \((2, 1)\) and \((3,1)\) are assigned color \(1\). Edge \((4, 3)\) is of color \(2\). Hence the subgraph of color \(1\) consists of a single connected component (vertices \(1, 2, 3\)) and its value equals \(3 + 5 + 4 = 12\). The subgraph of color \(2\) contains two vertices and one edge. Its value equals \(4 + 6 = 10\). In an optimal \(3\)-coloring all edges are assigned distinct colors. Hence subgraphs of each color consist of a single edge. They values are as follows: \(3 + 4 = 7\), \(4 + 6 = 10\), \(3 + 5 = 8\).
Input: 4 4 3 5 4 6 2 1 3 1 4 3 2 21 32 2 1 6 20 13 17 13 13 11 2 1 3 1 4 1 5 1 6 1 4 10 6 6 6 1 2 2 3 4 1 | Output: 18 22 25 53 87 107 127 147 167 28 38 44
Medium
4
1,322
649
207
14
1,670
B
1670B
B. Dorms War
1,100
brute force; implementation; strings
Hosssam decided to sneak into Hemose's room while he is sleeping and change his laptop's password. He already knows the password, which is a string \(s\) of length \(n\). He also knows that there are \(k\) special letters of the alphabet: \(c_1,c_2,\ldots, c_k\).Hosssam made a program that can do the following. The program considers the current password \(s\) of some length \(m\). Then it finds all positions \(i\) (\(1\le i<m\)) such that \(s_{i+1}\) is one of the \(k\) special letters. Then it deletes all of those positions from the password \(s\) even if \(s_{i}\) is a special character. If there are no positions to delete, then the program displays an error message which has a very loud sound. For example, suppose the string \(s\) is ""abcdef"" and the special characters are 'b' and 'd'. If he runs the program once, the positions \(1\) and \(3\) will be deleted as they come before special characters, so the password becomes ""bdef"". If he runs the program again, it deletes position \(1\), and the password becomes ""def"". If he is wise, he won't run it a third time.Hosssam wants to know how many times he can run the program on Hemose's laptop without waking him up from the sound of the error message. Can you help him?
The first line contains a single integer \(t\) (\(1 \le t \le 10^5\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of each test case contains a single integer \(n\) (\(2 \le n \le 10^5\)) β€” the initial length of the password.The next line contains a string \(s\) consisting of \(n\) lowercase English letters β€” the initial password.The next line contains an integer \(k\) (\(1 \le k \le 26\)), followed by \(k\) distinct lowercase letters \(c_1,c_2,\ldots,c_k\) β€” the special letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
For each test case, print the maximum number of times Hosssam can run the program without displaying the error message, on a new line.
In the first test case, the program can run \(5\) times as follows: \(\text{iloveslim} \to \text{ilovslim} \to \text{iloslim} \to \text{ilslim} \to \text{islim} \to \text{slim}\)In the second test case, the program can run \(2\) times as follows: \(\text{joobeel} \to \text{oel} \to \text{el}\)In the third test case, the program can run \(3\) times as follows: \(\text{basiozi} \to \text{bioi} \to \text{ii} \to \text{i}\).In the fourth test case, the program can run \(5\) times as follows: \(\text{khater} \to \text{khatr} \to \text{khar} \to \text{khr} \to \text{kr} \to \text{r}\)In the fifth test case, the program can run only once as follows: \(\text{abobeih} \to \text{h}\)In the sixth test case, the program cannot run as none of the characters in the password is a special character.
Input: 109iloveslim1 s7joobeel2 o e7basiozi2 s i6khater1 r7abobeih6 a b e h i o5zondl5 a b c e f6shoman2 a h7shetwey2 h y5samez1 m6mouraz1 m | Output: 5 2 3 5 1 0 3 5 2 0
Easy
3
1,241
602
134
16
732
E
732E
E. Sockets
2,100
greedy; sortings
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point β€” the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters β€” power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
The first line contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of computers and the number of sockets.The second line contains n integers p1, p2, ..., pn (1 ≀ pi ≀ 109) β€” the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≀ si ≀ 109) β€” the power of the sockets.
In the first line print two numbers c and u β€” the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers.In the second line print m integers a1, a2, ..., am (0 ≀ ai ≀ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u.In third line print n integers b1, b2, ..., bn (0 ≀ bi ≀ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c.If there are multiple answers, print any of them.
Input: 2 21 12 2 | Output: 2 21 11 2
Hard
2
1,971
309
880
7
1,952
B
1952B
B. Is it stated?
0
*special; strings
The first line contains an integer \(t\) (\(1 \leq t \leq 100\)) β€” the number of testcases.The following \(t\) lines each contain a string of length at most \(100\) consisting of lowercase English letters.
For each test case, output ""YES"" or ""NO"", denoting the answer.
Input: 10isitstatedsubmitacacceptedwawronganswertletimelimitexceeded | Output: NO YES NO YES NO NO NO NO NO YES
Beginner
2
0
205
66
19
708
B
708B
B. Recover the String
1,900
constructive algorithms; greedy; implementation; math
For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000.
The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109.
If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print ""Impossible"". The length of your answer must not exceed 1 000 000.
Input: 1 2 3 4 | Output: Impossible
Hard
4
477
118
204
7
1,037
H
1037H
H. Security
3,200
data structures; string suffix structures
Some programming website is establishing a secure communication protocol. For security reasons, they want to choose several more or less random strings.Initially, they have a string \(s\) consisting of lowercase English letters. Now they want to choose \(q\) strings using the following steps, and you are to help them. A string \(x\) consisting of lowercase English letters and integers \(l\) and \(r\) (\(1 \leq l \leq r \leq |s|\)) are chosen. Consider all non-empty distinct substrings of the \(s_l s_{l + 1} \ldots s_r\), that is all distinct strings \(s_i s_{i+1} \ldots s_{j}\) where \(l \le i \le j \le r\). Among all of them choose all strings that are lexicographically greater than \(x\). If there are no such strings, you should print \(-1\). Otherwise print the lexicographically smallest among them. String \(a\) is lexicographically less than string \(b\), if either \(a\) is a prefix of \(b\) and \(a \ne b\), or there exists such a position \(i\) (\(1 \le i \le min(|a|, |b|)\)), such that \(a_i < b_i\) and for all \(j\) (\(1 \le j < i\)) \(a_j = b_j\). Here \(|a|\) denotes the length of the string \(a\).
The first line of input contains a non-empty string \(s\) (\(1 \leq |s| \leq 10^{5}\)) consisting of lowercase English letters.The second line contains an integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) β€” the number of strings to select.Each of the next \(q\) lines contains two integers \(l\), \(r\) (\(1 \leq l \leq r \leq |s|\)) and a non-empty string \(x\) consisting of lowercase English letters. The total length of strings \(x\) for all queries does not exceed \(2 \cdot 10^{5}\).
Output \(q\) lines, each of them should contain the desired string or \(-1\), if there is no such string.
Consider the first example.The string \(s\) is ""baa"". The queries are as follows. We consider the substring \(s_1 s_2\) that is ""ba"". It has substrings ""b"", ""a"" and ""ba"", since none of them is greater than the query string ""ba"", the answer is \(-1\). We consider substring ""aa"". Among its substrings only ""aa"" is greater than the query string ""a"". So the answer is ""aa"". We consider substring ""ba"". Out of ""b"", ""a"" and ""ba"" only ""ba"" is greater than the query string ""b"", so the answer is ""ba"". We consider substring ""aa"". No substring of ""aa"" is greater than the query string ""aa"" so the answer is \(-1\). We consider substring ""baa"" and it has (among others) substrings ""ba"", ""baa"" which are greater than the query string ""b"". Since ""ba"" is lexicographically smaller than ""baa"", the answer is ""ba"".
Input: baa51 2 ba2 3 a1 2 b2 3 aa1 3 b | Output: -1aaba-1ba
Master
2
1,124
484
105
10
177
B1
177B1
B1. Rectangular Game
1,000
number theory
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = aΒ·b. 10 pebbles are arranged in two rows, each row has 5 pebbles Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble. The game process can be represented as a finite sequence of integers c1, ..., ck, where: c1 = n ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≀ i < k). Note that ci > ci + 1. ck = 1 The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
The single line of the input contains a single integer n β€” the initial number of pebbles the Smart Beaver has.The input limitations for getting 30 points are: 2 ≀ n ≀ 50 The input limitations for getting 100 points are: 2 ≀ n ≀ 109
Print a single number β€” the maximum possible result of the game.
Consider the first example (c1 = 10). The possible options for the game development are: Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11. Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) β€” 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13. Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 β€” the maximum possible result.
Input: 10 | Output: 16
Beginner
1
1,143
231
64
1
74
D
74D
D. Hanger
2,400
data structures
In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work.
The first line contains two integers n, q (1 ≀ n ≀ 109, 1 ≀ q ≀ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type ""0 i j"" (1 ≀ i ≀ j ≀ n) β€” is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 β€” an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook.
For each director's request in the input data print a single number on a single line β€” the number of coats hanging on the hooks from the i-th one to the j-th one inclusive.
Input: 9 11120 5 81130 3 890 6 960 1 9 | Output: 2325
Expert
1
1,621
688
172
0
1,312
B
1312B
B. Bogosort
1,000
constructive algorithms; sortings
You are given an array \(a_1, a_2, \dots , a_n\). Array is good if for each pair of indexes \(i < j\) the condition \(j - a_j \ne i - a_i\) holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if \(a = [1, 1, 3, 5]\), then shuffled arrays \([1, 3, 5, 1]\), \([3, 5, 1, 1]\) and \([5, 3, 1, 1]\) are good, but shuffled arrays \([3, 1, 5, 1]\), \([1, 1, 3, 5]\) and \([1, 1, 5, 3]\) aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.
The first line contains one integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases.The first line of each test case contains one integer \(n\) (\(1 \le n \le 100\)) β€” the length of array \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \dots , a_n\) (\(1 \le a_i \le 100\)).
For each test case print the shuffled version of the array \(a\) which is good.
Input: 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 | Output: 7 1 5 1 3 2 4 6 1 3 5
Beginner
2
600
309
79
13
893
B
893B
B. Beautiful Divisors
1,000
brute force; implementation
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.Some examples of beautiful numbers: 12 (110); 1102 (610); 11110002 (12010); 1111100002 (49610). More formally, the number is beautiful iff there exists some positive integer k such that the number is equal to (2k - 1) * (2k - 1).Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find it!
The only line of input contains one number n (1 ≀ n ≀ 105) β€” the number Luba has got.
Output one number β€” the greatest beautiful divisor of Luba's number. It is obvious that the answer always exists.
Input: 3 | Output: 1
Beginner
2
552
85
113
8
745
B
745B
B. Hongcow Solves A Puzzle
1,400
implementation
Hongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions ""make a rectangle"" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
The first line of input will contain two integers n and m (1 ≀ n, m ≀ 500), the dimensions of the puzzle piece.The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output ""YES"" if it is possible for Hongcow to make a rectangle. Output ""NO"" otherwise.
For the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................
Input: 2 3XXXXXX | Output: YES
Easy
1
1,044
427
90
7
1,688
C
1688C
C. Manipulating History
1,700
constructive algorithms; greedy; strings
As a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness.β€”Perfect Memento in Strict SenseKeine has the ability to manipulate history. The history of Gensokyo is a string \(s\) of length \(1\) initially. To fix the chaos caused by Yukari, she needs to do the following operations \(n\) times, for the \(i\)-th time: She chooses a non-empty substring \(t_{2i-1}\) of \(s\). She replaces \(t_{2i-1}\) with a non-empty string, \(t_{2i}\). Note that the lengths of strings \(t_{2i-1}\) and \(t_{2i}\) can be different.Note that if \(t_{2i-1}\) occurs more than once in \(s\), exactly one of them will be replaced.For example, let \(s=\)""marisa"", \(t_{2i-1}=\)""a"", and \(t_{2i}=\)""z"". After the operation, \(s\) becomes ""mzrisa"" or ""marisz"".After \(n\) operations, Keine got the final string and an operation sequence \(t\) of length \(2n\). Just as Keine thinks she has finished, Yukari appears again and shuffles the order of \(t\). Worse still, Keine forgets the initial history. Help Keine find the initial history of Gensokyo!Recall that a substring is a sequence of consecutive characters of the string. For example, for string ""abc"" its substrings are: ""ab"", ""c"", ""bc"" and some others. But the following strings are not its substring: ""ac"", ""cba"", ""acb"".HacksYou cannot make hacks in this problem.
Each test contains multiple test cases. The first line contains a single integer \(T\) (\(1 \leq T \leq 10^3\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n < 10 ^ 5\)) β€” the number of operations.The next \(2n\) lines contains one non-empty string \(t_{i}\) β€” the \(i\)-th string of the shuffled sequence \(t\).The next line contains one non-empty string \(s\) β€” the final string.It is guaranteed that the total length of given strings (including \(t_i\) and \(s\)) over all test cases does not exceed \(2 \cdot 10 ^ 5\). All given strings consist of lowercase English letters only.It is guaranteed that the initial string exists. It can be shown that the initial string is unique.
For each test case, print the initial string in one line.
Test case 1:Initially \(s\) is ""a"". In the first operation, Keine chooses ""a"", and replaces it with ""ab"". \(s\) becomes ""ab"". In the second operation, Keine chooses ""b"", and replaces it with ""cd"". \(s\) becomes ""acd"".So the final string is ""acd"", and \(t=[\)""a"", ""ab"", ""b"", ""cd""\(]\) before being shuffled.Test case 2:Initially \(s\) is ""z"". In the first operation, Keine chooses ""z"", and replaces it with ""aa"". \(s\) becomes ""aa"". In the second operation, Keine chooses ""a"", and replaces it with ""ran"". \(s\) becomes ""aran"". In the third operation, Keine chooses ""a"", and replaces it with ""yakumo"". \(s\) becomes ""yakumoran"".So the final string is ""yakumoran"", and \(t=[\)""z"", ""aa"", ""a"", ""ran"", ""a"", ""yakumo""\(]\) before being shuffled.
Input: 22aabbcdacd3zaaaayakumoranyakumoran | Output: a z
Medium
3
1,382
782
57
16
533
D
533D
D. Landmarks
3,000
data structures; dp
We have an old building with n + 2 columns in a row. These columns support the ceiling. These columns are located in points with coordinates 0 = x0 < x1 < ... < xn < xn + 1. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary. For each column we know its durability di. Let's consider an ordinary column with coordinate x. Let's assume that the coordinate of the closest to it column to the left (bearing or ordinary) is a and the coordinate of the closest to it column to the right (also, bearing or ordinary) is b. In this task let's assume that this column supports the segment of the ceiling from point to point (here both fractions are considered as real division). If the length of the segment of the ceiling supported by the column exceeds di, then the column cannot support it and it crashes after a while, and after that the load is being redistributeed between the neighbouring columns according to the same principle. Thus, ordinary columns will be crashing for some time until the process stops at some state. One can prove that the set of the remaining columns doesn't depend on the order in which columns crash. If there are only two bearing columns left in the end, then we assume that the whole construction crashes under the weight of the roof. But if at least one ordinary column stays in addition to the bearing ones, then the building doesn't crash.To make the building stronger, we can add one extra ordinary column of arbitrary durability d' at any (not necessarily integer) point 0 < x' < xn + 1. If point x' is already occupied by an ordinary column, it is replaced by a new one.Your task is to find out: what minimal durability can the added column have so that the building doesn't crash?
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of ordinary columns.The second line contains n + 2 integers x0, x1, ..., xn, xn + 1 (x0 = 0, xi < xi + 1 for 0 ≀ i ≀ n, xn + 1 ≀ 109) β€” the coordinates of the columns.The third line contains n integers d1, d2, ..., dn (1 ≀ di ≀ 109).
Print a single number β€” the minimum possible durability of the column that you need to add in order to make the building stay. If you do not have to add the column, please print 0. Your answer will be checked with the relative or absolute error 10 - 4.
Input: 20 20 40 10015 40 | Output: 10
Master
2
1,772
294
252
5
36
B
36B
B. Fractal
1,600
implementation
Ever since Kalevitch, a famous Berland abstractionist, heard of fractals, he made them the main topic of his canvases. Every morning the artist takes a piece of graph paper and starts with making a model of his future canvas. He takes a square as big as n Γ— n squares and paints some of them black. Then he takes a clean square piece of paper and paints the fractal using the following algorithm: Step 1. The paper is divided into n2 identical squares and some of them are painted black according to the model.Step 2. Every square that remains white is divided into n2 smaller squares and some of them are painted black according to the model.Every following step repeats step 2. Unfortunately, this tiresome work demands too much time from the painting genius. Kalevitch has been dreaming of making the process automatic to move to making 3D or even 4D fractals.
The first line contains integers n and k (2 ≀ n ≀ 3, 1 ≀ k ≀ 5), where k is the amount of steps of the algorithm. Each of the following n lines contains n symbols that determine the model. Symbol Β«.Β» stands for a white square, whereas Β«*Β» stands for a black one. It is guaranteed that the model has at least one white square.
Output a matrix nk Γ— nk which is what a picture should look like after k steps of the algorithm.
Input: 2 3.*.. | Output: .*******..******.*.*****....****.***.***..**..**.*.*.*.*........
Medium
1
863
325
96
0
1,444
D
1444D
D. Rectangular Polyline
2,900
constructive algorithms; dp; geometry
One drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersections, which means that in case any two segments shared a common point, that point was an endpoint for both of them (please consult the examples in the notes section).Unfortunately, the polyline was erased, and you only know the lengths of the horizonal and vertical segments. Please construct any polyline matching the description with such segments, or determine that it does not exist.
The first line contains one integer \(t\) (\(1 \leq t \leq 200\)) β€”the number of test cases.The first line of each test case contains one integer \(h\) (\(1 \leq h \leq 1000\)) β€” the number of horizontal segments. The following line contains \(h\) integers \(l_1, l_2, \dots, l_h\) (\(1 \leq l_i \leq 1000\)) β€” lengths of the horizontal segments of the polyline, in arbitrary order.The following line contains an integer \(v\) (\(1 \leq v \leq 1000\)) β€” the number of vertical segments, which is followed by a line containing \(v\) integers \(p_1, p_2, \dots, p_v\) (\(1 \leq p_i \leq 1000\)) β€” lengths of the vertical segments of the polyline, in arbitrary order.Test cases are separated by a blank line, and the sum of values \(h + v\) over all test cases does not exceed \(1000\).
For each test case output Yes, if there exists at least one polyline satisfying the requirements, or No otherwise. If it does exist, in the following \(n\) lines print the coordinates of the polyline vertices, in order of the polyline traversal: the \(i\)-th line should contain two integers \(x_i\) and \(y_i\) β€” coordinates of the \(i\)-th vertex.Note that, each polyline segment must be either horizontal or vertical, and the segments should alternate between horizontal and vertical. The coordinates should not exceed \(10^9\) by their absolute value.
In the first test case of the first example, the answer is Yes β€” for example, the following picture illustrates a square that satisfies the requirements: In the first test case of the second example, the desired polyline also exists. Note that, the polyline contains self-intersections, but only in the endpoints: In the second test case of the second example, the desired polyline could be like the one below: Note that the following polyline is not a valid one, since it contains self-intersections that are not endpoints for some of the segments:
Input: 2 2 1 1 2 1 1 2 1 2 2 3 3 | Output: Yes 1 0 1 1 0 1 0 0 No
Master
3
706
783
555
14
1,970
G3
1970G3
G3. Min-Fund Prison (Hard)
2,400
bitmasks; dfs and similar; dp; graphs; trees
In the hard version, \(2 \leq \sum n \leq 10^5\) and \(1 \leq \sum m \leq 5 \times 10^{5}\)After a worker's strike organized by the Dementors asking for equal rights, the prison of Azkaban has suffered some damage. After settling the spirits, the Ministry of Magic is looking to renovate the prison to ensure that the Dementors are kept in check. The prison consists of \(n\) prison cells and \(m\) bi-directional corridors. The \(i^{th}\) corridor is from cells \(u_i\) to \(v_i\). A subset of these cells \(S\) is called a complex if any cell in \(S\) is reachable from any other cell in \(S\). Formally, a subset of cells \(S\) is a complex if \(x\) and \(y\) are reachable from each other for all \(x, y \in S\), using only cells from \(S\) on the way. The funding required for a complex \(S\) consisting of \(k\) cells is defined as \(k^2\).As part of your Intro to Magical Interior Design course at Hogwarts, you have been tasked with designing the prison. The Ministry of Magic has asked that you divide the prison into \(2\) complexes with \(\textbf{exactly one corridor}\) connecting them, so that the Dementors can't organize union meetings. For this purpose, you are allowed to build bi-directional corridors. The funding required to build a corridor between any \(2\) cells is \(c\). Due to budget cuts and the ongoing fight against the Death Eaters, you must find the \(\textbf{minimum total funding}\) required to divide the prison as per the Ministry's requirements or \(-1\) if no division is possible.Note: The total funding is the sum of the funding required for the \(2\) complexes and the corridors built. If after the division, the two complexes have \(x\) and \(y\) cells respectively and you have built a total of \(a\) corridors, the total funding will be \(x^2 + y^2 + c \times a\). Note that \(x+y=n\).
The first line contains one integer \(t\) (\(1 \leq t \leq 10^5\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of each test case consists of three integers \(n, m\) and \(c\) (\(2 \leq n \leq 10^5\), \(1 \leq m \leq 5 \times 10^{5}\), \(1 \leq c \leq 10^9\))\(m\) lines follow, each consisting of 2 integers β€” \(u_i, v_i\) indicating a corridor is present between cells \(u_i\) and \(v_i\) (\(1 \leq u_i, v_i \leq n\), \(u_i \neq v_i\))It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).It is guaranteed that the sum of \(m\) over all test cases does not exceed \(5 \times 10^5\).It is guaranteed that there exists at most one corridor between any two cells.
Print the \(\textbf{minimum funding}\) required to divide the prison as per the Ministry's requirements or \(-1\) if no division is possible.
In the first test case of the sample input, there is no way to divide the prison according to the Ministry's requirements.In the second test case, consider the corridor between cells \(1\) and \(5\) as the connection between the \(2\) complexes consisting of \(\{2, 3, 5, 6\}\) and \(\{1, 4\}\) cells respectively. There are no new corridors built. The total funding is \(4^2 + 2^2 = 20\). You can verify this is the minimum funding required. In the third test case, build a corridor between \(2\) and \(4\). Consider the corridor between cells \(1\) and \(5\) as the connection between the \(2\) complexes consisting of \(\{3, 5, 6\}\) and \(\{1, 2, 4\}\) cells respectively. The total funding is \(3^2 + 3^2 + 7 \times 1 = 25\). You can verify this is the minimum funding required. In the fourth test case, build a corridor between \(2\) and \(4\) and between \(5\) and \(7\). Consider the corridor between cells \(5\) and \(7\) as the connection between the \(2\) complexes consisting of \(\{1, 2, 4, 7\}\) and \(\{3, 5, 6\}\) cells respectively. The total funding is \(4^2 + 3^2 + 4 \times 2 = 33\). You can verify this is the minimum funding required. Note for all test cases that there may be multiple ways to get the same funding but there is no other division which will have a more optimal minimum funding.
Input: 4 4 6 5 4 3 2 3 2 4 1 2 4 1 3 1 6 6 2 1 4 2 5 3 6 1 5 3 5 6 5 6 5 7 1 4 2 5 3 6 3 5 6 5 7 5 4 1 4 3 6 3 5 6 5 2 7 | Output: -1 20 25 33
Expert
5
1,828
719
141
19
754
A
754A
A. Lesha and array splitting
1,200
constructive algorithms; greedy; implementation
One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A.Lesha is tired now so he asked you to split the array. Help Lesha!
The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A.The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A.
If it is not possible to split the array A and satisfy all the constraints, print single line containing ""NO"" (without quotes).Otherwise in the first line print ""YES"" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: l1 = 1 rk = n ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them.
Input: 31 2 -3 | Output: YES21 23 3
Easy
3
432
195
557
7
1,832
E
1832E
E. Combinatorics Problem
2,200
brute force; combinatorics; dp
Recall that the binomial coefficient \(\binom{x}{y}\) is calculated as follows (\(x\) and \(y\) are non-negative integers): if \(x < y\), then \(\binom{x}{y} = 0\); otherwise, \(\binom{x}{y} = \frac{x!}{y! \cdot (x-y)!}\). You are given an array \(a_1, a_2, \dots, a_n\) and an integer \(k\). You have to calculate a new array \(b_1, b_2, \dots, b_n\), where \(b_1 = (\binom{1}{k} \cdot a_1) \bmod 998244353\); \(b_2 = (\binom{2}{k} \cdot a_1 + \binom{1}{k} \cdot a_2) \bmod 998244353\); \(b_3 = (\binom{3}{k} \cdot a_1 + \binom{2}{k} \cdot a_2 + \binom{1}{k} \cdot a_3) \bmod 998244353\), and so on. Formally, \(b_i = (\sum\limits_{j=1}^{i} \binom{i - j + 1}{k} \cdot a_j) \bmod 998244353\).Note that the array is given in a modified way, and you have to output it in a modified way as well.
The only line of the input contains six integers \(n\), \(a_1\), \(x\), \(y\), \(m\) and \(k\) (\(1 \le n \le 10^7\); \(0 \le a_1, x, y < m\); \(2 \le m \le 998244353\); \(1 \le k \le 5\)).The array \([a_1, a_2, \dots, a_n]\) is generated as follows: \(a_1\) is given in the input; for \(2 \le i \le n\), \(a_i = (a_{i-1} \cdot x + y) \bmod m\).
Since outputting up to \(10^7\) integers might be too slow, you have to do the following:Let \(c_i = b_i \cdot i\) (without taking modulo \(998244353\) after the multiplication). Print the integer \(c_1 \oplus c_2 \oplus \dots \oplus c_n\), where \(\oplus\) denotes the bitwise XOR operator.
Input: 5 8 2 3 100 2 | Output: 1283
Hard
3
792
345
291
18
1,084
C
1084C
C. The Fair Nut and String
1,500
combinatorics; dp; implementation
The Fair Nut found a string \(s\). The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences \(p_1, p_2, \ldots, p_k\), such that: For each \(i\) (\(1 \leq i \leq k\)), \(s_{p_i} =\) 'a'. For each \(i\) (\(1 \leq i < k\)), there is such \(j\) that \(p_i < j < p_{i + 1}\) and \(s_j =\) 'b'. The Nut is upset because he doesn't know how to find the number. Help him.This number should be calculated modulo \(10^9 + 7\).
The first line contains the string \(s\) (\(1 \leq |s| \leq 10^5\)) consisting of lowercase Latin letters.
In a single line print the answer to the problem β€” the number of such sequences \(p_1, p_2, \ldots, p_k\) modulo \(10^9 + 7\).
In the first example, there are \(5\) possible sequences. \([1]\), \([4]\), \([5]\), \([1, 4]\), \([1, 5]\).In the second example, there are \(4\) possible sequences. \([2]\), \([3]\), \([4]\), \([5]\).In the third example, there are \(3\) possible sequences. \([1]\), \([3]\), \([4]\).
Input: abbaa | Output: 5
Medium
3
498
106
126
10
1,095
C
1095C
C. Powers Of Two
1,400
bitmasks; greedy
A positive integer \(x\) is called a power of two if it can be represented as \(x = 2^y\), where \(y\) is a non-negative integer. So, the powers of two are \(1, 2, 4, 8, 16, \dots\).You are given two positive integers \(n\) and \(k\). Your task is to represent \(n\) as the sum of exactly \(k\) powers of two.
The only line of the input contains two integers \(n\) and \(k\) (\(1 \le n \le 10^9\), \(1 \le k \le 2 \cdot 10^5\)).
If it is impossible to represent \(n\) as the sum of \(k\) powers of two, print NO.Otherwise, print YES, and then print \(k\) positive integers \(b_1, b_2, \dots, b_k\) such that each of \(b_i\) is a power of two, and \(\sum \limits_{i = 1}^{k} b_i = n\). If there are multiple answers, you may print any of them.
Input: 9 4 | Output: YES 1 2 2 4
Easy
2
309
118
313
10
2,095
H
2095H
H. Blurry Vision
0
*special; fft; math
Please direct your vision to line number \(x\). Now, read the word you see on that line. If you struggle, I might have to prescribe eyeglasses.
The only line contains one integer \(x\) (\(1 \leq x \leq 11\)) β€” the line number.
Output the word on line number \(x\).
If you fail to read the first line, even glasses won't save you.
Input: 1 | Output: CODEFORCES
Beginner
3
143
82
37
20
2,064
F
2064F
F. We Be Summing
2,600
binary search; data structures; dp; two pointers
You are given an array \(a\) of length \(n\) and an integer \(k\).Call a non-empty array \(b\) of length \(m\) epic if there exists an integer \(i\) where \(1 \le i < m\) and \(\min(b_1,\ldots,b_i) + \max(b_{i + 1},\ldots,b_m) = k\).Count the number of epic subarrays\(^{\text{βˆ—}}\) of \(a\).\(^{\text{βˆ—}}\)An array \(a\) is a subarray of an array \(b\) if \(a\) can be obtained from \(b\) by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of testcases.The first line of each testcase contains integers \(n\) and \(k\) (\(2 \le n \le 2 \cdot 10^5\); \(n < k < 2 \cdot n\)) β€” the length of the array \(a\) and \(k\).The second line of each testcase contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(1 \le a_i \le n\)).The sum of \(n\) across all testcases does not exceed \(2 \cdot 10^5\).
For each testcase, output the number of epic contiguous subarrays of \(a\).
These are all the epic subarrays in the first testcase: \([2, 3, 4, 5]\), because \(\min(2, 3) + \max(4, 5) = 2 + 5 = 7\). \([3, 4]\), because \(\min(3) + \max(4) = 3 + 4 = 7\). In the second test case, every subarray that contains at least one \(6\) and at least one \(7\) is epic.
Input: 65 71 2 3 4 57 136 6 6 6 7 7 76 94 5 6 6 5 15 95 5 4 5 55 63 3 3 3 36 84 5 4 5 4 5 | Output: 2 12 3 8 10 4
Expert
4
527
425
75
20
1,433
A
1433A
A. Boring Apartments
800
implementation; math
There is a building consisting of \(10~000\) apartments numbered from \(1\) to \(10~000\), inclusive.Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are \(11, 2, 777, 9999\) and so on.Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone answers the call, in the following order: First he calls all apartments consisting of digit \(1\), in increasing order (\(1, 11, 111, 1111\)). Next he calls all apartments consisting of digit \(2\), in increasing order (\(2, 22, 222, 2222\)) And so on. The resident of the boring apartment \(x\) answers the call, and our character stops calling anyone further.Our character wants to know how many digits he pressed in total and your task is to help him to count the total number of keypresses.For example, if the resident of boring apartment \(22\) answered, then our character called apartments with numbers \(1, 11, 111, 1111, 2, 22\) and the total number of digits he pressed is \(1 + 2 + 3 + 4 + 1 + 2 = 13\).You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 36\)) β€” the number of test cases.The only line of the test case contains one integer \(x\) (\(1 \le x \le 9999\)) β€” the apartment number of the resident who answered the call. It is guaranteed that \(x\) consists of the same digit.
For each test case, print the answer: how many digits our character pressed in total.
Input: 4 22 9999 1 777 | Output: 13 90 1 66
Beginner
2
1,095
301
85
14
594
D
594D
D. REQ
2,500
data structures; number theory
Today on a math lesson the teacher told Vovochka that the Euler function of a positive integer Ο†(n) is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number 1 is coprime to all the positive integers and Ο†(1) = 1.Now the teacher gave Vovochka an array of n positive integers a1, a2, ..., an and a task to process q queries li ri β€” to calculate and print modulo 109 + 7. As it is too hard for a second grade school student, you've decided to help Vovochka.
The first line of the input contains number n (1 ≀ n ≀ 200 000) β€” the length of the array given to Vovochka. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106).The third line contains integer q (1 ≀ q ≀ 200 000) β€” the number of queries. Next q lines contain the queries, one per line. Each query is defined by the boundaries of the segment li and ri (1 ≀ li ≀ ri ≀ n).
Print q numbers β€” the value of the Euler function for each query, calculated modulo 109 + 7.
In the second sample the values are calculated like that: Ο†(13Β·52Β·6) = Ο†(4056) = 1248 Ο†(52Β·6Β·10Β·1) = Ο†(3120) = 768 Ο†(24Β·63Β·13Β·52Β·6Β·10Β·1) = Ο†(61326720) = 12939264 Ο†(63Β·13Β·52) = Ο†(42588) = 11232 Ο†(13Β·52Β·6Β·10) = Ο†(40560) = 9984 Ο†(63Β·13Β·52Β·6Β·10) = Ο†(2555280) = 539136
Input: 101 2 3 4 5 6 7 8 9 1071 13 85 64 88 107 97 10 | Output: 14608815361921441152
Expert
2
524
384
92
5
1,844
G
1844G
G. Tree Weights
3,000
bitmasks; constructive algorithms; data structures; dfs and similar; implementation; math; matrices; number theory; trees
You are given a tree with \(n\) nodes labelled \(1,2,\dots,n\). The \(i\)-th edge connects nodes \(u_i\) and \(v_i\) and has an unknown positive integer weight \(w_i\). To help you figure out these weights, you are also given the distance \(d_i\) between the nodes \(i\) and \(i+1\) for all \(1 \le i \le n-1\) (the sum of the weights of the edges on the simple path between the nodes \(i\) and \(i+1\) in the tree).Find the weight of each edge. If there are multiple solutions, print any of them. If there are no weights \(w_i\) consistent with the information, print a single integer \(-1\).
The first line contains a single integer \(n\) (\(2 \le n \le 10^5\)).The \(i\)-th of the next \(n-1\) lines contains two integers \(u_i\) and \(v_i\) (\(1 \le u_i,v_i \le n\), \(u_i \ne v_i\)).The last line contains \(n-1\) integers \(d_1,\dots,d_{n-1}\) (\(1 \le d_i \le 10^{12}\)).It is guaranteed that the given edges form a tree.
If there is no solution, print a single integer \(-1\). Otherwise, output \(n-1\) lines containing the weights \(w_1,\dots,w_{n-1}\).If there are multiple solutions, print any of them.
In the first sample, the tree is as follows: In the second sample, note that \(w_2\) is not allowed to be \(0\) because it must be a positive integer, so there is no solution.In the third sample, the tree is as follows:
Input: 5 1 2 1 3 2 4 2 5 31 41 59 26 | Output: 31 10 18 8
Master
9
593
334
184
18
1,401
B
1401B
B. Ternary Sequence
1,100
constructive algorithms; greedy; math
You are given two sequences \(a_1, a_2, \dots, a_n\) and \(b_1, b_2, \dots, b_n\). Each element of both sequences is either \(0\), \(1\) or \(2\). The number of elements \(0\), \(1\), \(2\) in the sequence \(a\) is \(x_1\), \(y_1\), \(z_1\) respectively, and the number of elements \(0\), \(1\), \(2\) in the sequence \(b\) is \(x_2\), \(y_2\), \(z_2\) respectively.You can rearrange the elements in both sequences \(a\) and \(b\) however you like. After that, let's define a sequence \(c\) as follows:\(c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}\)You'd like to make \(\sum_{i=1}^n c_i\) (the sum of all elements of the sequence \(c\)) as large as possible. What is the maximum possible sum?
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.Each test case consists of two lines. The first line of each test case contains three integers \(x_1\), \(y_1\), \(z_1\) (\(0 \le x_1, y_1, z_1 \le 10^8\)) β€” the number of \(0\)-s, \(1\)-s and \(2\)-s in the sequence \(a\).The second line of each test case also contains three integers \(x_2\), \(y_2\), \(z_2\) (\(0 \le x_2, y_2, z_2 \le 10^8\); \(x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0\)) β€” the number of \(0\)-s, \(1\)-s and \(2\)-s in the sequence \(b\).
For each test case, print the maximum possible sum of the sequence \(c\).
In the first sample, one of the optimal solutions is:\(a = \{2, 0, 1, 1, 0, 2, 1\}\)\(b = \{1, 0, 1, 0, 2, 1, 0\}\)\(c = \{2, 0, 0, 0, 0, 2, 0\}\)In the second sample, one of the optimal solutions is:\(a = \{0, 2, 0, 0, 0\}\)\(b = \{1, 1, 0, 1, 0\}\)\(c = \{0, 2, 0, 0, 0\}\)In the third sample, the only possible solution is:\(a = \{2\}\)\(b = \{2\}\)\(c = \{0\}\)
Input: 3 2 3 2 3 3 1 4 0 1 2 3 0 0 0 1 0 0 1 | Output: 4 2 0
Easy
3
771
549
73
14
916
A
916A
A. Jamie and Alarm Snooze
900
brute force; implementation; math
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to know what is the smallest number of times he needs to press the snooze button.A time is considered lucky if it contains a digit '7'. For example, 13: 07 and 17: 27 are lucky, while 00: 48 and 21: 34 are not lucky.Note that it is not necessary that the time set for the alarm and the wake-up time are on the same day. It is guaranteed that there is a lucky time Jamie can set so that he can wake at hh: mm.Formally, find the smallest possible non-negative integer y such that the time representation of the time xΒ·y minutes before hh: mm contains the digit '7'.Jamie uses 24-hours clock, so after 23: 59 comes 00: 00.
The first line contains a single integer x (1 ≀ x ≀ 60).The second line contains two two-digit integers, hh and mm (00 ≀ hh ≀ 23, 00 ≀ mm ≀ 59).
Print the minimum number of times he needs to press the button.
In the first sample, Jamie needs to wake up at 11:23. So, he can set his alarm at 11:17. He would press the snooze button when the alarm rings at 11:17 and at 11:20.In the second sample, Jamie can set his alarm at exactly at 01:07 which is lucky.
Input: 311 23 | Output: 2
Beginner
3
933
144
63
9
1,305
C
1305C
C. Kuroni and Impossible Calculation
1,600
brute force; combinatorics; math; number theory
To become the king of Codeforces, Kuroni has to solve the following problem.He is given \(n\) numbers \(a_1, a_2, \dots, a_n\). Help Kuroni to calculate \(\prod_{1\le i<j\le n} |a_i - a_j|\). As result can be very big, output it modulo \(m\).If you are not familiar with short notation, \(\prod_{1\le i<j\le n} |a_i - a_j|\) is equal to \(|a_1 - a_2|\cdot|a_1 - a_3|\cdot\) \(\dots\) \(\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot\) \(\dots\) \(\cdot|a_2 - a_n| \cdot\) \(\dots\) \(\cdot |a_{n-1} - a_n|\). In other words, this is the product of \(|a_i - a_j|\) for all \(1\le i < j \le n\).
The first line contains two integers \(n\), \(m\) (\(2\le n \le 2\cdot 10^5\), \(1\le m \le 1000\)) β€” number of numbers and modulo.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(0 \le a_i \le 10^9\)).
Output the single number β€” \(\prod_{1\le i<j\le n} |a_i - a_j| \bmod m\).
In the first sample, \(|8 - 5| = 3 \equiv 3 \bmod 10\).In the second sample, \(|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12\).In the third sample, \(|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7\).
Input: 2 10 8 5 | Output: 3
Medium
4
600
221
73
13
1,154
F
1154F
F. Shovels Shop
2,100
dp; greedy; sortings
There are \(n\) shovels in the nearby shop. The \(i\)-th shovel costs \(a_i\) bourles.Misha has to buy exactly \(k\) shovels. Each shovel can be bought no more than once.Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.There are also \(m\) special offers in the shop. The \(j\)-th of them is given as a pair \((x_j, y_j)\), and it means that if Misha buys exactly \(x_j\) shovels during one purchase then \(y_j\) most cheapest of them are for free (i.e. he will not pay for \(y_j\) most cheapest shovels during the current purchase).Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).Your task is to calculate the minimum cost of buying \(k\) shovels, if Misha buys them optimally.
The first line of the input contains three integers \(n, m\) and \(k\) (\(1 \le n, m \le 2 \cdot 10^5, 1 \le k \le min(n, 2000)\)) β€” the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 2 \cdot 10^5\)), where \(a_i\) is the cost of the \(i\)-th shovel.The next \(m\) lines contain special offers. The \(j\)-th of them is given as a pair of integers \((x_i, y_i)\) (\(1 \le y_i \le x_i \le n\)) and means that if Misha buys exactly \(x_i\) shovels during some purchase, then he can take \(y_i\) most cheapest of them for free.
Print one integer β€” the minimum cost of buying \(k\) shovels if Misha buys them optimally.
In the first example Misha can buy shovels on positions \(1\) and \(4\) (both with costs \(2\)) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions \(3\) and \(6\) (with costs \(4\) and \(3\)) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position \(7\) with cost \(1\). So the total cost is \(4 + 2 + 1 = 7\).In the second example Misha can buy shovels on positions \(1\), \(2\), \(3\), \(4\) and \(8\) (costs are \(6\), \(8\), \(5\), \(1\) and \(2\)) and get three cheapest (with costs \(5\), \(1\) and \(2\)) for free. And then he can buy shovels on positions \(6\), \(7\) and \(9\) (all with costs \(1\)) without using any special offers. So the total cost is \(6 + 8 + 1 + 1 + 1 = 17\).In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost \(17\).
Input: 7 4 5 2 5 4 2 6 3 1 2 1 6 5 2 1 3 1 | Output: 7
Hard
3
894
691
90
11
1,365
A
1365A
A. Matrix Game
1,100
games; greedy; implementation
Ashish and Vivek play a game on a matrix consisting of \(n\) rows and \(m\) columns, where they take turns claiming cells. Unclaimed cells are represented by \(0\), while claimed cells are represented by \(1\). The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.
The first line consists of a single integer \(t\) \((1 \le t \le 50)\) β€” the number of test cases. The description of the test cases follows.The first line of each test case consists of two space-separated integers \(n\), \(m\) \((1 \le n, m \le 50)\) β€” the number of rows and columns in the matrix.The following \(n\) lines consist of \(m\) integers each, the \(j\)-th integer on the \(i\)-th line denoting \(a_{i,j}\) \((a_{i,j} \in \{0, 1\})\).
For each test case if Ashish wins the game print ""Ashish"" otherwise print ""Vivek"" (without quotes).
For the first case: One possible scenario could be: Ashish claims cell \((1, 1)\), Vivek then claims cell \((2, 2)\). Ashish can neither claim cell \((1, 2)\), nor cell \((2, 1)\) as cells \((1, 1)\) and \((2, 2)\) are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell \((1, 1)\), the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell \((2, 3)\), Vivek will have no moves left.
Input: 4 2 2 0 0 0 0 2 2 0 0 0 1 2 3 1 0 1 1 1 0 3 3 1 0 0 0 0 0 1 0 0 | Output: Vivek Ashish Vivek Ashish
Easy
3
805
447
103
13
1,433
B
1433B
B. Yet Another Bookshelf
800
greedy; implementation
There is a bookshelf which can fit \(n\) books. The \(i\)-th position of bookshelf is \(a_i = 1\) if there is a book on this position and \(a_i = 0\) otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment \([l; r]\) consisting of books (i.e. for each \(i\) from \(l\) to \(r\) the condition \(a_i = 1\) holds) and: Shift it to the right by \(1\): move the book at index \(i\) to \(i + 1\) for all \(l \le i \le r\). This move can be done only if \(r+1 \le n\) and there is no book at the position \(r+1\). Shift it to the left by \(1\): move the book at index \(i\) to \(i-1\) for all \(l \le i \le r\). This move can be done only if \(l-1 \ge 1\) and there is no book at the position \(l-1\). Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for \(a = [0, 0, 1, 0, 1]\) there is a gap between books (\(a_4 = 0\) when \(a_3 = 1\) and \(a_5 = 1\)), for \(a = [1, 1, 0]\) there are no gaps between books and for \(a = [0, 0,0]\) there are also no gaps between books.You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 200\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of the test case contains one integer \(n\) (\(1 \le n \le 50\)) β€” the number of places on a bookshelf. The second line of the test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 1\)), where \(a_i\) is \(1\) if there is a book at this position and \(0\) otherwise. It is guaranteed that there is at least one book on the bookshelf.
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
In the first test case of the example, you can shift the segment \([3; 3]\) to the right and the segment \([4; 5]\) to the right. After all moves, the books form the contiguous segment \([5; 7]\). So the answer is \(2\).In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment \([5; 5]\) to the left and then the segment \([4; 4]\) to the left again. After all moves, the books form the contiguous segment \([1; 3]\). So the answer is \(2\).In the fourth test case of the example, you can shift the segment \([1; 1]\) to the right, the segment \([2; 2]\) to the right, the segment \([6; 6]\) to the left and then the segment \([5; 5]\) to the left. After all moves, the books form the contiguous segment \([3; 4]\). So the answer is \(4\).In the fifth test case of the example, you can shift the segment \([1; 2]\) to the right. After all moves, the books form the contiguous segment \([2; 5]\). So the answer is \(1\).
Input: 5 7 0 0 1 0 1 0 1 3 1 0 0 5 1 1 0 0 1 6 1 0 0 0 0 1 5 1 1 0 1 1 | Output: 2 0 2 4 1
Beginner
2
1,220
505
184
14
914
G
914G
G. Sum the Fibonacci
2,600
bitmasks; divide and conquer; dp; fft; math
You are given an array s of n non-negative integers.A 5-tuple of integers (a, b, c, d, e) is said to be valid if it satisfies the following conditions: 1 ≀ a, b, c, d, e ≀ n (sa | sb) & sc & (sd ^ se) = 2i for some integer i sa & sb = 0 Here, '|' is the bitwise OR, '&' is the bitwise AND and '^' is the bitwise XOR operation.Find the sum of f(sa|sb) * f(sc) * f(sd^se) over all valid 5-tuples (a, b, c, d, e), where f(i) is the i-th Fibonnaci number (f(0) = 0, f(1) = 1, f(i) = f(i - 1) + f(i - 2)).Since answer can be is huge output it modulo 109 + 7.
The first line of input contains an integer n (1 ≀ n ≀ 106).The second line of input contains n integers si (0 ≀ si < 217).
Output the sum as described above, modulo 109 + 7
Input: 21 2 | Output: 32
Expert
5
553
123
49
9
1,536
C
1536C
C. Diluc and Kaeya
1,500
data structures; dp; hashing; number theory
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of \(n\) characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly \(0\)) on this string, partitioning it into several contiguous pieces, each with length at least \(1\). Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!For a string we define a ratio as \(a:b\) where 'D' appears in it \(a\) times, and 'K' appears \(b\) times. Note that \(a\) or \(b\) can equal \(0\), but not both. Ratios \(a:b\) and \(c:d\) are considered equal if and only if \(a\cdot d = b\cdot c\). For example, for the string 'DDD' the ratio will be \(3:0\), for 'DKD' β€” \(2:1\), for 'DKK' β€” \(1:2\), and for 'KKKKDD' β€” \(2:4\). Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). Description of the test cases follows.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 5 \cdot 10^5\)) β€” the length of the wood.The second line of each test case contains a string \(s\) of length \(n\). Every character of \(s\) will be either 'D' or 'K'.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5 \cdot 10^5\).
For each test case, output \(n\) space separated integers. The \(i\)-th of these numbers should equal the answer for the prefix \(s_{1},s_{2},\dots,s_{i}\).
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.For the second test case, you can split each prefix of length \(i\) into \(i\) blocks 'D'.
Input: 5 3 DDK 6 DDDDDD 4 DKDK 1 D 9 DKDKDDDDK | Output: 1 2 1 1 2 3 4 5 6 1 1 1 2 1 1 1 1 2 1 2 1 1 3
Medium
4
1,470
492
156
15
1,955
C
1955C
C. Inhabitant of the Deep Sea
1,300
greedy; implementation; math
\(n\) ships set out to explore the depths of the ocean. The ships are numbered from \(1\) to \(n\) and follow each other in ascending order; the \(i\)-th ship has a durability of \(a_i\).The Kraken attacked the ships \(k\) times in a specific order. First, it attacks the first of the ships, then the last, then the first again, and so on.Each attack by the Kraken reduces the durability of the ship by \(1\). When the durability of the ship drops to \(0\), it sinks and is no longer subjected to attacks (thus the ship ceases to be the first or last, and the Kraken only attacks the ships that have not yet sunk). If all the ships have sunk, the Kraken has nothing to attack and it swims away.For example, if \(n=4\), \(k=5\), and \(a=[1, 2, 4, 3]\), the following will happen: The Kraken attacks the first ship, its durability becomes zero and now \(a = [2, 4, 3]\); The Kraken attacks the last ship, now \(a = [2, 4, 2]\); The Kraken attacks the first ship, now \(a = [1, 4, 2]\); The Kraken attacks the last ship, now \(a = [1, 4, 1]\); The Kraken attacks the first ship, its durability becomes zero and now \(a = [4, 1]\). How many ships were sunk after the Kraken's attack?
The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le n \le 2 \cdot 10^5\), \(1 \le k \le 10^{15}\)) β€” the number of ships and how many times the Kraken will attack the ships.The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)) β€” the durability of the ships.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output the number of ships sunk by the Kraken on a separate line.
Input: 64 51 2 4 34 61 2 4 35 202 7 1 8 22 23 22 151 52 75 2 | Output: 2 3 5 0 2 2
Easy
3
1,179
521
85
19
491
C
491C
C. Deciphering
2,300
flows; graph matchings
One day Maria Ivanovna found a Sasha's piece of paper with a message dedicated to Olya. Maria Ivanovna wants to know what is there in a message, but unfortunately the message is ciphered. Maria Ivanovna knows that her students usually cipher their messages by replacing each letter of an original message by some another letter. Replacement works in such way that same letters are always replaced with some fixed letter, and different letters are always replaced by different letters. Maria Ivanovna supposed that the message contains answers to the final exam (since its length is equal to the number of final exam questions). On the other hand she knows that Sasha's answer are not necessary correct. There are K possible answers for each questions. Of course, Maria Ivanovna knows correct answers.Maria Ivanovna decided to decipher message in such way that the number of Sasha's correct answers is maximum possible. She is very busy now, so your task is to help her.
First line contains length of both strings N (1 ≀ N ≀ 2 000 000) and an integer K β€” number of possible answers for each of the questions (1 ≀ K ≀ 52). Answers to the questions are denoted as Latin letters abcde...xyzABCDE...XYZ in the order. For example for K = 6, possible answers are abcdef and for K = 30 possible answers are abcde...xyzABCD.Second line contains a ciphered message string consisting of Latin letters.Third line contains a correct answers string consisting of Latin letters.
In the first line output maximum possible number of correct Sasha's answers.In the second line output cipher rule as the string of length K where for each letter from the students' cipher (starting from 'a' as mentioned above) there is specified which answer does it correspond to.If there are several ways to produce maximum answer, output any of them.
Input: 10 2aaabbbaaabbbbbabbbbb | Output: 7ba
Expert
2
969
493
353
4
772
E
772E
E. Verifying Kingdom
3,200
binary search; divide and conquer; interactive; trees
This is an interactive problem.The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2n - 1 nodes in the tree. The leaves of the judge's tree has labels from 1 to n. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.A question consists of printing the label of three distinct leaves a1, a2, a3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let LCA(a, b) denote the node with maximum depth that is a common ancestor of the nodes a and b.Consider X = LCA(a1, a2), Y = LCA(a2, a3), Z = LCA(a3, a1). The judge will tell you which one of X, Y, Z has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties. More specifically, if X (or Y, Z respectively) maximizes the depth, the judge will respond with the string ""X"" (or ""Y"", ""Z"" respectively). You may only ask at most 10Β·n questions.
The first line of input will contain a single integer n (3 ≀ n ≀ 1 000) β€” the number of leaves in the tree.
To print the final answer, print out the string ""-1"" on its own line. Then, the next line should contain 2n - 1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root.Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to n. Here, isomorphic means that there exists a permutation Ο€ such that node i is the parent of node j in the judge tree if and only node Ο€(i) is the parent of node Ο€(j) in your tree.
For the first sample, the judge has the hidden tree:Here is a more readable format of the interaction: The last line can also be 8 6 9 8 9 7 -1 6 7.
Input: 5XZYYX | Output: 1 4 21 2 42 4 12 3 52 4 3-1-1 1 1 2 2 3 3 6 6
Master
4
1,147
107
547
7
1,481
B
1481B
B. New Colony
1,100
brute force; greedy; implementation
After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you). You are given an array \(h_1, h_2, \dots, h_n\), where \(h_i\) is the height of the \(i\)-th mountain, and \(k\) β€” the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is \(h_i\)): if \(h_i \ge h_{i + 1}\), the boulder will roll to the next mountain; if \(h_i < h_{i + 1}\), the boulder will stop rolling and increase the mountain height by \(1\) (\(h_i = h_i + 1\)); if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the \(k\)-th boulder or determine that it will fall into the waste collection system.
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases.Each test case consists of two lines. The first line in each test case contains two integers \(n\) and \(k\) (\(1 \le n \le 100\); \(1 \le k \le 10^9\)) β€” the number of mountains and the number of boulders.The second line contains \(n\) integers \(h_1, h_2, \dots, h_n\) (\(1 \le h_i \le 100\)) β€” the height of the mountains.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(100\).
For each test case, print \(-1\) if the \(k\)-th boulder will fall into the collection system. Otherwise, print the position of the \(k\)-th boulder.
Let's simulate the first case: The first boulder starts at \(i = 1\); since \(h_1 \ge h_2\) it rolls to \(i = 2\) and stops there because \(h_2 < h_3\). The new heights are \([4,2,2,3]\). The second boulder starts at \(i = 1\); since \(h_1 \ge h_2\) the boulder rolls to \(i = 2\); since \(h_2 \ge h_3\) the boulder rolls to \(i = 3\) and stops there because \(h_3 < h_4\). The new heights are \([4,2,3,3]\). The third boulder starts at \(i = 1\); since \(h_1 \ge h_2\) it rolls to \(i = 2\) and stops there because \(h_2 < h_3\). The new heights are \([4,3,3,3]\). The positions where each boulder stopped are the following: \([2,3,2]\).In the second case, all \(7\) boulders will stop right at the first mountain rising its height from \(1\) to \(8\).The third case is similar to the first one but now you'll throw \(5\) boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to \([4, 3, 3, 3]\), that's why the other two boulders will fall into the collection system.In the fourth case, the first and only boulders will fall straight into the collection system.
Input: 4 4 3 4 1 2 3 2 7 1 8 4 5 4 1 2 3 3 1 5 3 1 | Output: 2 1 -1 -1
Easy
3
1,000
504
149
14
1,428
H
1428H
H. Rotary Laser Lock
3,500
binary search; interactive
This is an interactive problem.To prevent the mischievous rabbits from freely roaming around the zoo, Zookeeper has set up a special lock for the rabbit enclosure. This lock is called the Rotary Laser Lock. The lock consists of \(n\) concentric rings numbered from \(0\) to \(n-1\). The innermost ring is ring \(0\) and the outermost ring is ring \(n-1\). All rings are split equally into \(nm\) sections each. Each of those rings contains a single metal arc that covers exactly \(m\) contiguous sections. At the center of the ring is a core and surrounding the entire lock are \(nm\) receivers aligned to the \(nm\) sections. The core has \(nm\) lasers that shine outward from the center, one for each section. The lasers can be blocked by any of the arcs. A display on the outside of the lock shows how many lasers hit the outer receivers. In the example above, there are \(n=3\) rings, each covering \(m=4\) sections. The arcs are colored in green (ring \(0\)), purple (ring \(1\)), and blue (ring \(2\)) while the lasers beams are shown in red. There are \(nm=12\) sections and \(3\) of the lasers are not blocked by any arc, thus the display will show \(3\) in this case. Wabbit is trying to open the lock to free the rabbits, but the lock is completely opaque, and he cannot see where any of the arcs are. Given the relative positions of the arcs, Wabbit can open the lock on his own. To be precise, Wabbit needs \(n-1\) integers \(p_1,p_2,\ldots,p_{n-1}\) satisfying \(0 \leq p_i < nm\) such that for each \(i\) \((1 \leq i < n)\), Wabbit can rotate ring \(0\) clockwise exactly \(p_i\) times such that the sections that ring \(0\) covers perfectly aligns with the sections that ring \(i\) covers. In the example above, the relative positions are \(p_1 = 1\) and \(p_2 = 7\). To operate the lock, he can pick any of the \(n\) rings and rotate them by \(1\) section either clockwise or anti-clockwise. You will see the number on the display after every rotation.Because his paws are small, Wabbit has asked you to help him to find the relative positions of the arcs after all of your rotations are completed. You may perform up to \(15000\) rotations before Wabbit gets impatient.
The first line consists of 2 integers \(n\) and \(m\) \((2 \leq n \leq 100, 2 \leq m \leq 20)\), indicating the number of rings and the number of sections each ring covers.
For the first test, the configuration is the same as shown on the picture from the statement. After the first rotation (which is rotating ring \(0\) clockwise by \(1\) section), we obtain the following configuration: After the second rotation (which is rotating ring \(2\) counter-clockwise by \(1\) section), we obtain the following configuration: After the third rotation (which is rotating ring \(1\) clockwise by \(1\) section), we obtain the following configuration: If we rotate ring \(0\) clockwise once, we can see that the sections ring \(0\) covers will be the same as the sections that ring \(1\) covers, hence \(p_1=1\).If we rotate ring \(0\) clockwise five times, the sections ring \(0\) covers will be the same as the sections that ring \(2\) covers, hence \(p_2=5\).Note that if we will make a different set of rotations, we can end up with different values of \(p_1\) and \(p_2\) at the end.
Input: 3 4 4 4 3 | Output: ? 0 1 ? 2 -1 ? 1 1 ! 1 5
Master
2
2,186
172
0
14
1,227
A
1227A
A. Math Problem
1,100
math
Your math teacher gave you the following problem:There are \(n\) segments on the \(x\)-axis, \([l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]\). The segment \([l; r]\) includes the bounds, i.e. it is a set of such \(x\) that \(l \le x \le r\). The length of the segment \([l; r]\) is equal to \(r - l\).Two segments \([a; b]\) and \([c; d]\) have a common point (intersect) if there exists \(x\) that \(a \leq x \leq b\) and \(c \leq x \leq d\). For example, \([2; 5]\) and \([3; 10]\) have a common point, but \([5; 6]\) and \([1; 4]\) don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given \(n\) segments.In other words, you need to find a segment \([a; b]\), such that \([a; b]\) and every \([l_i; r_i]\) have a common point for each \(i\), and \(b-a\) is minimal.
The first line contains integer number \(t\) (\(1 \le t \le 100\)) β€” the number of test cases in the input. Then \(t\) test cases follow.The first line of each test case contains one integer \(n\) (\(1 \le n \le 10^{5}\)) β€” the number of segments. The following \(n\) lines contain segment descriptions: the \(i\)-th of them contains two integers \(l_i,r_i\) (\(1 \le l_i \le r_i \le 10^{9}\)).The sum of all values \(n\) over all the test cases in the input doesn't exceed \(10^5\).
For each test case, output one integer β€” the smallest possible length of the segment which has at least one common point with all given segments.
In the first test case of the example, we can choose the segment \([5;7]\) as the answer. It is the shortest segment that has at least one common point with all given segments.
Input: 4 3 4 5 5 9 7 7 5 11 19 4 17 16 16 3 12 14 17 1 1 10 1 1 1 | Output: 2 4 0 0
Easy
1
1,003
483
145
12
1,913
C
1913C
C. Game with Multiset
1,300
binary search; bitmasks; brute force; greedy
In this problem, you are initially given an empty multiset. You have to process two types of queries: ADD \(x\) β€” add an element equal to \(2^{x}\) to the multiset; GET \(w\) β€” say whether it is possible to take the sum of some subset of the current multiset and get a value equal to \(w\).
The first line contains one integer \(m\) (\(1 \le m \le 10^5\)) β€” the number of queries.Then \(m\) lines follow, each of which contains two integers \(t_i\), \(v_i\), denoting the \(i\)-th query. If \(t_i = 1\), then the \(i\)-th query is ADD \(v_i\) (\(0 \le v_i \le 29\)). If \(t_i = 2\), then the \(i\)-th query is GET \(v_i\) (\(0 \le v_i \le 10^9\)).
For each GET query, print YES if it is possible to choose a subset with sum equal to \(w\), or NO if it is impossible.
Input: 51 01 01 02 32 4 | Output: YES NO
Easy
4
290
356
118
19
710
F
710F
F. String Set Queries
2,400
brute force; data structures; hashing; interactive; string suffix structures; strings
You should process m queries over a set D of strings. Each query is one of three kinds: Add a string s to the set D. It is guaranteed that the string s was not added before. Delete a string s from the set D. It is guaranteed that the string s is in the set D. For the given string s find the number of occurrences of the strings from the set D. If some string p from D has several occurrences in s you should count all of them. Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query of the third type. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
The first line contains integer m (1 ≀ m ≀ 3Β·105) β€” the number of queries.Each of the next m lines contains integer t (1 ≀ t ≀ 3) and nonempty string s β€” the kind of the query and the string to process. All strings consist of only lowercase English letters.The sum of lengths of all strings in the input will not exceed 3Β·105.
For each query of the third kind print the only integer c β€” the desired number of occurrences in the string s.
Input: 51 abc3 abcabc2 abc1 aba3 abababc | Output: 22
Expert
6
735
326
110
7
1,439
A1
1439A1
A1. Binary Table (Easy Version)
1,500
constructive algorithms; implementation
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.You are given a binary table of size \(n \times m\). This table consists of symbols \(0\) and \(1\).You can make such operation: select \(3\) different cells that belong to one \(2 \times 2\) square and change the symbols in these cells (change \(0\) to \(1\) and \(1\) to \(0\)).Your task is to make all symbols in the table equal to \(0\). You are allowed to make at most \(3nm\) operations. You don't need to minimize the number of operations.It can be proved that it is always possible.
The first line contains a single integer \(t\) (\(1 \leq t \leq 5000\)) β€” the number of test cases. The next lines contain descriptions of test cases.The first line of the description of each test case contains two integers \(n\), \(m\) (\(2 \leq n, m \leq 100\)).Each of the next \(n\) lines contains a binary string of length \(m\), describing the symbols of the next row of the table.It is guaranteed that the sum of \(nm\) for all test cases does not exceed \(20000\).
For each test case print the integer \(k\) (\(0 \leq k \leq 3nm\)) β€” the number of operations.In the each of the next \(k\) lines print \(6\) integers \(x_1, y_1, x_2, y_2, x_3, y_3\) (\(1 \leq x_1, x_2, x_3 \leq n, 1 \leq y_1, y_2, y_3 \leq m\)) describing the next operation. This operation will be made with three cells \((x_1, y_1)\), \((x_2, y_2)\), \((x_3, y_3)\). These three cells should be different. These three cells should belong into some \(2 \times 2\) square.
In the first test case, it is possible to make only one operation with cells \((1, 1)\), \((2, 1)\), \((2, 2)\). After that, all symbols will be equal to \(0\).In the second test case: operation with cells \((2, 1)\), \((3, 1)\), \((3, 2)\). After it the table will be: 011001000 operation with cells \((1, 2)\), \((1, 3)\), \((2, 3)\). After it the table will be: 000000000 In the fifth test case: operation with cells \((1, 3)\), \((2, 2)\), \((2, 3)\). After it the table will be: 010110 operation with cells \((1, 2)\), \((2, 1)\), \((2, 2)\). After it the table will be: 000000
Input: 5 2 2 10 11 3 3 011 101 110 4 4 1111 0110 0110 1111 5 5 01011 11001 00010 11011 10000 2 3 011 101 | Output: 1 1 1 2 1 2 2 2 2 1 3 1 3 2 1 2 1 3 2 3 4 1 1 1 2 2 2 1 3 1 4 2 3 3 2 4 1 4 2 3 3 4 3 4 4 4 1 2 2 1 2 2 1 4 1 5 2 5 4 1 4 2 5 1 4 4 4 5 3 4 2 1 3 2 2 2 3 1 2 2 1 2 2
Medium
2
699
472
474
14
1,210
E
1210E
E. Wojtek and Card Tricks
2,700
math
Wojtek has just won a maths competition in Byteland! The prize is admirable β€” a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!'The first chapter of the book is 'How to Shuffle \(k\) Cards in Any Order You Want.' It's basically a list of \(n\) intricate methods of shuffling the deck of \(k\) cards in a deterministic way. Specifically, the \(i\)-th recipe can be described as a permutation \((P_{i,1}, P_{i,2}, \dots, P_{i,k})\) of integers from \(1\) to \(k\). If we enumerate the cards in the deck from \(1\) to \(k\) from top to bottom, then \(P_{i,j}\) indicates the number of the \(j\)-th card from the top of the deck after the shuffle.The day is short and Wojtek wants to learn only some of the tricks today. He will pick two integers \(l, r\) (\(1 \le l \le r \le n\)), and he will memorize each trick from the \(l\)-th to the \(r\)-th, inclusive. He will then take a sorted deck of \(k\) cards and repeatedly apply random memorized tricks until he gets bored. He still likes maths, so he started wondering: how many different decks can he have after he stops shuffling it?Wojtek still didn't choose the integers \(l\) and \(r\), but he is still curious. Therefore, he defined \(f(l, r)\) as the number of different decks he can get if he memorizes all the tricks between the \(l\)-th and the \(r\)-th, inclusive. What is the value of$$$\(\sum_{l=1}^n \sum_{r=l}^n f(l, r)?\)$$$
The first line contains two integers \(n\), \(k\) (\(1 \le n \le 200\,000\), \(1 \le k \le 5\)) β€” the number of tricks and the number of cards in Wojtek's deck.Each of the following \(n\) lines describes a single trick and is described by \(k\) distinct integers \(P_{i,1}, P_{i,2}, \dots, P_{i, k}\) (\(1 \le P_{i, j} \le k\)).
Output the value of the sum described in the statement.
Consider the first sample: The first trick swaps two top cards. The second trick takes a card from the bottom and puts it on the top of the deck. The third trick swaps two bottom cards. The first or the third trick allow Wojtek to generate only two distinct decks (either the two cards are swapped or not). Therefore, \(f(1, 1) = f(3, 3) = 2\).The second trick allows him to shuffle the deck in a cyclic order. Therefore, \(f(2,2)=3\).It turns that two first tricks or two last tricks are enough to shuffle the deck in any way desired by Wojtek. Therefore, \(f(1,2) = f(2,3) = f(1,3) = 3! = 6\).
Input: 3 3 2 1 3 3 1 2 1 3 2 | Output: 25
Master
1
1,500
328
55
12
894
C
894C
C. Marco and GCD Sequence
1,900
constructive algorithms; math
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≀ i ≀ j ≀ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.
The first line contains a single integer m (1 ≀ m ≀ 1000) β€” the size of the set S.The second line contains m integers s1, s2, ..., sm (1 ≀ si ≀ 106) β€” the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 < s2 < ... < sm.
If there is no solution, print a single line containing -1.Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000.In the second line print n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the sequence.We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106.If there are multiple solutions, print any of them.
In the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 ≀ i ≀ j ≀ n.
Input: 42 4 6 12 | Output: 34 6 12
Hard
2
812
293
423
8
1,696
A
1696A
A. NIT orz!
800
bitmasks; greedy
NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to \(\operatorname{or} z\). Can you solve this problem too?You are given a 1-indexed array of \(n\) integers, \(a\), and an integer \(z\). You can do the following operation any number (possibly zero) of times: Select a positive integer \(i\) such that \(1\le i\le n\). Then, simutaneously set \(a_i\) to \((a_i\operatorname{or} z)\) and set \(z\) to \((a_i\operatorname{and} z)\). In other words, let \(x\) and \(y\) respectively be the current values of \(a_i\) and \(z\). Then set \(a_i\) to \((x\operatorname{or}y)\) and set \(z\) to \((x\operatorname{and}y)\). Here \(\operatorname{or}\) and \(\operatorname{and}\) denote the bitwise operations OR and AND respectively.Find the maximum possible value of the maximum value in \(a\) after any number (possibly zero) of operations.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). Description of the test cases follows.The first line of each test case contains two integers \(n\) and \(z\) (\(1\le n\le 2000\), \(0\le z<2^{30}\)).The second line of each test case contains \(n\) integers \(a_1\),\(a_2\),\(\ldots\),\(a_n\) (\(0\le a_i<2^{30}\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^4\).
For each test case, print one integer β€” the answer to the problem.
In the first test case of the sample, one optimal sequence of operations is: Do the operation with \(i=1\). Now \(a_1\) becomes \((3\operatorname{or}3)=3\) and \(z\) becomes \((3\operatorname{and}3)=3\). Do the operation with \(i=2\). Now \(a_2\) becomes \((4\operatorname{or}3)=7\) and \(z\) becomes \((4\operatorname{and}3)=0\). Do the operation with \(i=1\). Now \(a_1\) becomes \((3\operatorname{or}0)=3\) and \(z\) becomes \((3\operatorname{and}0)=0\). After these operations, the sequence \(a\) becomes \([3,7]\), and the maximum value in it is \(7\). We can prove that the maximum value in \(a\) can never exceed \(7\), so the answer is \(7\).In the fourth test case of the sample, one optimal sequence of operations is: Do the operation with \(i=1\). Now \(a_1\) becomes \((7\operatorname{or}7)=7\) and \(z\) becomes \((7\operatorname{and}7)=7\). Do the operation with \(i=3\). Now \(a_3\) becomes \((30\operatorname{or}7)=31\) and \(z\) becomes \((30\operatorname{and}7)=6\). Do the operation with \(i=5\). Now \(a_5\) becomes \((27\operatorname{or}6)=31\) and \(z\) becomes \((27\operatorname{and}6)=2\).
Input: 52 33 45 50 2 4 6 81 9105 77 15 30 29 273 3954874310293834 10284344 13635445 | Output: 7 13 11 31 48234367
Beginner
2
949
466
66
16
1,525
A
1525A
A. Potion-making
800
math; number theory
You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly \(k\ \%\) magic essence and \((100 - k)\ \%\) water.In one step, you can pour either one liter of magic essence or one liter of water into the cauldron. What is the minimum number of steps to brew a potion? You don't care about the total volume of the potion, only about the ratio between magic essence and water in it.A small reminder: if you pour \(e\) liters of essence and \(w\) liters of water (\(e + w > 0\)) into the cauldron, then it contains \(\frac{e}{e + w} \cdot 100\ \%\) (without rounding) magic essence and \(\frac{w}{e + w} \cdot 100\ \%\) water.
The first line contains the single \(t\) (\(1 \le t \le 100\)) β€” the number of test cases.The first and only line of each test case contains a single integer \(k\) (\(1 \le k \le 100\)) β€” the percentage of essence in a good potion.
For each test case, print the minimum number of steps to brew a good potion. It can be proved that it's always possible to achieve it in a finite number of steps.
In the first test case, you should pour \(3\) liters of magic essence and \(97\) liters of water into the cauldron to get a potion with \(3\ \%\) of magic essence.In the second test case, you can pour only \(1\) liter of essence to get a potion with \(100\ \%\) of magic essence.In the third test case, you can pour \(1\) liter of magic essence and \(3\) liters of water.
Input: 3 3 100 25 | Output: 100 1 4
Beginner
2
753
231
162
15
1,431
D
1431D
D. Used Markers
1,500
*special; greedy
Your University has a large auditorium and today you are on duty there. There will be \(n\) lectures today β€” all from different lecturers, and your current task is to choose in which order \(ord\) they will happen.Each lecturer will use one marker to write something on a board during their lecture. Unfortunately, markers become worse the more you use them and lecturers may decline using markers which became too bad in their opinion.Formally, the \(i\)-th lecturer has their acceptance value \(a_i\) which means they will not use the marker that was used at least in \(a_i\) lectures already and will ask for a replacement. More specifically: before the first lecture you place a new marker in the auditorium; before the \(ord_j\)-th lecturer (in the order you've chosen) starts, they check the quality of the marker and if it was used in at least \(a_{ord_j}\) lectures before, they will ask you for a new marker; if you were asked for a new marker, then you throw away the old one, place a new one in the auditorium, and the lecturer gives a lecture. You know: the better the marker β€” the easier for an audience to understand what a lecturer has written, so you want to maximize the number of used markers. Unfortunately, the higher-ups watch closely how many markers were spent, so you can't just replace markers before each lecture. So, you have to replace markers only when you are asked by a lecturer. The marker is considered used if at least one lecturer used it for their lecture.You can choose the order \(ord\) in which lecturers will give lectures. Find such order that leads to the maximum possible number of the used markers.
The first line contains one integer \(t\) (\(1 \le t \le 100\)) β€” the number of independent tests.The first line of each test case contains one integer \(n\) (\(1 \le n \le 500\)) β€” the number of lectures and lecturers.The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le n\)) β€” acceptance values of each lecturer.
For each test case, print \(n\) integers β€” the order \(ord\) of lecturers which maximizes the number of used markers. The lecturers are numbered from \(1\) to \(n\) in the order of the input. If there are multiple answers, print any of them.
In the first test case, one of the optimal orders is the following: the \(4\)-th lecturer comes first. The marker is new, so they don't ask for a replacement; the \(1\)-st lecturer comes next. The marker is used once and since \(a_1 = 1\) the lecturer asks for a replacement; the \(3\)-rd lecturer comes next. The second marker is used once and since \(a_3 = 1\) the lecturer asks for a replacement; the \(2\)-nd lecturer comes last. The third marker is used once but \(a_2 = 2\) so the lecturer uses this marker. In total, \(3\) markers are used.In the second test case, \(2\) markers are used.In the third test case, \(3\) markers are used.In the fourth test case, \(3\) markers are used.
Input: 4 4 1 2 1 2 2 2 1 3 1 1 1 4 2 3 1 3 | Output: 4 1 3 2 1 2 3 1 2 4 3 2 1
Medium
2
1,642
361
241
14
1,791
E
1791E
E. Negatives and Positives
1,100
dp; greedy; sortings
Given an array \(a\) consisting of \(n\) elements, find the maximum possible sum the array can have after performing the following operation any number of times: Choose \(2\) adjacent elements and flip both of their signs. In other words choose an index \(i\) such that \(1 \leq i \leq n - 1\) and assign \(a_i = -a_i\) and \(a_{i+1} = -a_{i+1}\).
The input consists of multiple test cases. The first line contains an integer \(t\) (\(1 \leq t \leq 1000\)) β€” the number of test cases. The descriptions of the test cases follow.The first line of each test case contains an integer \(n\) (\(2 \leq n \leq 2\cdot10^5\)) β€” the length of the array.The following line contains \(n\) space-separated integers \(a_1,a_2,\dots,a_n\) (\(-10^9 \leq a_i \leq 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot10^5\).
For each test case, output the maximum possible sum the array can have after performing the described operation any number of times.
For the first test case, by performing the operation on the first two elements, we can change the array from \([-1, -1, -1]\) to \([1, 1, -1]\), and it can be proven this array obtains the maximum possible sum which is \(1 + 1 + (-1) = 1\).For the second test case, by performing the operation on \(-5\) and \(0\), we change the array from \([1, 5, -5, 0, 2]\) to \([1, 5, -(-5), -0, 2] = [1, 5, 5, 0, 2]\), which has the maximum sum since all elements are non-negative. So, the answer is \(1 + 5 + 5 + 0 + 2 = 13\).For the third test case, the array already contains only positive numbers, so performing operations is unnecessary. The answer is just the sum of the whole array, which is \(1 + 2 + 3 = 6\).
Input: 53-1 -1 -151 5 -5 0 231 2 36-1 10 9 8 7 62-1 -1 | Output: 1 13 6 39 2
Easy
3
347
497
132
17
1,742
B
1742B
B. Increasing
800
greedy; implementation; sortings
You are given an array \(a\) of \(n\) positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that \(a_1 < a_2 < \dots < a_n\) holds.
The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)) β€” the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 100\)) β€” the length of the array.The second line of each test case contains \(n\) integers \(a_i\) (\(1 \leq a_i \leq 10^9\)) β€” the elements of the array.
For each test case, output ""YES"" (without quotes) if the array satisfies the condition, and ""NO"" (without quotes) otherwise.You can output the answer in any case (for example, the strings ""yEs"", ""yes"", ""Yes"" and ""YES"" will be recognized as a positive answer).
In the first test case any rearrangement will keep the array \([1,1,1,1]\), which is not strictly increasing.In the second test case, you can make the array \([1,3,4,7,8]\).
Input: 341 1 1 158 7 1 3 415 | Output: NO YES YES
Beginner
3
258
334
271
17
773
E
773E
E. Blog Post Rating
3,000
data structures; sortings
It's well-known that blog posts are an important part of Codeforces platform. Every blog post has a global characteristic changing over time β€” its community rating. A newly created blog post's community rating is 0. Codeforces users may visit the blog post page and rate it, changing its community rating by +1 or -1.Consider the following model of Codeforces users' behavior. The i-th user has his own estimated blog post rating denoted by an integer ai. When a user visits a blog post page, he compares his estimated blog post rating to its community rating. If his estimated rating is higher, he rates the blog post with +1 (thus, the blog post's community rating increases by 1). If his estimated rating is lower, he rates the blog post with -1 (decreasing its community rating by 1). If the estimated rating and the community rating are equal, user doesn't rate the blog post at all (in this case we'll say that user rates the blog post for 0). In any case, after this procedure user closes the blog post page and never opens it again.Consider a newly created blog post with the initial community rating of 0. For each of n Codeforces users, numbered from 1 to n, his estimated blog post rating ai is known.For each k from 1 to n, inclusive, the following question is asked. Let users with indices from 1 to k, in some order, visit the blog post page, rate the blog post and close the page. Each user opens the blog post only after the previous user closes it. What could be the maximum possible community rating of the blog post after these k visits?
The first line contains a single integer n (1 ≀ n ≀ 5Β·105) β€” the number of Codeforces users.The second line contains n integers a1, a2, ..., an ( - 5Β·105 ≀ ai ≀ 5Β·105) β€” estimated blog post ratings for users in order from 1 to n.
For each k from 1 to n, output a single integer equal to the maximum possible community rating of the blog post after users with indices from 1 to k, in some order, visit the blog post page, rate the blog post, and close the page.
Input: 42 0 2 2 | Output: 1122
Master
2
1,556
229
230
7
794
C
794C
C. Naming Company
1,800
games; greedy; sortings
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s β‰  t) if si < ti where i is the smallest index such that si β‰  ti. (so sj = tj for all j < i)
The first line of input contains a string s of length n (1 ≀ n ≀ 3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially.The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.
The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.
One way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx.
Input: tinkoffzscoder | Output: fzfsirk
Medium
3
1,778
367
126
7
1,030
B
1030B
B. Vasya and Cornfield
1,100
geometry
Vasya owns a cornfield which can be defined with two integers \(n\) and \(d\). The cornfield can be represented as rectangle with vertices having Cartesian coordinates \((0, d), (d, 0), (n, n - d)\) and \((n - d, n)\). An example of a cornfield with \(n = 7\) and \(d = 2\). Vasya also knows that there are \(m\) grasshoppers near the field (maybe even inside it). The \(i\)-th grasshopper is at the point \((x_i, y_i)\). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).
The first line contains two integers \(n\) and \(d\) (\(1 \le d < n \le 100\)).The second line contains a single integer \(m\) (\(1 \le m \le 100\)) β€” the number of grasshoppers.The \(i\)-th of the next \(m\) lines contains two integers \(x_i\) and \(y_i\) (\(0 \le x_i, y_i \le n\)) β€” position of the \(i\)-th grasshopper.
Print \(m\) lines. The \(i\)-th line should contain ""YES"" if the position of the \(i\)-th grasshopper lies inside or on the border of the cornfield. Otherwise the \(i\)-th line should contain ""NO"".You can print each letter in any case (upper or lower).
The cornfield from the first example is pictured above. Grasshoppers with indices \(1\) (coordinates \((2, 4)\)) and \(4\) (coordinates \((4, 5)\)) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices \(1\) (coordinates \((4, 4)\)), \(3\) (coordinates \((8, 1)\)) and \(4\) (coordinates \((6, 1)\)) are inside the cornfield.
Input: 7 242 44 16 34 5 | Output: YESNONOYES
Easy
1
686
323
256
10
1,461
C
1461C
C. Random Events
1,500
dp; math; probabilities
Ron is a happy owner of a permutation \(a\) of length \(n\).A permutation of length \(n\) is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array) and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array). Ron's permutation is subjected to \(m\) experiments of the following type: (\(r_i\), \(p_i\)). This means that elements in range \([1, r_i]\) (in other words, the prefix of length \(r_i\)) have to be sorted in ascending order with the probability of \(p_i\). All experiments are performed in the same order in which they are specified in the input data.As an example, let's take a look at a permutation \([4, 2, 1, 5, 3]\) and an experiment (\(3, 0.6\)). After such an experiment with the probability of \(60\%\) the permutation will assume the form \([1, 2, 4, 5, 3]\) and with a \(40\%\) probability it will remain unchanged.You have to determine the probability of the permutation becoming completely sorted in ascending order after \(m\) experiments.
Each test contains one or more test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)).The first line of each test case contains two integers \(n\) and \(m\) \((1 \le n, m \le 10^5)\) β€” the length of the permutation and the number of experiments, respectively.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) \((1 \le a_i \le n)\) β€” contents of the permutation.The following \(m\) lines of each test case each contain an integer \(r_i\) and a real number \(p_i\) \((1 \le r_i \le n, 0 \le p_i \le 1)\) β€” the length of the prefix and the probability of it being sorted. All probabilities are given with at most \(6\) decimal places.It is guaranteed that the sum of \(n\) and the sum of \(m\) does not exceed \(10^5\) (\(\sum n, \sum m \le 10^5\)).
For each test case, print a single number β€” the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed \(10^{-6}\).Formally, let your answer be \(a\), and the jury's answer be \(b\). Your answer is accepted if and only if \(\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}\).
Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the \((4, 0.6)\) experiment.
Input: 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 | Output: 0.600000 0.720000 0.989500 1.000000
Medium
3
1,138
814
393
14
952
C
952C
C. Ravioli Sort
1,600
implementation
Everybody knows of spaghetti sort. You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you...You come up with the following algorithm. For each number in the array ai, build a stack of ai ravioli. The image shows the stack for ai = 4. Arrange the stacks in one row in the order in which the corresponding numbers appear in the input array. Find the tallest one (if there are several stacks of maximal height, use the leftmost one). Remove it and add its height to the end of the output array. Shift the stacks in the row so that there is no gap between them. Repeat the procedure until all stacks have been removed.At first you are very happy with your algorithm, but as you try it on more inputs you realize that it doesn't always produce the right sorted array. Turns out when two stacks of ravioli are next to each other (at any step of the process) and differ in height by two or more, the top ravioli of the taller stack slides down on top of the lower stack.Given an input array, figure out whether the described algorithm will sort it correctly.
The first line of input contains a single number n (1 ≀ n ≀ 10) β€” the size of the array.The second line of input contains n space-separated integers ai (1 ≀ ai ≀ 100) β€” the elements of the array.
Output ""YES"" if the array can be sorted using the described procedure and ""NO"" if it can not.
In the second example the array will change even before the tallest stack is chosen for the first time: ravioli from stack of height 3 will slide on the stack of height 1, and the algorithm will output an array {2, 2, 2}.
Input: 31 2 3 | Output: YES
Medium
1
1,213
195
97
9
818
C
818C
C. Sofa Thief
2,000
brute force; implementation
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same!The storehouse is represented as matrix n Γ— m. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells.Sofa A is standing to the left of sofa B if there exist two such cells a and b that xa < xb, a is covered by A and b is covered by B. Sofa A is standing to the top of sofa B if there exist two such cells a and b that ya < yb, a is covered by A and b is covered by B. Right and bottom conditions are declared the same way. Note that in all conditions A β‰  B. Also some sofa A can be both to the top of another sofa B and to the bottom of it. The same is for left and right conditions.The note also stated that there are cntl sofas to the left of Grandpa Maks's sofa, cntr β€” to the right, cntt β€” to the top and cntb β€” to the bottom.Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions.Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.
The first line contains one integer number d (1 ≀ d ≀ 105) β€” the number of sofas in the storehouse.The second line contains two integer numbers n, m (1 ≀ n, m ≀ 105) β€” the size of the storehouse.Next d lines contains four integer numbers x1, y1, x2, y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” coordinates of the i-th sofa. It is guaranteed that cells (x1, y1) and (x2, y2) have common side, (x1, y1) β‰  (x2, y2) and no cell is covered by more than one sofa.The last line contains four integer numbers cntl, cntr, cntt, cntb (0 ≀ cntl, cntr, cntt, cntb ≀ d - 1).
Print the number of the sofa for which all the conditions are met. Sofas are numbered 1 through d as given in input. If there is no such sofa then print -1.
Let's consider the second example. The first sofa has 0 to its left, 2 sofas to its right ((1, 1) is to the left of both (5, 5) and (5, 4)), 0 to its top and 2 to its bottom (both 2nd and 3rd sofas are below). The second sofa has cntl = 2, cntr = 1, cntt = 2 and cntb = 0. The third sofa has cntl = 2, cntr = 1, cntt = 1 and cntb = 1. So the second one corresponds to the given conditions.In the third example The first sofa has cntl = 1, cntr = 1, cntt = 0 and cntb = 1. The second sofa has cntl = 1, cntr = 1, cntt = 1 and cntb = 0. And there is no sofa with the set (1, 0, 0, 0) so the answer is -1.
Input: 23 23 1 3 21 2 2 21 0 0 1 | Output: 1
Hard
2
1,400
555
156
8
1,002
B4
1002B4
B4. Distinguish four 2-qubit states - 2
1,700
*special
You are given 2 qubits which are guaranteed to be in one of the four orthogonal states: Your task is to perform necessary operations and measurements to figure out which state it was and to return the index of that state (0 for , 1 for etc.). The state of the qubits after the operations does not matter.You have to implement an operation which takes an array of 2 qubits as an input and returns an integer. Your code should have the following signature:namespace Solution { open Microsoft.Quantum.Primitive; open Microsoft.Quantum.Canon; operation Solve (qs : Qubit[]) : Int { body { // your code here } }}
Medium
1
607
0
0
10
1,131
F
1131F
F. Asya And Kittens
1,700
constructive algorithms; dsu
Asya loves animals very much. Recently, she purchased \(n\) kittens, enumerated them from \(1\) and \(n\) and then put them into the cage. The cage consists of one row of \(n\) cells, enumerated with integers from \(1\) to \(n\) from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were \(n - 1\) partitions originally. Initially, each cell contained exactly one kitten with some number.Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day \(i\), Asya: Noticed, that the kittens \(x_i\) and \(y_i\), located in neighboring cells want to play together. Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells. Since Asya has never putted partitions back, after \(n - 1\) days the cage contained a single cell, having all kittens.For every day, Asya remembers numbers of kittens \(x_i\) and \(y_i\), who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into \(n\) cells.
The first line contains a single integer \(n\) (\(2 \le n \le 150\,000\)) β€” the number of kittens.Each of the following \(n - 1\) lines contains integers \(x_i\) and \(y_i\) (\(1 \le x_i, y_i \le n\), \(x_i \ne y_i\)) β€” indices of kittens, which got together due to the border removal on the corresponding day.It's guaranteed, that the kittens \(x_i\) and \(y_i\) were in the different cells before this day.
For every cell from \(1\) to \(n\) print a single integer β€” the index of the kitten from \(1\) to \(n\), who was originally in it.All printed integers must be distinct.It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.
The answer for the example contains one of several possible initial arrangements of the kittens.The picture below shows how the cells were united for this initial arrangement. Note, that the kittens who wanted to play together on each day were indeed in adjacent cells.
Input: 5 1 4 2 5 3 1 4 5 | Output: 3 1 4 2 5
Medium
2
1,295
408
292
11
1,409
A
1409A
A. Yet Another Two Integers Problem
800
greedy; math
You are given two integers \(a\) and \(b\).In one move, you can choose some integer \(k\) from \(1\) to \(10\) and add it to \(a\) or subtract it from \(a\). In other words, you choose an integer \(k \in [1; 10]\) and perform \(a := a + k\) or \(a := a - k\). You may use different values of \(k\) in different moves.Your task is to find the minimum number of moves required to obtain \(b\) from \(a\).You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 2 \cdot 10^4\)) β€” the number of test cases. Then \(t\) test cases follow.The only line of the test case contains two integers \(a\) and \(b\) (\(1 \le a, b \le 10^9\)).
For each test case, print the answer: the minimum number of moves required to obtain \(b\) from \(a\).
In the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: \(13 \rightarrow 23 \rightarrow 32 \rightarrow 42\) (add \(10\), add \(9\), add \(10\)).In the third test case of the example, the following sequence of moves can be applied: \(18 \rightarrow 10 \rightarrow 4\) (subtract \(8\), subtract \(6\)).
Input: 6 5 5 13 42 18 4 1337 420 123456789 1000000000 100500 9000 | Output: 0 3 2 92 87654322 9150
Beginner
2
450
238
102
14
447
B
447B
B. DZY Loves Strings
1,000
greedy; implementation
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
The first line contains a single string s (1 ≀ |s| ≀ 103).The second line contains a single integer k (0 ≀ k ≀ 103).The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Print a single integer β€” the largest possible value of the resulting string DZY could get.
In the test sample DZY can obtain ""abcbbc"", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Input: abc31 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | Output: 41
Beginner
2
469
232
90
4
225
C
225C
C. Barcode
1,700
dp; matrices
You've got an n Γ— m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y.
The first line contains four space-separated integers n, m, x and y (1 ≀ n, m, x, y ≀ 1000; x ≀ y).Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character ""."" represents a white pixel and ""#"" represents a black pixel. The picture description doesn't have any other characters besides ""."" and ""#"".
In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists.
In the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#.
Input: 6 5 1 2##.#..###.###..#...#.##.####.. | Output: 11
Medium
2
503
361
105
2
730
C
730C
C. Bulmart
2,100
binary search; dfs and similar
A new trade empire is rising in Berland. Bulmart, an emerging trade giant, decided to dominate the market of ... shovels! And now almost every city in Berland has a Bulmart store, and some cities even have several of them! The only problem is, at the moment sales are ... let's say a little below estimates. Some people even say that shovels retail market is too small for such a big company to make a profit. But the company management believes in the future of that market and seeks new ways to increase income. There are n cities in Berland connected with m bi-directional roads. All roads have equal lengths. It can happen that it is impossible to reach a city from another city using only roads. There is no road which connects a city to itself. Any pair of cities can be connected by at most one road.There are w Bulmart stores in Berland. Each of them is described by three numbers: ci β€” the number of city where the i-th store is located (a city can have no stores at all or have several of them), ki β€” the number of shovels in the i-th store, pi β€” the price of a single shovel in the i-th store (in burles). The latest idea of the Bulmart management is to create a program which will help customers get shovels as fast as possible for affordable budget. Formally, the program has to find the minimum amount of time needed to deliver rj shovels to the customer in the city gj for the total cost of no more than aj burles. The delivery time between any two adjacent cities is equal to 1. If shovels are delivered from several cities, the delivery time is equal to the arrival time of the last package. The delivery itself is free of charge.The program needs to find answers to q such queries. Each query has to be processed independently from others, i.e. a query does not change number of shovels in stores for the next queries.
The first line contains two integers n, m (1 ≀ n ≀ 5000, 0 ≀ m ≀ min(5000, nΒ·(n - 1) / 2)). Each of the next m lines contains two integers xe and ye, meaning that the e-th road connects cities xe and ye (1 ≀ xe, ye ≀ n).The next line contains a single integer w (1 ≀ w ≀ 5000) β€” the total number of Bulmart stores in Berland. Each of the next w lines contains three integers describing the i-th store: ci, ki, pi (1 ≀ ci ≀ n, 1 ≀ ki, pi ≀ 2Β·105).The next line contains a single integer q (1 ≀ q ≀ 1000) β€” the number of queries. Each of the next q lines contains three integers describing the j-th query: gj, rj and aj (1 ≀ gj ≀ n, 1 ≀ rj, aj ≀ 109)
Output q lines. On the j-th line, print an answer for the j-th query β€” the minimum amount of time needed to deliver rj shovels to the customer in city gj spending no more than aj burles. Print -1 if there is no solution for the j-th query.
Input: 6 44 25 41 23 224 1 23 2 361 2 62 3 73 1 24 3 85 2 56 1 10 | Output: 2-1223-1
Hard
2
1,836
648
239
7
567
F
567F
F. Mausoleum
2,400
dp
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 Γ— 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then β€” non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement: [1, 2, 2, 3, 4, 4, 3, 1]; [1, 1]; [2, 2, 1, 1]; [1, 2, 3, 3, 2, 1]. Suddenly, k more requirements appeared. Each of the requirements has the form: ""h[xi] signi h[yi]"", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≀ xi, yi ≀ 2n) and sign signi.Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
The first line of the input contains integers n and k (1 ≀ n ≀ 35, 0 ≀ k ≀ 100) β€” the number of pairs of blocks and the number of additional requirements.Next k lines contain listed additional requirements, one per line in the format ""xi signi yi"" (1 ≀ xi, yi ≀ 2n), and the sign is on of the list of the five possible signs.
Print the sought number of ways.
Input: 3 0 | Output: 9
Expert
1
1,755
327
32
5
218
A
218A
A. Mountain Scenery
1,100
brute force; constructive algorithms; implementation
Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point (i + 1, yi + 1). For any even i (2 ≀ i ≀ 2n) the following condition holds: yi - 1 < yi and yi > yi + 1. We shall call a vertex of a polyline with an even x coordinate a mountain peak. The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2. Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1, r1), (2, r2), ..., (2n + 1, r2n + 1).Given Bolek's final picture, restore the initial one.
The first line contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 100). The next line contains 2n + 1 space-separated integers r1, r2, ..., r2n + 1 (0 ≀ ri ≀ 100) β€” the y coordinates of the polyline vertices on Bolek's picture.It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.
Print 2n + 1 integers y1, y2, ..., y2n + 1 β€” the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.
Input: 3 20 5 3 5 1 5 2 | Output: 0 5 3 4 1 4 2
Easy
3
1,171
362
173
2
618
D
618D
D. Hamiltonian Spanning Tree
2,200
dfs and similar; dp; graph matchings; greedy; trees
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.
The first line of the input contains three integers n, x and y (2 ≀ n ≀ 200 000, 1 ≀ x, y ≀ 109).Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≀ ui, vi ≀ n) β€” indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.
Print a single integer β€” the minimum number of seconds one needs to spend in order to visit all the cities exactly once.
In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is .In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is .
Input: 5 2 31 21 33 45 3 | Output: 9
Hard
5
818
361
120
6
215
B
215B
B. Olympic Medal
1,300
greedy; math
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0 < r2 < r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested inside the ring.The Olympic jury decided that r1 will take one of possible values of x1, x2, ..., xn. It is up to jury to decide which particular value r1 will take. Similarly, the Olympic jury decided that p1 will take one of possible value of y1, y2, ..., ym, and p2 will take a value from list z1, z2, ..., zk.According to most ancient traditions the ratio between the outer ring mass mout and the inner disk mass min must equal , where A, B are constants taken from ancient books. Now, to start making medals, the jury needs to take values for r1, p1, p2 and calculate the suitable value of r2.The jury wants to choose the value that would maximize radius r2. Help the jury find the sought value of r2. Value r2 doesn't have to be an integer.Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.
The first input line contains an integer n and a sequence of integers x1, x2, ..., xn. The second input line contains an integer m and a sequence of integers y1, y2, ..., ym. The third input line contains an integer k and a sequence of integers z1, z2, ..., zk. The last line contains two integers A and B.All numbers given in the input are positive and do not exceed 5000. Each of the three sequences contains distinct numbers. The numbers in the lines are separated by spaces.
Print a single real number β€” the sought value r2 with absolute or relative error of at most 10 - 6. It is guaranteed that the solution that meets the problem requirements exists.
In the first sample the jury should choose the following values: r1 = 3, p1 = 2, p2 = 1.
Input: 3 1 2 31 23 3 2 11 2 | Output: 2.683281573000
Easy
2
1,196
478
178
2
1,753
F
1753F
F. Minecraft Series
3,500
brute force; two pointers
Little Misha goes to the programming club and solves nothing there. It may seem strange, but when you find out that Misha is filming a Minecraft series, everything will fall into place...Misha is inspired by Manhattan, so he built a city in Minecraft that can be imagined as a table of size \(n \times m\). \(k\) students live in a city, the \(i\)-th student lives in the house, located at the intersection of the \(x_i\)-th row and the \(y_i\)-th column. Also, each student has a degree of his aggressiveness \(w_i\). Since the city turned out to be very large, Misha decided to territorially limit the actions of his series to some square \(s\), which sides are parallel to the coordinate axes. The length of the side of the square should be an integer from \(1\) to \(\min(n, m)\) cells.According to the plot, the main hero will come to the city and accidentally fall into the square \(s\). Possessing a unique degree of aggressiveness \(0\), he will be able to show his leadership qualities and assemble a team of calm, moderate and aggressive students.In order for the assembled team to be versatile and close-knit, degrees of aggressiveness of all students of the team must be pairwise distinct and must form a single segment of consecutive integers. Formally, if there exist students with degrees of aggressiveness \(l, l+1, \ldots, -1, 1, \ldots, r-1, r\) inside the square \(s\), where \(l \le 0 \le r\), the main hero will be able to form a team of \(r-l+1\) people (of course, he is included in this team).Notice, that it is not required to take all students from square \(s\) to the team.Misha thinks that the team should consist of at least \(t\) people. That is why he is interested, how many squares are there in the table in which the main hero will be able to form a team of at least \(t\) people. Help him to calculate this.
The first line contains four integers \(n\), \(m\), \(k\) and \(t\) (\(1 \le n, m \le 40\,000\), \(1 \le n \cdot m \le 40\,000\), \(1 \le k \le 10^6\), \(1 \le t \le k + 1\)) β€” the number of rows and columns in the table, and the number of students living in the city, respectively.Each of the following \(k\) lines contains three integers \(x_i\), \(y_i\) and \(w_i\) (\(1 \le x_i \le n\), \(1 \le y_i \le m\), \(1 \le \lvert w_i \rvert \le 10^9\)) β€” the number of row and column, where the \(i\)-th student is living, and the degree of his aggressiveness.
Print one integer β€” the number of ways to choose the square \(s\) in such way that the main hero will be able to form a team of at least \(t\) people.
In the first example the main hero will not be able to form a team of more than one person in any square \(s\). Illustration for the first example. In the second example there are two ways to select square \(s\). Both of them are illustrated below. In one of them the main hero will be able to form a team of students with degrees of aggressiveness \([0, 1]\), and in the another β€” with degrees of aggressiveness \([0, 1, 2]\). Notice, that the main hero with degree of aggressiveness \(0\) will be included to the team regardless of the chosen square. Illustration for the second example. In the third example there are four ways to select square \(s\). All of them are illustrated below. The main hero will be able to form a team with degrees of aggressiveness: \([-1,0,1]\), \([0,1]\), \([0,1]\), \([-1, 0, 1]\), respectively. Illustration for the third example.
Input: 2 2 1 2 1 1 2 | Output: 0
Master
2
1,842
557
150
17
131
C
131C
C. The World is a Theatre
1,400
combinatorics; math
There are n boys and m girls attending a theatre club. To set a play ""The Big Bang Theory"", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.Perform all calculations in the 64-bit type: long long for Π‘/Π‘++, int64 for Delphi and long for Java.
The only line of the input data contains three integers n, m, t (4 ≀ n ≀ 30, 1 ≀ m ≀ 30, 5 ≀ t ≀ n + m).
Find the required number of ways.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Input: 5 2 5 | Output: 10
Easy
2
451
104
181
1
62
A
62A
A. A Student's Dream
1,300
greedy; math
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych.The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams. So the professor began: ""Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has al fingers on her left hand and ar fingers on the right one. The boy correspondingly has bl and br fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. And in addition, no three fingers of the boy should touch each other. Determine if they can hold hands so that the both were comfortable.""The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.
The first line contains two positive integers not exceeding 100. They are the number of fingers on the Venusian girl's left and right hand correspondingly. The second line contains two integers not exceeding 100. They are the number of fingers on the Marsian boy's left and right hands correspondingly.
Print YES or NO, that is, the answer to Petr Palych's question.
The boy and the girl don't really care who goes to the left.
Input: 5 110 5 | Output: YES
Easy
2
1,553
302
63
0
802
M
802M
M. April Fools' Problem (easy)
1,200
greedy; sortings
The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!
The first line of the input contains two space-separated integers n and k (1 ≀ k ≀ n ≀ 2200). The second line contains n space-separated integers a1, ..., an (1 ≀ ai ≀ 104).
Output one number.
Input: 8 51 1 1 1 1 1 1 1 | Output: 5
Easy
2
534
173
18
8
2,122
E
2122E
E. Greedy Grid Counting
2,600
combinatorics; dp; greedy; math
A path in a grid is called greedy if it starts at the top-left cell and moves only to the right or downward, always moving to its neighbor with the greater value (or either if the values are equal).The value of a path is the sum of the values of the cells it visits, including the start and end.Given a partially filled \(2 \times n\) grid of integers between \(1\) and \(k\), count the number of ways to fill the empty cells such that in every subgrid\(^{\text{βˆ—}}\), there exists a greedy path that achieves the maximum value out of all down/right paths. Since the answer may be large, calculate it modulo \(998\,244\,353\).\(^{\text{βˆ—}}\) A subgrid of a \(2 \times n\) grid \(a_{i,j}\) is a grid formed from all cells \(a_{x,y}\) such that \(l_x \leq x \leq r_x\), \(l_y \leq y \leq r_y\) for some \(1 \leq l_x \leq r_x \leq 2\), \(1 \leq l_y \leq r_y \leq n\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(k\) (\(1 \leq n, k \leq 500\)) β€” the number of columns and the range of integers in the grid, respectively.Then two lines follow, the \(i\)-th line containing \(n\) integers \(a_{i,1}, a_{i,2}, \ldots, a_{i,n}\) (\(-1 \leq a_{i,j} \leq k\), \(a_{i,j} \neq 0\)) β€” the values of cells in the \(i\)-th row of the grid, where \(-1\) represents an empty cell.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(500\).
For each test case, output a single integer β€” the number of ways to fill the grid that satisfy the above conditions, modulo \(998\,244\,353\).
In the first test case, the grids that satisfy the conditions are: $$$\( \begin{bmatrix} 2 & 1 & 1 & 2 \\ 2 & 1 & 1 & 3 \end{bmatrix},\: \begin{bmatrix} 2 & 1 & 1 & 2 \\ 2 & 2 & 1 & 3 \end{bmatrix},\: \begin{bmatrix} 2 & 1 & 1 & 2 \\ 2 & 3 & 1 & 3 \end{bmatrix},\: \begin{bmatrix} 2 & 1 & 2 & 2 \\ 2 & 2 & 1 & 3 \end{bmatrix},\: \begin{bmatrix} 2 & 1 & 2 & 2 \\ 2 & 3 & 1 & 3 \end{bmatrix},\: \begin{bmatrix} 2 & 1 & 3 & 2 \\ 2 & 3 & 1 & 3 \end{bmatrix}. \)$$$In the second test case, all ways to fill the grid satisfy the conditions.
Input: 34 32 1 -1 22 -1 1 35 41 3 -1 4 2-1 3 4 2 -110 10-1 -1 -1 -1 -1 -1 -1 -1 -1 -1-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 | Output: 6 64 123782927
Expert
4
864
665
142
21
550
D
550D
D. Regular Bridge
1,900
constructive algorithms; graphs; implementation
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
The single line of the input contains integer k (1 ≀ k ≀ 100) β€” the required degree of the vertices of the regular graph.
Print ""NO"" (without quotes), if such graph doesn't exist. Otherwise, print ""YES"" in the first line and the description of any suitable graph in the next lines.The description of the made graph must start with numbers n and m β€” the number of vertices and edges respectively. Each of the next m lines must contain two integers, a and b (1 ≀ a, b ≀ n, a β‰  b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Input: 1 | Output: YES2 11 2
Hard
3
335
121
979
5
1,927
A
1927A
A. Make it White
800
greedy; strings
You have a horizontal strip of \(n\) cells. Each cell is either white or black.You can choose a continuous segment of cells once and paint them all white. After this action, all the black cells in this segment will become white, and the white ones will remain white.What is the minimum length of the segment that needs to be painted white in order for all \(n\) cells to become white?
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. The descriptions of the test cases follow.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10\)) β€” the length of the strip.The second line of each test case contains a string \(s\), consisting of \(n\) characters, each of which is either 'W' or 'B'. The symbol 'W' denotes a white cell, and 'B' β€” a black one. It is guaranteed that at least one cell of the given strip is black.
For each test case, output a single number β€” the minimum length of a continuous segment of cells that needs to be painted white in order for the entire strip to become white.
In the first test case of the example for the strip ""WBBWBW"", the minimum length of the segment to be repainted white is \(4\). It is necessary to repaint to white the segment from the \(2\)-nd to the \(5\)-th cell (the cells are numbered from \(1\) from left to right).
Input: 86WBBWBW1B2WB3BBW4BWWB6BWBWWB6WWBBWB9WBWBWWWBW | Output: 4 1 1 2 4 6 4 7
Beginner
2
384
520
174
19
986
E
986E
E. Prince's Problem
2,800
brute force; data structures; math; number theory; trees
Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem.You are given a tree with \(n\) vertices.In each vertex \(v\) there is positive integer \(a_{v}\).You have to answer \(q\) queries.Each query has a from \(u\) \(v\) \(x\).You have to calculate \(\prod_{w \in P} gcd(x, a_{w}) \mod (10^{9} + 7)\), where \(P\) is a set of vertices on path from \(u\) to \(v\). In other words, you are to calculate the product of \(gcd(x, a_{w})\) for all vertices \(w\) on the path from \(u\) to \(v\). As it might be large, compute it modulo \(10^9+7\). Here \(gcd(s, t)\) denotes the greatest common divisor of \(s\) and \(t\).Note that the numbers in vertices do not change after queries.I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them.
In the first line of input there is one integer \(n\) (\(1 \le n \le 10^{5}\)) β€” the size of the tree.In the next \(n-1\) lines the edges of the tree are described. The \(i\)-th edge is described with two integers \(u_{i}\) and \(v_{i}\) (\(1 \le u_{i}, v_{i} \le n\)) and it connects the vertices \(u_{i}\) and \(v_{i}\). It is guaranteed that graph with these edges is a tree.In the next line there are \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_{v} \le 10^{7}\)).In the next line there is one integer \(q\) (\(1 \le q \le 10^{5}\)) β€” the number of queries.And in the next \(q\) lines the queries are described. Each query is described with three integers \(u_{i}\), \(v_{i}\) and \(x_{i}\) (\(1 \le u_{i}, v_{i} \le n\), \(1 \le x_{i} \le 10^{7}\)).
Print \(q\) numbers β€” the answers to the queries in the order they are given in the input. Print each answer modulo \(10^9+7 = 1000000007\). Print each number on a separate line.
Input: 41 21 31 46 4 9 532 3 62 3 23 4 7 | Output: 3641
Master
5
1,213
761
178
9