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
1,557
D
1557D
D. Ezzat and Grid
2,200
data structures; dp; greedy
Moamen was drawing a grid of \(n\) rows and \(10^9\) columns containing only digits \(0\) and \(1\). Ezzat noticed what Moamen was drawing and became interested in the minimum number of rows one needs to remove to make the grid beautiful.A grid is beautiful if and only if for every two consecutive rows there is at least one column containing \(1\) in these two rows.Ezzat will give you the number of rows \(n\), and \(m\) segments of the grid that contain digits \(1\). Every segment is represented with three integers \(i\), \(l\), and \(r\), where \(i\) represents the row number, and \(l\) and \(r\) represent the first and the last column of the segment in that row.For example, if \(n = 3\), \(m = 6\), and the segments are \((1,1,1)\), \((1,7,8)\), \((2,7,7)\), \((2,15,15)\), \((3,1,1)\), \((3,15,15)\), then the grid is: Your task is to tell Ezzat the minimum number of rows that should be removed to make the grid beautiful.
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 3\cdot10^5\)).Each of the next \(m\) lines contains three integers \(i\), \(l\), and \(r\) (\(1 \le i \le n\), \(1 \le l \le r \le 10^9\)). Each of these \(m\) lines means that row number \(i\) contains digits \(1\) in columns from \(l\) to \(r\), inclusive.Note that the segments may overlap.
In the first line, print a single integer \(k\) β€” the minimum number of rows that should be removed.In the second line print \(k\) distinct integers \(r_1, r_2, \ldots, r_k\), representing the rows that should be removed (\(1 \le r_i \le n\)), in any order.If there are multiple answers, print any.
In the first test case, the grid is the one explained in the problem statement. The grid has the following properties: The \(1\)-st row and the \(2\)-nd row have a common \(1\) in the column \(7\). The \(2\)-nd row and the \(3\)-rd row have a common \(1\) in the column \(15\). As a result, this grid is beautiful and we do not need to remove any row.In the second test case, the given grid is as follows:
Input: 3 6 1 1 1 1 7 8 2 7 7 2 15 15 3 1 1 3 15 15 | Output: 0
Hard
3
935
364
298
15
1,252
C
1252C
C. Even Path
1,600
data structures; implementation
Pathfinding is a task of finding a route between two points. It often appears in many problems. For example, in a GPS navigation software where a driver can query for a suggested route, or in a robot motion planning where it should find a valid sequence of movements to do some tasks, or in a simple maze solver where it should find a valid path from one point to another point. This problem is related to solving a maze.The maze considered in this problem is in the form of a matrix of integers \(A\) of \(N \times N\). The value of each cell is generated from a given array \(R\) and \(C\) of \(N\) integers each. Specifically, the value on the \(i^{th}\) row and \(j^{th}\) column, cell \((i,j)\), is equal to \(R_i + C_j\). Note that all indexes in this problem are from \(1\) to \(N\).A path in this maze is defined as a sequence of cells \((r_1,c_1), (r_2,c_2), \dots, (r_k,c_k)\) such that \(|r_i - r_{i+1}| + |c_i - c_{i+1}| = 1\) for all \(1 \le i < k\). In other words, each adjacent cell differs only by \(1\) row or only by \(1\) column. An even path in this maze is defined as a path in which all the cells in the path contain only even numbers.Given a tuple \(\langle r_a,c_a,r_b,c_b \rangle\) as a query, your task is to determine whether there exists an even path from cell \((r_a,c_a)\) to cell \((r_b,c_b)\). To simplify the problem, it is guaranteed that both cell \((r_a,c_a)\) and cell \((r_b,c_b)\) contain even numbers.For example, let \(N = 5\), \(R = \{6, 2, 7, 8, 3\}\), and \(C = \{3, 4, 8, 5, 1\}\). The following figure depicts the matrix \(A\) of \(5 \times 5\) which is generated from the given array \(R\) and \(C\). Let us consider several queries: \(\langle 2, 2, 1, 3 \rangle\): There is an even path from cell \((2,2)\) to cell \((1,3)\), e.g., \((2,2), (2,3), (1,3)\). Of course, \((2,2), (1,2), (1,3)\) is also a valid even path. \(\langle 4, 2, 4, 3 \rangle\): There is an even path from cell \((4,2)\) to cell \((4,3)\), namely \((4,2), (4,3)\). \(\langle 5, 1, 3, 4 \rangle\): There is no even path from cell \((5,1)\) to cell \((3,4)\). Observe that the only two neighboring cells of \((5,1)\) are cell \((5,2)\) and cell \((4,1)\), and both of them contain odd numbers (7 and 11, respectively), thus, there cannot be any even path originating from cell \((5,1)\).
Input begins with a line containing two integers: \(N\) \(Q\) (\(2 \le N \le 100\,000\); \(1 \le Q \le 100\,000\)) representing the size of the maze and the number of queries, respectively. The next line contains \(N\) integers: \(R_i\) (\(0 \le R_i \le 10^6\)) representing the array \(R\). The next line contains \(N\) integers: \(C_i\) (\(0 \le C_i \le 10^6\)) representing the array \(C\). The next \(Q\) lines each contains four integers: \(r_a\) \(c_a\) \(r_b\) \(c_b\) (\(1 \le r_a, c_a, r_b, c_b \le N\)) representing a query of \(\langle r_a, c_a, r_b, c_b \rangle\). It is guaranteed that \((r_a,c_a)\) and \((r_b,c_b)\) are two different cells in the maze and both of them contain even numbers.
For each query in the same order as input, output in a line a string ""YES"" (without quotes) or ""NO"" (without quotes) whether there exists an even path from cell \((r_a,c_a)\) to cell \((r_b,c_b)\).
Explanation for the sample input/output #1This is the example from the problem description.
Input: 5 3 6 2 7 8 3 3 4 8 5 1 2 2 1 3 4 2 4 3 5 1 3 4 | Output: YES YES NO
Medium
2
2,306
705
201
12
1,056
C
1056C
C. Pick Heroes
1,700
greedy; implementation; interactive; sortings
Don't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are \(2\) teams each having \(n\) players and \(2n\) heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the \(i\)-th of the heroes as \(p_i\). Each team wants to maximize the total power of its heroes. However, there is one exception: there are \(m\) pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of \(q\) or greater regardless of jury's program choices, you must get \(q\) or greater to pass a test.
The first line contains two integers \(n\) and \(m\) (\(1 \le n \le 10^3\), \(0 \le m \le n\)) β€” the number of players in one team and the number of special pairs of heroes.The second line contains \(2n\) integers \(p_1, p_2, \ldots, p_{2n}\) (\(1 \le p_i \le 10^3\)) β€” the powers of the heroes.Each of the next \(m\) lines contains two integer \(a\) and \(b\) (\(1 \le a, b \le 2n\), \(a \ne b\)) β€” a pair of heroes that are especially strong against each other. It is guaranteed that each hero appears at most once in this list.The next line contains a single integer \(t\) (\(1 \le t \le 2\)) β€” the team you are to play for. If \(t = 1\), the first turn is yours, otherwise you have the second turn.HacksIn order to hack, use the format described above with one additional line. In this line output \(2n\) distinct integers from \(1\) to \(2n\) β€” the priority order for the jury's team. The jury's team will on each turn select the first possible hero from this list. Here possible means that it is not yet taken and does not contradict the rules about special pair of heroes.
In the first example the first turn is yours. In example, you choose \(6\), the other team is forced to reply with \(2\). You choose \(5\), the other team chooses \(4\). Finally, you choose \(3\) and the other team choose \(1\).In the second example you have the second turn. The other team chooses \(6\), you choose \(5\), forcing the other team to choose \(1\). Now you choose \(4\), the other team chooses \(3\) and you choose \(2\).
Input: 3 1 1 2 3 4 5 6 2 6 1 2 4 1 | Output: 6 5 3
Medium
4
1,527
1,079
0
10
357
B
357B
B. Flag Day
1,400
constructive algorithms; implementation
In Berland, there is the national holiday coming β€” the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
The first line contains two space-separated integers n (3 ≀ n ≀ 105) and m (1 ≀ m ≀ 105) β€” the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers β€” the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
Input: 7 31 2 31 4 54 6 7 | Output: 1 2 3 3 2 2 1
Easy
2
1,255
422
251
3
1,495
C
1495C
C. Garden of the Sun
2,300
constructive algorithms; graphs
There are many sunflowers in the Garden of the Sun.Garden of the Sun is a rectangular table with \(n\) rows and \(m\) columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burned into ashes. In other words, those cells struck by the lightning became empty. Magically, any two empty cells have no common points (neither edges nor corners).Now the owner wants to remove some (possibly zero) sunflowers to reach the following two goals: When you are on an empty cell, you can walk to any other empty cell. In other words, those empty cells are connected. There is exactly one simple path between any two empty cells. In other words, there is no cycle among the empty cells. You can walk from an empty cell to another if they share a common edge.Could you please give the owner a solution that meets all her requirements?Note that you are not allowed to plant sunflowers. You don't need to minimize the number of sunflowers you remove. It can be shown that the answer always exists.
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1\le t\le 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line contains two integers \(n\), \(m\) (\(1 \le n,m \le 500\)) β€” the number of rows and columns. Each of the next \(n\) lines contains \(m\) characters. Each character is either 'X' or '.', representing an empty cell and a cell that grows a sunflower, respectively.It is guaranteed that the sum of \(n \cdot m\) for all test cases does not exceed \(250\,000\).
For each test case, print \(n\) lines. Each should contain \(m\) characters, representing one row of the table. Each character should be either 'X' or '.', representing an empty cell and a cell with a sunflower, respectively.If there are multiple answers, you can print any. It can be shown that the answer always exists.
Let's use \((x,y)\) to describe the cell on \(x\)-th row and \(y\)-th column.In the following pictures white, yellow, and blue cells stand for the cells that grow a sunflower, the cells lightning stroke, and the cells sunflower on which are removed, respectively.In the first test case, one possible solution is to remove sunflowers on \((1,2)\), \((2,3)\) and \((3 ,2)\). Another acceptable solution is to remove sunflowers on \((1,2)\), \((2,2)\) and \((3,2)\). This output is considered wrong because there are 2 simple paths between any pair of cells (there is a cycle). For example, there are 2 simple paths between \((1,1)\) and \((3,3)\). \((1,1)\to (1,2)\to (1,3)\to (2,3)\to (3,3)\) \((1,1)\to (2,1)\to (3,1)\to (3,2)\to (3,3)\) This output is considered wrong because you can't walk from \((1,1)\) to \((3,3)\).
Input: 5 3 3 X.X ... X.X 4 4 .... .X.X .... .X.X 5 5 .X... ....X .X... ..... X.X.X 1 10 ....X.X.X. 2 2 .. .. | Output: XXX ..X XXX XXXX .X.X .X.. .XXX .X... .XXXX .X... .X... XXXXX XXXXXXXXXX .. ..
Expert
2
1,128
552
321
14
1,837
A
1837A
A. Grasshopper on a Line
800
constructive algorithms; math
You are given two integers \(x\) and \(k\). Grasshopper starts in a point \(0\) on an OX axis. In one move, it can jump some integer distance, that is not divisible by \(k\), to the left or to the right.What's the smallest number of moves it takes the grasshopper to reach point \(x\)? What are these moves? If there are multiple answers, print any of them.
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of testcases.The only line of each testcase contains two integers \(x\) and \(k\) (\(1 \le x \le 100\); \(2 \le k \le 100\)) β€” the endpoint and the constraint on the jumps, respectively.
For each testcase, in the first line, print a single integer \(n\) β€” the smallest number of moves it takes the grasshopper to reach point \(x\).In the second line, print \(n\) integers, each of them not divisible by \(k\). A positive integer would mean jumping to the right, a negative integer would mean jumping to the left. The endpoint after the jumps should be exactly \(x\).Each jump distance should be from \(-10^9\) to \(10^9\). In can be shown that, for any solution with the smallest number of jumps, there exists a solution with the same number of jumps such that each jump is from \(-10^9\) to \(10^9\).It can be shown that the answer always exists under the given constraints. If there are multiple answers, print any of them.
Input: 310 210 33 4 | Output: 2 7 3 1 10 1 3
Beginner
2
357
269
738
18
1,790
D
1790D
D. Matryoshkas
1,200
data structures; greedy; sortings
Matryoshka is a wooden toy in the form of a painted doll, inside which you can put a similar doll of a smaller size.A set of nesting dolls contains one or more nesting dolls, their sizes are consecutive positive integers. Thus, a set of nesting dolls is described by two numbers: \(s\) β€” the size of a smallest nesting doll in a set and \(m\) β€” the number of dolls in a set. In other words, the set contains sizes of \(s, s + 1, \dots, s + m - 1\) for some integer \(s\) and \(m\) (\(s,m > 0\)).You had one or more sets of nesting dolls. Recently, you found that someone mixed all your sets in one and recorded a sequence of doll sizes β€” integers \(a_1, a_2, \dots, a_n\).You do not remember how many sets you had, so you want to find the minimum number of sets that you could initially have.For example, if a given sequence is \(a=[2, 2, 3, 4, 3, 1]\). Initially, there could be \(2\) sets: the first set consisting of \(4\) nesting dolls with sizes \([1, 2, 3, 4]\); a second set consisting of \(2\) nesting dolls with sizes \([2, 3]\). According to a given sequence of sizes of nesting dolls \(a_1, a_2, \dots, a_n\), determine the minimum number of nesting dolls that can make this sequence.Each set is completely used, so all its nesting dolls are used. Each element of a given sequence must correspond to exactly one doll from some set.
The first line of input data contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.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 total number of matryoshkas that were in all sets.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 sizes of the matryoshkas. It is guaranteed that the sum of values of \(n\) over all test cases does not exceed \(2\cdot10^5\).
For each test case, print one integer \(k\) β€” the minimum possible number of matryoshkas sets.
The first test case is described in the problem statement.In the second test case, all matryoshkas could be part of the same set with minimum size \(s=7\).In the third test case, each matryoshka represents a separate set.
Input: 1062 2 3 4 3 1511 8 7 10 961000000000 1000000000 1000000000 1000000000 1000000000 100000000081 1 4 4 2 3 2 361 2 3 2 3 4710 11 11 12 12 13 1378 8 9 9 10 10 1184 14 5 15 6 16 7 1785 15 6 14 8 12 9 1154 2 2 3 4 | Output: 2 1 6 2 2 2 2 2 4 3
Easy
3
1,342
540
94
17
794
E
794E
E. Choosing Carrot
2,800
games; math
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present.There are n carrots arranged in a line. The i-th carrot from the left has juiciness ai. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose.To settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS.Oleg is a sneaky bank client. When Igor goes to a restroom, he performs k moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first. Oleg wonders: for each k such that 0 ≀ k ≀ n - 1, what is the juiciness of the carrot they will give to ZS if he makes k extra moves beforehand and both players play optimally?
The first line of input contains a single integer n (1 ≀ n ≀ 3Β·105) β€” the total number of carrots.The next line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109). Here ai denotes the juiciness of the i-th carrot from the left of the line.
Output n space-separated integers x0, x1, ..., xn - 1. Here, xi denotes the juiciness of the carrot the friends will present to ZS if k = i.
For the first example, When k = 0, one possible optimal game is as follows: Oleg eats the carrot with juiciness 1. Igor eats the carrot with juiciness 5. Oleg eats the carrot with juiciness 2. The remaining carrot has juiciness 3.When k = 1, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2. Igor eats the carrot with juiciness 5. The remaining carrot has juiciness 3.When k = 2, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2 beforehand. Oleg eats the carrot with juiciness 3. The remaining carrot has juiciness 5.When k = 3, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2 beforehand. Oleg eats the carrot with juiciness 3 beforehand. The remaining carrot has juiciness 5.Thus, the answer is 3, 3, 5, 5.For the second sample, Oleg can always eat the carrot with juiciness 1 since he always moves first. So, the remaining carrot will always have juiciness 1000000000.
Input: 41 2 3 5 | Output: 3 3 5 5
Master
2
1,363
255
140
7
87
A
87A
A. Trains
1,500
implementation; math
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every a minutes, but a train goes to Masha's direction every b minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.Help Vasya count to which girlfriend he will go more often.
The first line contains two integers a and b (a β‰  b, 1 ≀ a, b ≀ 106).
Print ""Dasha"" if Vasya will go to Dasha more frequently, ""Masha"" if he will go to Masha more frequently, or ""Equal"" if he will go to both girlfriends with the same frequency.
Let's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0, 6], he will go to both girls equally often. If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute.If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute.If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute.If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction.In sum Masha and Dasha get equal time β€” three minutes for each one, thus, Vasya will go to both girlfriends equally often.
Input: 3 7 | Output: Dasha
Medium
2
1,041
69
180
0
2,026
D
2026D
D. Sums of Segments
1,900
binary search; data structures; dp; implementation; math
You are given a sequence of integers \([a_1, a_2, \dots, a_n]\). Let \(s(l,r)\) be the sum of elements from \(a_l\) to \(a_r\) (i. e. \(s(l,r) = \sum\limits_{i=l}^{r} a_i\)).Let's construct another sequence \(b\) of size \(\frac{n(n+1)}{2}\) as follows: \(b = [s(1,1), s(1,2), \dots, s(1,n), s(2,2), s(2,3), \dots, s(2,n), s(3,3), \dots, s(n,n)]\).For example, if \(a = [1, 2, 5, 10]\), then \(b = [1, 3, 8, 18, 2, 7, 17, 5, 15, 10]\).You are given \(q\) queries. During the \(i\)-th query, you are given two integers \(l_i\) and \(r_i\), and you have to calculate \(\sum \limits_{j=l_i}^{r_i} b_j\).
The first line contains one integer \(n\) (\(1 \le n \le 3 \cdot 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10 \le a_i \le 10\)).The third line contains one integer \(q\) (\(1 \le q \le 3 \cdot 10^5\)).Then \(q\) lines follow, the \(i\)-th of them contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le \frac{n(n+1)}{2}\)).
Print \(q\) integers, the \(i\)-th of which should be equal to \(\sum \limits_{j=l_i}^{r_i} b_j\).
Input: 41 2 5 10151 11 21 31 41 51 105 106 102 83 43 103 85 65 51 8 | Output: 1 4 12 30 32 86 56 54 60 26 82 57 9 2 61
Hard
5
600
369
98
20
217
B
217B
B. Blackboard Fibonacci
2,100
brute force; math
Fibonacci numbers are the sequence of integers: f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ..., fn = fn - 2 + fn - 1. So every next number is the sum of the previous two.Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations: operation ""T"": replace the top number with the sum of both numbers; operation ""B"": replace the bottom number with the sum of both numbers. If he performs n operations, starting with ""T"" and then choosing operations alternately (so that the sequence of operations looks like ""TBTBTBTB...""), the last number written will be equal to fn + 1.Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute f7, then he would want to do n = 6 operations: ""TBTBTB"". If he instead performs the sequence of operations ""TTTBBT"", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations (Β«TTΒ» or Β«BBΒ»).You are given the number n of operations that Bajtek has made in an attempt to compute fn + 1 and the number r that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of n operations resulting in r with that number of mistakes.Assume that Bajtek always correctly starts with operation ""T"".
The first line contains the integers n and r (1 ≀ n, r ≀ 106).
The first line of the output should contain one number β€” the minimum possible number of mistakes made by Bajtek. The second line should contain n characters, starting with ""T"", describing one possible sequence of operations with that number of mistakes. Each character must be either ""T"" or ""B"".If the required sequence doesn't exist, output ""IMPOSSIBLE"" (without quotes).
Input: 6 10 | Output: 2TBBTTB
Hard
2
1,587
62
380
2
903
C
903C
C. Boxes Packing
1,200
greedy
Mishka has got n empty boxes. For every i (1 ≀ i ≀ n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met: i-th box is not put into another box; j-th box doesn't contain any other boxes; box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!
The first line contains one integer n (1 ≀ n ≀ 5000) β€” the number of boxes Mishka has got.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the side length of i-th box.
Print the minimum possible number of visible boxes.
In the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1.
Input: 31 2 3 | Output: 1
Easy
1
543
198
51
9
819
B
819B
B. Mister B and PR Shifts
1,900
data structures; implementation; math
Some time ago Mister B detected a strange signal from the space, which he started to study.After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.Let's define the deviation of a permutation p as .Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.Let's denote id k (0 ≀ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: k = 0: shift p1, p2, ... pn, k = 1: shift pn, p1, ... pn - 1, ..., k = n - 1: shift p2, p3, ... pn, p1.
First line contains single integer n (2 ≀ n ≀ 106) β€” the length of the permutation.The second line contains n space-separated integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of the permutation. It is guaranteed that all elements are distinct.
Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.
In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.
Input: 31 2 3 | Output: 0 0
Hard
3
766
247
153
8
69
D
69D
D. Dot
1,900
dp; games
Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name ""dot"" with the following rules: On the checkered paper a coordinate system is drawn. A dot is initially put in the position (x, y). A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line y = x. Anton and Dasha take turns. Anton goes first. The player after whose move the distance from the dot to the coordinates' origin exceeds d, loses. Help them to determine the winner.
The first line of the input file contains 4 integers x, y, n, d ( - 200 ≀ x, y ≀ 200, 1 ≀ d ≀ 200, 1 ≀ n ≀ 20) β€” the initial coordinates of the dot, the distance d and the number of vectors. It is guaranteed that the initial dot is at the distance less than d from the origin of the coordinates. The following n lines each contain two non-negative numbers xi and yi (0 ≀ xi, yi ≀ 200) β€” the coordinates of the i-th vector. It is guaranteed that all the vectors are nonzero and different.
You should print ""Anton"", if the winner is Anton in case of both players play the game optimally, and ""Dasha"" otherwise.
In the first test, Anton goes to the vector (1;2), and Dasha loses. In the second test Dasha with her first move shifts the dot so that its coordinates are (2;3), and Anton loses, as he has the only possible move β€” to reflect relatively to the line y = x. Dasha will respond to it with the same move and return the dot in position (2;3).
Input: 0 0 2 31 11 2 | Output: Anton
Hard
2
728
487
124
0
263
B
263B
B. Squares
900
greedy; implementation; sortings
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square.Vasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly k drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. Help Vasya find a point that would meet the described limits.
The first line contains two space-separated integers n, k (1 ≀ n, k ≀ 50). The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).It is guaranteed that all given squares are distinct.
In a single line print two space-separated integers x and y (0 ≀ x, y ≀ 109) β€” the coordinates of the point that belongs to exactly k squares. If there are multiple answers, you are allowed to print any of them. If there is no answer, print ""-1"" (without the quotes).
Input: 4 35 1 3 4 | Output: 2 1
Beginner
3
590
209
269
2
679
D
679D
D. Bear and Chase
2,900
brute force; dfs and similar; graphs; implementation; math; probabilities
Bearland has n cities, numbered 1 through n. There are m bidirectional roads. The i-th road connects two distinct cities ai and bi. No two roads connect the same pair of cities. It's possible to get from any city to any other city (using one or more roads).The distance between cities a and b is defined as the minimum number of roads used to travel between a and b.Limak is a grizzly bear. He is a criminal and your task is to catch him, or at least to try to catch him. You have only two days (today and tomorrow) and after that Limak is going to hide forever.Your main weapon is BCD (Bear Criminal Detector). Where you are in some city, you can use BCD and it tells you the distance between you and a city where Limak currently is. Unfortunately, BCD can be used only once a day.You don't know much about Limak's current location. You assume that he is in one of n cities, chosen uniformly at random (each city with probability ). You decided for the following plan: Choose one city and use BCD there. After using BCD you can try to catch Limak (but maybe it isn't a good idea). In this case you choose one city and check it. You win if Limak is there. Otherwise, Limak becomes more careful and you will never catch him (you loose). Wait 24 hours to use BCD again. You know that Limak will change his location during that time. In detail, he will choose uniformly at random one of roads from his initial city, and he will use the chosen road, going to some other city. Tomorrow, you will again choose one city and use BCD there. Finally, you will try to catch Limak. You will choose one city and check it. You will win if Limak is there, and loose otherwise. Each time when you choose one of cities, you can choose any of n cities. Let's say it isn't a problem for you to quickly get somewhere.What is the probability of finding Limak, if you behave optimally?
The first line of the input contains two integers n and m (2 ≀ n ≀ 400, ) β€” the number of cities and the number of roads, respectively.Then, m lines follow. The i-th of them contains two integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi) β€” cities connected by the i-th road.No two roads connect the same pair of cities. It's possible to get from any city to any other city.
Print one real number β€” the probability of finding Limak, if you behave optimally. Your answer will be considered correct if its absolute error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if |a - b| ≀ 10 - 6.
In the first sample test, there are three cities and there is a road between every pair of cities. Let's analyze one of optimal scenarios. Use BCD in city 1. With probability Limak is in this city and BCD tells you that the distance is 0. You should try to catch him now and you win for sure. With probability the distance is 1 because Limak is in city 2 or city 3. In this case you should wait for the second day. You wait and Limak moves to some other city. There is probability that Limak was in city 2 and then went to city 3. that he went from 2 to 1. that he went from 3 to 2. that he went from 3 to 1. Use BCD again in city 1 (though it's allowed to use it in some other city). If the distance is 0 then you're sure Limak is in this city (you win). If the distance is 1 then Limak is in city 2 or city 3. Then you should guess that he is in city 2 (guessing city 3 would be fine too). You loose only if Limak was in city 2 first and then he moved to city 3. The probability of loosing is . The answer is .
Input: 3 31 21 32 3 | Output: 0.833333333333
Master
6
1,863
367
318
6
1,841
C
1841C
C. Ranom Numbers
1,800
brute force; dp; greedy; math; strings
No, not ""random"" numbers.Ranom digits are denoted by uppercase Latin letters from A to E. Moreover, the value of the letter A is \(1\), B is \(10\), C is \(100\), D is \(1000\), E is \(10000\).A Ranom number is a sequence of Ranom digits. The value of the Ranom number is calculated as follows: the values of all digits are summed up, but some digits are taken with negative signs: a digit is taken with negative sign if there is a digit with a strictly greater value to the right of it (not necessarily immediately after it); otherwise, that digit is taken with a positive sign.For example, the value of the Ranom number DAAABDCA is \(1000 - 1 - 1 - 1 - 10 + 1000 + 100 + 1 = 2088\).You are given a Ranom number. You can change no more than one digit in it. Calculate the maximum possible value of the resulting number.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The only line of each test case contains a string \(s\) (\(1 \le |s| \le 2 \cdot 10^5\)) consisting of uppercase Latin letters from A to E β€” the Ranom number you are given.The sum of the string lengths over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print a single integer β€” the maximum possible value of the number, if you can change no more than one digit in it.
In the first example, you can get EAAABDCA with the value \(10000-1-1-1-10+1000+100+1=11088\).In the second example, you can get EB with the value \(10000+10=10010\).
Input: 4DAAABDCAABABCDEEDCBADDDDAAADDABECD | Output: 11088 10010 31000 15886
Medium
5
822
352
134
18
1,156
A
1156A
A. Inscribed Figures
1,400
geometry
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.Future students will be asked just a single question. They are given a sequence of integer numbers \(a_1, a_2, \dots, a_n\), each number is from \(1\) to \(3\) and \(a_i \ne a_{i + 1}\) for each valid \(i\). The \(i\)-th number represents a type of the \(i\)-th figure: circle; isosceles triangle with the length of height equal to the length of base; square. The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that: \((i + 1)\)-th figure is inscribed into the \(i\)-th one; each triangle base is parallel to OX; the triangle is oriented in such a way that the vertex opposite to its base is at the top; each square sides are parallel to the axes; for each \(i\) from \(2\) to \(n\) figure \(i\) has the maximum possible length of side for triangle and square and maximum radius for circle. Note that the construction is unique for some fixed position and size of just the first figure.The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?So can you pass the math test and enroll into Berland State University?
The first line contains a single integer \(n\) (\(2 \le n \le 100\)) β€” the number of figures.The second line contains \(n\) integer numbers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 3\), \(a_i \ne a_{i + 1}\)) β€” types of the figures.
The first line should contain either the word ""Infinite"" if the number of distinct points where figures touch is infinite or ""Finite"" otherwise.If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type.
Here are the glorious pictures for the examples. Note that the triangle is not equilateral but just isosceles with the length of height equal to the length of base. Thus it fits into a square in a unique way.The distinct points where figures touch are marked red.In the second example the triangle and the square touch each other for the whole segment, it contains infinite number of points.
Input: 3 2 1 3 | Output: Finite 7
Easy
1
1,474
233
268
11
756
C
756C
C. Nikita and stack
2,200
data structures
Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer x on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing.Nikita made m operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the i-th step he remembers an operation he made pi-th. In other words, he remembers the operations in order of some permutation p1, p2, ..., pm. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!
The first line contains the integer m (1 ≀ m ≀ 105) β€” the number of operations Nikita made.The next m lines contain the operations Nikita remembers. The i-th line starts with two integers pi and ti (1 ≀ pi ≀ m, ti = 0 or ti = 1) β€” the index of operation he remembers on the step i, and the type of the operation. ti equals 0, if the operation is pop(), and 1, is the operation is push(x). If the operation is push(x), the line also contains the integer xi (1 ≀ xi ≀ 106) β€” the integer added to the stack.It is guaranteed that each integer from 1 to m is present exactly once among integers pi.
Print m integers. The integer i should equal the number on the top of the stack after performing all the operations Nikita remembered on the steps from 1 to i. If the stack is empty after performing all these operations, print -1.
In the first example, after Nikita remembers the operation on the first step, the operation push(2) is the only operation, so the answer is 2. After he remembers the operation pop() which was done before push(2), answer stays the same.In the second example, the operations are push(2), push(3) and pop(). Nikita remembers them in the order they were performed.In the third example Nikita remembers the operations in the reversed order.
Input: 22 1 21 0 | Output: 22
Hard
1
746
593
230
7
457
B
457B
B. Distributed Join
1,900
greedy
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.
First line contains two integer numbers, m and n (1 ≀ m, n ≀ 105). Second line contains description of the first cluster with m space separated integers, ai (1 ≀ ai ≀ 109). Similarly, third line describes second cluster with n space separated integers, bi (1 ≀ bi ≀ 109).
Print one integer β€” minimal number of copy operations.
In the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2Β·3 = 6 copy operations.
Input: 2 22 63 100 | Output: 11
Hard
1
730
271
54
4
166
E
166E
E. Tetrahedron
1,500
dp; math; matrices
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
The first line contains the only integer n (1 ≀ n ≀ 107) β€” the required length of the cyclic path.
Print the only integer β€” the required number of ways modulo 1000000007 (109 + 7).
The required paths in the first sample are: D - A - D D - B - D D - C - D
Input: 2 | Output: 3
Medium
3
724
98
81
1
1,883
G2
1883G2
G2. Dances (Hard Version)
1,900
binary search; greedy; sortings; two pointers
This is the hard version of the problem. The only difference is that in this version \(m \leq 10^9\).You are given two arrays of integers \(a_1, a_2, \ldots, a_n\) and \(b_1, b_2, \ldots, b_n\). Before applying any operations, you can reorder the elements of each array as you wish. Then, in one operation, you will perform both of the following actions, if the arrays are not empty: Choose any element from array \(a\) and remove it (all remaining elements are shifted to a new array \(a\)), Choose any element from array \(b\) and remove it (all remaining elements are shifted to a new array \(b\)).Let \(k\) be the final size of both arrays. You need to find the minimum number of operations required to satisfy \(a_i < b_i\) for all \(1 \leq i \leq k\).This problem was too easy, so the problem author decided to make it more challenging. You are also given a positive integer \(m\). Now, you need to find the sum of answers to the problem for \(m\) pairs of arrays \((c[i], b)\), where \(1 \leq i \leq m\). Array \(c[i]\) is obtained from \(a\) as follows: \(c[i]_1 = i\), \(c[i]_j = a_j\), for \(2 \leq j \leq n\).
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) - the number of sets of input data. This is followed by their description.The first line of each test case contains two integers \(n\) and \(m\) (\(2 \leq n \leq 10^5\), \(1 \leq m \leq 10^9\)) - the size of arrays \(a\) and \(b\) and the constraints on the value of element \(a_1\).The second line of each test case contains \(n - 1\) integers \(a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)).The third line of each test case contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \leq b_i \leq 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, output the total number of minimum operations for all pairs of arrays \((c_i, b)\).
In the first test case: For the pair of arrays \(([1, 1], [3, 2])\), the answer is \(0\). No operations or reordering of elements are needed. For the pair of arrays \(([2, 1], [3, 2])\), the answer is \(0\). The elements of the first array can be rearranged to obtain \([1, 2)\). No operations are needed. For the pair of arrays \(([3, 1], [3, 2])\), the answer is \(1\). The element \(3\) can be removed from the first array and the element \(2\) can be removed from the second array. For the pair of arrays \(([4, 1], [3, 2])\), the answer is \(1\). The element \(4\) can be removed from the first array and the element \(3\) can be removed from the second array.
Input: 42 413 24 75 1 53 8 3 38 44 3 3 2 2 1 11 1 1 1 3 3 3 39 19 2 8 3 7 4 6 51 2 3 2 1 4 5 6 5 | Output: 2 12 16 4
Hard
4
1,120
702
103
18
26
B
26B
B. Regular Bracket Sequence
1,400
greedy
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters Β«+Β» and Β«1Β» into this sequence. For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are regular, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
Input consists of a single line with non-empty string of Β«(Β» and Β«)Β» characters. Its length does not exceed 106.
Output the maximum possible length of a regular bracket sequence.
Input: (()))( | Output: 4
Easy
1
469
112
65
0
513
A
513A
A. Game
800
constructive algorithms; math
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.
The first line contains four integers n1, n2, k1, k2. All numbers in the input are from 1 to 50.This problem doesn't have subproblems. You will get 3 points for the correct submission.
Output ""First"" if the first player wins and ""Second"" otherwise.
Consider the first sample test. Each player has a box with 2 balls. The first player draws a single ball from his box in one move and the second player can either take 1 or 2 balls from his box in one move. No matter how the first player acts, the second player can always win if he plays wisely.
Input: 2 2 1 2 | Output: Second
Beginner
2
510
184
67
5
855
B
855B
B. Marvolo Gaunt's Ring
1,500
brute force; data structures; dp
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made. Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 ≀ i ≀ j ≀ k ≀ n. Help Snape find the value of x. Do note that the value of x may be negative.
First line of input contains 4 integers n, p, q, r ( - 109 ≀ p, q, r ≀ 109, 1 ≀ n ≀ 105).Next line of input contains n space separated integers a1, a2, ... an ( - 109 ≀ ai ≀ 109).
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 ≀ i ≀ j ≀ k ≀ n.
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Input: 5 1 2 31 2 3 4 5 | Output: 30
Medium
3
591
179
112
8
1,660
E
1660E
E. Matrix and Shifts
1,600
brute force; constructive algorithms; greedy; implementation
You are given a binary matrix \(A\) of size \(n \times n\). Rows are numbered from top to bottom from \(1\) to \(n\), columns are numbered from left to right from \(1\) to \(n\). The element located at the intersection of row \(i\) and column \(j\) is called \(A_{ij}\). Consider a set of \(4\) operations: Cyclically shift all rows up. The row with index \(i\) will be written in place of the row \(i-1\) (\(2 \le i \le n\)), the row with index \(1\) will be written in place of the row \(n\). Cyclically shift all rows down. The row with index \(i\) will be written in place of the row \(i+1\) (\(1 \le i \le n - 1\)), the row with index \(n\) will be written in place of the row \(1\). Cyclically shift all columns to the left. The column with index \(j\) will be written in place of the column \(j-1\) (\(2 \le j \le n\)), the column with index \(1\) will be written in place of the column \(n\). Cyclically shift all columns to the right. The column with index \(j\) will be written in place of the column \(j+1\) (\(1 \le j \le n - 1\)), the column with index \(n\) will be written in place of the column \(1\). The \(3 \times 3\) matrix is shown on the left before the \(3\)-rd operation is applied to it, on the right β€” after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.After that, you can perform an arbitrary (possibly zero) number of new xor-operations: Select any element \(A_{ij}\) and assign it with new value \(A_{ij} \oplus 1\). In other words, the value of \((A_{ij} + 1) \bmod 2\) will have to be written into element \(A_{ij}\). Each application of this xor-operation costs one burl. Note that the \(4\) shift operations β€” are free. These \(4\) operations can only be performed before xor-operations are performed.Output the minimum number of burles you would have to pay to make the \(A\) matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, \(A_{ij} = 1\) if \(i = j\) and \(A_{ij} = 0\) otherwise).
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. Before each test case, an empty line is written in the input.The first line of each test case contains a single number \(n\) (\(1 \le n \le 2000\))This is followed by \(n\) lines, each containing exactly \(n\) characters and consisting only of zeros and ones. These lines describe the values in the elements of the matrix.It is guaranteed that the sum of \(n^2\) values over all test cases does not exceed \(4 \cdot 10^6\).
For each test case, output the minimum number of burles you would have to pay to make the \(A\) matrix unitary. In other words, print the minimum number of xor-operations it will take after applying cyclic shifts to the matrix for the \(A\) matrix to become unitary.
In the first test case, you can do the following: first, shift all the rows down cyclically, then the main diagonal of the matrix will contain only ""1"". Then it will be necessary to apply xor-operation to the only ""1"" that is not on the main diagonal.In the second test case, you can make a unitary matrix by applying the operation \(2\) β€” cyclic shift of rows upward twice to the matrix.
Input: 43010011100500010000011000001000001002101041111101111111111 | Output: 1 0 2 11
Medium
4
2,075
581
266
16
1,621
I
1621I
I. Two Sequences
3,500
data structures; hashing; string suffix structures
Consider an array of integers \(C = [c_1, c_2, \ldots, c_n]\) of length \(n\). Let's build the sequence of arrays \(D_0, D_1, D_2, \ldots, D_{n}\) of length \(n+1\) in the following way: The first element of this sequence will be equals \(C\): \(D_0 = C\). For each \(1 \leq i \leq n\) array \(D_i\) will be constructed from \(D_{i-1}\) in the following way: Let's find the lexicographically smallest subarray of \(D_{i-1}\) of length \(i\). Then, the first \(n-i\) elements of \(D_i\) will be equals to the corresponding \(n-i\) elements of array \(D_{i-1}\) and the last \(i\) elements of \(D_i\) will be equals to the corresponding elements of the found subarray of length \(i\). Array \(x\) is subarray of array \(y\), if \(x\) can be obtained by deletion of several (possibly, zero or all) elements from the beginning of \(y\) and several (possibly, zero or all) elements from the end of \(y\).For array \(C\) let's denote array \(D_n\) as \(op(C)\).Alice has an array of integers \(A = [a_1, a_2, \ldots, a_n]\) of length \(n\). She will build the sequence of arrays \(B_0, B_1, \ldots, B_n\) of length \(n+1\) in the following way: The first element of this sequence will be equals \(A\): \(B_0 = A\). For each \(1 \leq i \leq n\) array \(B_i\) will be equals \(op(B_{i-1})\), where \(op\) is the transformation described above. She will ask you \(q\) queries about elements of sequence of arrays \(B_0, B_1, \ldots, B_n\). Each query consists of two integers \(i\) and \(j\), and the answer to this query is the value of the \(j\)-th element of array \(B_i\).
The first line contains the single integer \(n\) (\(1 \leq n \leq 10^5\)) β€” the length of array \(A\).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq n\)) β€” the array \(A\).The third line contains the single integer \(q\) (\(1 \leq q \leq 10^6\)) β€” the number of queries.Each of the next \(q\) lines contains two integers \(i\), \(j\) (\(1 \leq i, j \leq n\)) β€” parameters of queries.
Output \(q\) integers: values of \(B_{i, j}\) for required \(i\), \(j\).
In the first test case \(B_0 = A = [2, 1, 3, 1]\).\(B_1\) is constructed in the following way: Initially, \(D_0 = [2, 1, 3, 1]\). For \(i=1\) the lexicographically smallest subarray of \(D_0\) of length \(1\) is \([1]\), so \(D_1\) will be \([2, 1, 3, 1]\). For \(i=2\) the lexicographically smallest subarray of \(D_1\) of length \(2\) is \([1, 3]\), so \(D_2\) will be \([2, 1, 1, 3]\). For \(i=3\) the lexicographically smallest subarray of \(D_2\) of length \(3\) is \([1, 1, 3]\), so \(D_3\) will be \([2, 1, 1, 3]\). For \(i=4\) the lexicographically smallest subarray of \(D_3\) of length \(4\) is \([2, 1, 1, 3]\), so \(D_4\) will be \([2, 1, 1, 3]\). So, \(B_1 = op(B_0) = op([2, 1, 3, 1]) = [2, 1, 1, 3]\).
Input: 4 2 1 3 1 4 1 1 1 2 1 3 1 4 | Output: 2 1 1 3
Master
3
1,567
421
72
16
1,843
E
1843E
E. Tracking Segments
1,600
binary search; brute force; data structures; two pointers
You are given an array \(a\) consisting of \(n\) zeros. You are also given a set of \(m\) not necessarily different segments. Each segment is defined by two numbers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le n\)) and represents a subarray \(a_{l_i}, a_{l_i+1}, \dots, a_{r_i}\) of the array \(a\).Let's call the segment \(l_i, r_i\) beautiful if the number of ones on this segment is strictly greater than the number of zeros. For example, if \(a = [1, 0, 1, 0, 1]\), then the segment \([1, 5]\) is beautiful (the number of ones is \(3\), the number of zeros is \(2\)), but the segment \([3, 4]\) is not is beautiful (the number of ones is \(1\), the number of zeros is \(1\)).You also have \(q\) changes. For each change you are given the number \(1 \le x \le n\), which means that you must assign an element \(a_x\) the value \(1\).You have to find the first change after which at least one of \(m\) given segments becomes beautiful, or report that none of them is beautiful after processing all \(q\) changes.
The first line contains a single 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 \(m\) (\(1 \le m \le n \le 10^5\)) β€” the size of the array \(a\) and the number of segments, respectively.Then there are \(m\) lines consisting of two numbers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le n\)) β€”the boundaries of the segments.The next line contains an integer \(q\) (\(1 \le q \le n\)) β€” the number of changes.The following \(q\) lines each contain a single integer \(x\) (\(1 \le x \le n\)) β€” the index of the array element that needs to be set to \(1\). It is guaranteed that indexes in queries are distinct.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(10^5\).
For each test case, output one integer β€” the minimum change number after which at least one of the segments will be beautiful, or \(-1\) if none of the segments will be beautiful.
In the first case, after first 2 changes we won't have any beautiful segments, but after the third one on a segment \([1; 5]\) there will be 3 ones and only 2 zeros, so the answer is 3.In the second case, there won't be any beautiful segments.
Input: 65 51 24 51 51 32 45531244 21 14 42235 21 51 5421345 21 51 35412355 51 51 51 51 51 431433 22 21 33231 | Output: 3 -1 3 3 3 1
Medium
4
1,014
770
179
18
1,110
D
1110D
D. Jongmah
2,200
dp
You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have \(n\) tiles in your hand. Each tile has an integer between \(1\) and \(m\) written on it.To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, \(7, 7, 7\) is a valid triple, and so is \(12, 13, 14\), but \(2,2,3\) or \(2,4,6\) are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple.To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand.
The first line contains two integers integer \(n\) and \(m\) (\(1 \le n, m \le 10^6\)) β€” the number of tiles in your hand and the number of tiles types.The second line contains integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le m\)), where \(a_i\) denotes the number written on the \(i\)-th tile.
Print one integer: the maximum number of triples you can form.
In the first example, we have tiles \(2, 3, 3, 3, 4, 4, 4, 5, 5, 6\). We can form three triples in the following way: \(2, 3, 4\); \(3, 4, 5\); \(4, 5, 6\). Since there are only \(10\) tiles, there is no way we could form \(4\) triples, so the answer is \(3\).In the second example, we have tiles \(1\), \(2\), \(3\) (\(7\) times), \(4\), \(5\) (\(2\) times). We can form \(3\) triples as follows: \(1, 2, 3\); \(3, 3, 3\); \(3, 4, 5\). One can show that forming \(4\) triples is not possible.
Input: 10 62 3 3 3 4 4 4 5 5 6 | Output: 3
Hard
1
710
297
62
11
1,116
C2
1116C2
C2. ""Is the bit string periodic?"" oracle
0
*special
Implement a quantum oracle on \(N\) qubits which checks whether the bits in the input vector \(\vec{x}\) form a periodic bit string (i.e., implements the function \(f(\vec{x}) = 1\) if \(\vec{x}\) is periodic, and 0 otherwise). A bit string of length \(N\) is considered periodic with period \(P\) (\(1 \le P \le N - 1\)) if for all \(i \in [0, N - P - 1]\) \(x_i = x_{i + P}\). Note that \(P\) does not have to divide \(N\) evenly; for example, bit string ""01010"" is periodic with period \(P = 2\).You have to implement an operation which takes the following inputs: an array of \(N\) (\(2 \le N \le 7\)) qubits \(x\) in an arbitrary state (input register), a qubit \(y\) in an arbitrary state (output qubit),and performs a transformation \(|x\rangle|y\rangle \rightarrow |x\rangle|y \oplus f(x)\rangle\). The operation doesn't have an output; its ""output"" is the state in which it leaves the qubits. Note that the input register \(x\) has to remain unchanged after applying the operation.Your code should have the following signature:namespace Solution { open Microsoft.Quantum.Primitive; open Microsoft.Quantum.Canon; operation Solve (x : Qubit[], y : Qubit) : Unit { body (...) { // your code here } adjoint auto; }}Note: the operation has to have an adjoint specified for it; adjoint auto means that the adjoint will be generated automatically. For details on adjoint, see Operation Definitions.You are not allowed to use measurements in your operation.
Beginner
1
1,462
0
0
11
1,195
A
1195A
A. Drinks Choosing
1,000
greedy; math
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are \(n\) students living in a building, and for each of them the favorite drink \(a_i\) is known. So you know \(n\) integers \(a_1, a_2, \dots, a_n\), where \(a_i\) (\(1 \le a_i \le k\)) is the type of the favorite drink of the \(i\)-th student. The drink types are numbered from \(1\) to \(k\).There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are \(k\) types of drink sets, the \(j\)-th type contains two portions of the drink \(j\). The available number of sets of each of the \(k\) types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly \(\lceil \frac{n}{2} \rceil\), where \(\lceil x \rceil\) is \(x\) rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if \(n\) is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if \(\lceil \frac{n}{2} \rceil\) sets will be chosen optimally and students will distribute portions between themselves optimally?
The first line of the input contains two integers \(n\) and \(k\) (\(1 \le n, k \le 1\,000\)) β€” the number of students in the building and the number of different drinks.The next \(n\) lines contain student's favorite drinks. The \(i\)-th line contains a single integer from \(1\) to \(k\) β€” the type of the favorite drink of the \(i\)-th student.
Print exactly one integer β€” the maximum number of students that can get a favorite drink.
In the first example, students could choose three sets with drinks \(1\), \(1\) and \(2\) (so they will have two sets with two drinks of the type \(1\) each and one set with two drinks of the type \(2\), so portions will be \(1, 1, 1, 1, 2, 2\)). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks \(1\), \(2\) and \(3\). In this case the portions will be \(1, 1, 2, 2, 3, 3\). Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with \(a_i = 1\) (i.e. the first, the third or the fourth).
Input: 5 3 1 3 1 1 2 | Output: 4
Beginner
2
1,455
347
89
11
1,182
E
1182E
E. Product Oriented Recurrence
2,300
dp; math; matrices; number theory
Let \(f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3}\) for \(x \ge 4\).You have given integers \(n\), \(f_{1}\), \(f_{2}\), \(f_{3}\), and \(c\). Find \(f_{n} \bmod (10^{9}+7)\).
The only line contains five integers \(n\), \(f_{1}\), \(f_{2}\), \(f_{3}\), and \(c\) (\(4 \le n \le 10^{18}\), \(1 \le f_{1}\), \(f_{2}\), \(f_{3}\), \(c \le 10^{9}\)).
Print \(f_{n} \bmod (10^{9} + 7)\).
In the first example, \(f_{4} = 90\), \(f_{5} = 72900\).In the second example, \(f_{17} \approx 2.28 \times 10^{29587}\).
Input: 5 1 2 5 3 | Output: 72900
Expert
4
190
170
35
11
1,981
D
1981D
D. Turtle and Multiplication
2,400
constructive algorithms; dfs and similar; graphs; number theory
Turtle just learned how to multiply two integers in his math class, and he was very excited.Then Piggy gave him an integer \(n\), and asked him to construct a sequence \(a_1, a_2, \ldots, a_n\) consisting of integers which satisfied the following conditions: For all \(1 \le i \le n\), \(1 \le a_i \le 3 \cdot 10^5\). For all \(1 \le i < j \le n - 1\), \(a_i \cdot a_{i + 1} \ne a_j \cdot a_{j + 1}\). Of all such sequences, Piggy asked Turtle to find the one with the minimum number of distinct elements.Turtle definitely could not solve the problem, so please help him!
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 a single integer \(n\) (\(2 \le n \le 10^6\)) β€” the length of the sequence \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
For each test case, output \(n\) integers \(a_1, a_2, \ldots, a_n\) β€” the elements of the sequence \(a\).If there are multiple answers, print any of them.
In the third test case, \(a = [3, 4, 2, 6]\) violates the second condition since \(a_1 \cdot a_2 = a_3 \cdot a_4\). \(a = [2, 3, 4, 4]\) satisfy the conditions but its number of distinct elements isn't minimum.
Input: 3234 | Output: 114514 114514 1 2 2 3 3 4 4
Expert
4
571
368
154
19
1,225
G
1225G
G. To Make 1
3,100
bitmasks; constructive algorithms; dp; greedy; number theory
There are \(n\) positive integers written on the blackboard. Also, a positive number \(k \geq 2\) is chosen, and none of the numbers on the blackboard are divisible by \(k\). In one operation, you can choose any two integers \(x\) and \(y\), erase them and write one extra number \(f(x + y)\), where \(f(x)\) is equal to \(x\) if \(x\) is not divisible by \(k\), otherwise \(f(x) = f(x / k)\).In the end, there will be a single number of the blackboard. Is it possible to make the final number equal to \(1\)? If so, restore any sequence of operations to do so.
The first line contains two integers \(n\) and \(k\) β€” the initial number of integers on the blackboard, and the chosen number (\(2 \leq n \leq 16\), \(2 \leq k \leq 2000\)).The second line contains \(n\) positive integers \(a_1, \ldots, a_n\) initially written on the blackboard. It is guaranteed that none of the numbers \(a_i\) is divisible by \(k\), and the sum of all \(a_i\) does not exceed \(2000\).
If it is impossible to obtain \(1\) as the final number, print ""NO"" in the only line.Otherwise, print ""YES"" on the first line, followed by \(n - 1\) lines describing operations. The \(i\)-th of these lines has to contain two integers \(x_i\) and \(y_i\) to be erased and replaced with \(f(x_i + y_i)\) on the \(i\)-th operation. If there are several suitable ways, output any of them.
In the second sample case: \(f(8 + 7) = f(15) = f(5) = 5\); \(f(23 + 13) = f(36) = f(12) = f(4) = 4\); \(f(5 + 4) = f(9) = f(3) = f(1) = 1\).
Input: 2 2 1 1 | Output: YES 1 1
Master
5
561
406
388
12
1,920
E
1920E
E. Counting Binary Strings
2,100
combinatorics; dp; math
Patrick calls a substring\(^\dagger\) of a binary string\(^\ddagger\) good if this substring contains exactly one 1. Help Patrick count the number of binary strings \(s\) such that \(s\) contains exactly \(n\) good substrings and has no good substring of length strictly greater than \(k\). Note that substrings are differentiated by their location in the string, so if \(s =\) 1010 you should count both occurrences of 10.\(^\dagger\) A string \(a\) is a substring of a string \(b\) if \(a\) can be obtained from \(b\) by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\(^\ddagger\) A binary string is a string that only contains the characters 0 and 1.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 2500\)) β€” the number of test cases. The description of the test cases follows.The only line of each test case contains two integers \(n\) and \(k\) (\(1 \leq n \leq 2500\), \(1 \leq k \leq n\)) β€” the number of required good substrings and the maximum allowed length of a good substring. It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2500\).
For each test case, output a single integer β€” the number of binary strings \(s\) such that \(s\) contains exactly \(n\) good substrings and has no good substring of length strictly greater than \(k\). Since this integer can be too large, output it modulo \(998\,244\,353\).
In the first test case, the only suitable binary string is 1. String 01 is not suitable because it contains a substring 01 with length \(2 > 1\).In the second test case, suitable binary strings are 011, 110 and 111.In the third test case, suitable binary strings are 101, 0110, 0111, 1110, and 1111.
Input: 61 13 24 25 46 22450 2391 | Output: 1 3 5 12 9 259280854
Hard
3
745
478
273
19
75
D
75D
D. Big Maximum Sum
2,000
data structures; dp; greedy; implementation; math; trees
Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?
The first line contains two integers n and m, n is the number of the small arrays (1 ≀ n ≀ 50), and m is the number of indexes in the big array (1 ≀ m ≀ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≀ l ≀ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n.The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array.Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.
Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty.Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
Input: 3 43 1 6 -22 3 32 -5 12 3 1 3 | Output: 9
Hard
6
1,263
865
297
0
776
D
776D
D. The Door Problem
2,000
2-sat; dfs and similar; dsu; graphs
Moriarty has trapped n people in n distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are m switches. Each switch control doors of some rooms, but each door is controlled by exactly two switches.You are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch 1, which was connected to room 1, 2 and 3 which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked.You need to tell Sherlock, if there exists a way to unlock all doors at the same time.
First line of input contains two integers n and m (2 ≀ n ≀ 105, 2 ≀ m ≀ 105) β€” the number of rooms and the number of switches.Next line contains n space-separated integers r1, r2, ..., rn (0 ≀ ri ≀ 1) which tell the status of room doors. The i-th room is locked if ri = 0, otherwise it is unlocked.The i-th of next m lines contains an integer xi (0 ≀ xi ≀ n) followed by xi distinct integers separated by space, denoting the number of rooms controlled by the i-th switch followed by the room numbers that this switch controls. It is guaranteed that the room numbers are in the range from 1 to n. It is guaranteed that each door is controlled by exactly two switches.
Output ""YES"" without quotes, if it is possible to open all doors at the same time, otherwise output ""NO"" without quotes.
In the second example input, the initial statuses of the doors are [1, 0, 1] (0 means locked, 1 β€” unlocked).After toggling switch 3, we get [0, 0, 0] that means all doors are locked.Then, after toggling switch 1, we get [1, 1, 1] that means all doors are unlocked.It can be seen that for the first and for the third example inputs it is not possible to make all doors unlocked.
Input: 3 31 0 12 1 32 1 22 2 3 | Output: NO
Hard
4
830
666
124
7
1,919
A
1919A
A. Wallet Exchange
800
games; math
Alice and Bob are bored, so they decide to play a game with their wallets. Alice has \(a\) coins in her wallet, while Bob has \(b\) coins in his wallet.Both players take turns playing, with Alice making the first move. In each turn, the player will perform the following steps in order: Choose to exchange wallets with their opponent, or to keep their current wallets. Remove \(1\) coin from the player's current wallet. The current wallet cannot have \(0\) coins before performing this step. The player who cannot make a valid move on their turn loses. If both Alice and Bob play optimally, determine who will win the game.
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 1000\)) β€” the number of test cases. The description of the test cases follows.The first and only line of each test case contains two integers \(a\) and \(b\) (\(1 \le a, b \le 10^9\)) β€” the number of coins in Alice's and Bob's wallets, respectively.
For each test case, output ""Alice"" if Alice will win the game, and ""Bob"" if Bob will win the game.
In the first test case, an example of the game is shown below: Alice chooses to not swap wallets with Bob in step 1 of her move. Now, \(a=0\) and \(b=1\). Since Alice's wallet is empty, Bob must choose to not swap their wallets in step 1 of his move. Now, \(a=0\) and \(b=0\). Since both Alice's and Bob's wallets are empty, Alice is unable to make a move. Hence, Bob wins. In the second test case, an example of the game is shown below: Alice chooses to swap wallets with Bob in step 1 of her move. Now, \(a=3\) and \(b=1\). Bob chooses to swap wallets with Alice in step 1 of his move. Now, \(a=1\) and \(b=2\). Alice chooses to not swap wallets with Bob in step 1 of her move. Now, \(a=0\) and \(b=2\). Since Alice's wallet is empty, Bob can only choose to not swap wallets with Alice in step 1 of his move. Now, \(a=0\) and \(b=1\). Since Alice's wallet is empty, Alice can only choose to swap wallets with Bob in step 1 of her move. Now, \(a=0\) and \(b=0\). Since both Alice's wallet and Bob's wallet are empty, Bob is unable to make a move. Hence, Alice wins.
Input: 101 11 45 34 511 983 911032 9307839204 72811000000000 100000000053110 2024 | Output: Bob Alice Bob Alice Bob Bob Alice Alice Bob Bob
Beginner
2
624
353
102
19
508
C
508C
C. Anya and Ghosts
1,600
constructive algorithms; greedy
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
The first line contains three integers m, t, r (1 ≀ m, t, r ≀ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers wi (1 ≀ i ≀ m, 1 ≀ wi ≀ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.If that is impossible, print - 1.
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Input: 1 8 310 | Output: 3
Medium
2
1,018
456
177
5
264
D
264D
D. Colorful Stones
2,500
dp; two pointers
There are two sequences of colorful stones. The color of each stone is one of red, green, or blue. You are given two strings s and t. The i-th (1-based) character of s represents the color of the i-th stone of the first sequence. Similarly, the i-th (1-based) character of t represents the color of the i-th stone of the second sequence. If the character is ""R"", ""G"", or ""B"", the color of the corresponding stone is red, green, or blue, respectively.Initially Squirrel Liss is standing on the first stone of the first sequence and Cat Vasya is standing on the first stone of the second sequence. You can perform the following instructions zero or more times.Each instruction is one of the three types: ""RED"", ""GREEN"", or ""BLUE"". After an instruction c, the animals standing on stones whose colors are c will move one stone forward. For example, if you perform an instruction Β«REDΒ», the animals standing on red stones will move one stone forward. You are not allowed to perform instructions that lead some animals out of the sequences. In other words, if some animals are standing on the last stones, you can't perform the instructions of the colors of those stones.A pair of positions (position of Liss, position of Vasya) is called a state. A state is called reachable if the state is reachable by performing instructions zero or more times from the initial state (1, 1). Calculate the number of distinct reachable states.
The input contains two lines. The first line contains the string s (1 ≀ |s| ≀ 106). The second line contains the string t (1 ≀ |t| ≀ 106). The characters of each string will be one of ""R"", ""G"", or ""B"".
Print the number of distinct reachable states in a single line.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
In the first example, there are five reachable states: (1, 1), (2, 2), (2, 3), (3, 2), and (3, 3). For example, the state (3, 3) is reachable because if you perform instructions ""RED"", ""GREEN"", and ""BLUE"" in this order from the initial state, the state will be (3, 3). The following picture shows how the instructions work in this case.
Input: RBRRGG | Output: 5
Expert
2
1,435
207
212
2
48
C
48C
C. The Race
1,800
math
Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name β€” The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with Ξ± liters of petrol (Ξ± β‰₯ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with Ξ± liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if Ξ± = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the Ξ± number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.
The first line contains an integer n (1 ≀ n ≀ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number Ξ± β‰₯ 10, to which such a succession of stops corresponds.
Print in the first line ""unique"" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line ""not unique"".
In the second example the answer is not unique. For example, if Ξ± = 10, we'll have such a sequence as 1, 2, 3, and if Ξ± = 14, the sequence will be 1, 2, 4.
Input: 31 2 4 | Output: unique5
Medium
1
2,212
453
250
0
1,903
D2
1903D2
D2. Maximum And Queries (hard version)
2,500
bitmasks; divide and conquer; dp; greedy
This is the hard version of the problem. The only difference between the two versions is the constraint on \(n\) and \(q\), the memory and time limits. You can make hacks only if all versions of the problem are solved.Theofanis really likes to play with the bits of numbers. He has an array \(a\) of size \(n\) and an integer \(k\). He can make at most \(k\) operations in the array. In each operation, he picks a single element and increases it by \(1\).He found the maximum bitwise AND that array \(a\) can have after at most \(k\) operations.Theofanis has put a lot of work into finding this value and was very happy with his result. Unfortunately, AdaΕ›, being the evil person that he is, decided to bully him by repeatedly changing the value of \(k\).Help Theofanis by calculating the maximum possible bitwise AND for \(q\) different values of \(k\). Note that queries are independent.
The first line contains two integers \(n\) and \(q\) (\(1 \le n, q \le 10^6\)) β€” the size of the array and the number of queries.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 10^6\)) β€” the elements of the array.Next \(q\) lines describe the queries. The \(i\)-th line contains one integer \(k_i\) (\(0 \le k_i \le 10^{18}\)) β€” the number of operations that can be done in the \(i\)-th query.
For each query, print one integer β€” the maximum bitwise AND that array \(a\) can have after at most \(k_i\) operations.
In the first test case, in the first query, we add \(1\) in the first and last elements of the array. Thus, the array becomes \([2,3,7,6]\) with bitwise AND equal to \(2\).In the second test case, in the first query, we add \(1\) in the first element, \(5\) in the second, and \(3\) in the third and now all the elements are equal to \(5\).
Input: 4 21 3 7 5210 | Output: 2 6
Expert
4
889
428
119
19
1,609
B
1609B
B. William the Vigilant
1,100
implementation; strings
Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment:You are given a string \(s\) of length \(n\) only consisting of characters ""a"", ""b"" and ""c"". There are \(q\) queries of format (\(pos, c\)), meaning replacing the element of string \(s\) at position \(pos\) with character \(c\). After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string ""abc"" as a substring. A valid replacement of a character is replacing it with ""a"", ""b"" or ""c"".A string \(x\) is a substring of a string \(y\) if \(x\) can be obtained from \(y\) by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
The first line contains two integers \(n\) and \(q\) \((1 \le n, q \le 10^5)\), the length of the string and the number of queries, respectively.The second line contains the string \(s\), consisting of characters ""a"", ""b"" and ""c"".Each of the next \(q\) lines contains an integer \(i\) and character \(c\) \((1 \le i \le n)\), index and the value of the new item in the string, respectively. It is guaranteed that character's \(c\) value is ""a"", ""b"" or ""c"".
For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain ""abc"" as a substring.
Let's consider the state of the string after each query: \(s =\) ""abcabcabc"". In this case \(3\) replacements can be performed to get, for instance, string \(s =\) ""bbcaccabb"". This string does not contain ""abc"" as a substring. \(s =\) ""bbcabcabc"". In this case \(2\) replacements can be performed to get, for instance, string \(s =\) ""bbcbbcbbc"". This string does not contain ""abc"" as a substring. \(s =\) ""bccabcabc"". In this case \(2\) replacements can be performed to get, for instance, string \(s =\) ""bccbbcbbc"". This string does not contain ""abc"" as a substring. \(s =\) ""bcaabcabc"". In this case \(2\) replacements can be performed to get, for instance, string \(s =\) ""bcabbcbbc"". This string does not contain ""abc"" as a substring. \(s =\) ""bcabbcabc"". In this case \(1\) replacements can be performed to get, for instance, string \(s =\) ""bcabbcabb"". This string does not contain ""abc"" as a substring. \(s =\) ""bcabccabc"". In this case \(2\) replacements can be performed to get, for instance, string \(s =\) ""bcabbcabb"". This string does not contain ""abc"" as a substring. \(s =\) ""bcabccaac"". In this case \(1\) replacements can be performed to get, for instance, string \(s =\) ""bcabbcaac"". This string does not contain ""abc"" as a substring. \(s =\) ""bcabccaab"". In this case \(1\) replacements can be performed to get, for instance, string \(s =\) ""bcabbcaab"". This string does not contain ""abc"" as a substring. \(s =\) ""ccabccaab"". In this case \(1\) replacements can be performed to get, for instance, string \(s =\) ""ccabbcaab"". This string does not contain ""abc"" as a substring. \(s =\) ""ccaaccaab"". In this case the string does not contain ""abc"" as a substring and no replacements are needed.
Input: 9 10 abcabcabc 1 a 1 b 2 c 3 a 4 b 5 c 8 a 9 b 1 c 4 a | Output: 3 2 2 2 1 2 1 1 1 0
Easy
2
992
468
144
16
1,680
A
1680A
A. Minimums and Maximums
800
brute force; math
An array is beautiful if both of the following two conditions meet: there are at least \(l_1\) and at most \(r_1\) elements in the array equal to its minimum; there are at least \(l_2\) and at most \(r_2\) elements in the array equal to its maximum. For example, the array \([2, 3, 2, 4, 4, 3, 2]\) has \(3\) elements equal to its minimum (\(1\)-st, \(3\)-rd and \(7\)-th) and \(2\) elements equal to its maximum (\(4\)-th and \(5\)-th).Another example: the array \([42, 42, 42]\) has \(3\) elements equal to its minimum and \(3\) elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.
The first line contains one integer \(t\) (\(1 \le t \le 5000\)) β€” the number of test cases.Each test case consists of one line containing four integers \(l_1\), \(r_1\), \(l_2\) and \(r_2\) (\(1 \le l_1 \le r_1 \le 50\); \(1 \le l_2 \le r_2 \le 50\)).
For each test case, print one integer β€” the minimum possible number of elements in a beautiful array.
Optimal arrays in the test cases of the example: \([1, 1, 1, 1]\), it has \(4\) minimums and \(4\) maximums; \([4, 4, 4, 4, 4]\), it has \(5\) minimums and \(5\) maximums; \([1, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2]\), it has \(3\) minimums and \(10\) maximums; \([8, 8, 8]\), it has \(3\) minimums and \(3\) maximums; \([4, 6, 6]\), it has \(1\) minimum and \(2\) maximums; \([3, 4, 3]\), it has \(2\) minimums and \(1\) maximum; \([5, 5, 5, 5, 5, 5]\), it has \(6\) minimums and \(6\) maximums.
Input: 73 5 4 65 8 5 53 3 10 121 5 3 31 1 2 22 2 1 16 6 6 6 | Output: 4 5 13 3 3 3 6
Beginner
2
648
252
101
16
1,156
E
1156E
E. Special Segments of Permutation
2,200
data structures; divide and conquer; dsu; two pointers
You are given a permutation \(p\) of \(n\) integers \(1\), \(2\), ..., \(n\) (a permutation is an array where each element from \(1\) to \(n\) occurs exactly once).Let's call some subsegment \(p[l, r]\) of this permutation special if \(p_l + p_r = \max \limits_{i = l}^{r} p_i\). Please calculate the number of special subsegments.
The first line contains one integer \(n\) (\(3 \le n \le 2 \cdot 10^5\)).The second line contains \(n\) integers \(p_1\), \(p_2\), ..., \(p_n\) (\(1 \le p_i \le n\)). All these integers are pairwise distinct.
Print the number of special subsegments of the given permutation.
Special subsegments in the first example are \([1, 5]\) and \([1, 3]\).The only special subsegment in the second example is \([1, 3]\).
Input: 5 3 4 1 5 2 | Output: 2
Hard
4
331
208
65
11
1,515
E
1515E
E. Phoenix and Computers
2,200
combinatorics; dp; math
There are \(n\) computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer \(i-1\) and computer \(i+1\) are both on, computer \(i\) \((2 \le i \le n-1)\) will turn on automatically if it is not already on. Note that Phoenix cannot manually turn on a computer that already turned on automatically.If we only consider the sequence of computers that Phoenix turns on manually, how many ways can he turn on all the computers? Two sequences are distinct if either the set of computers turned on manually is distinct, or the order of computers turned on manually is distinct. Since this number may be large, please print it modulo \(M\).
The first line contains two integers \(n\) and \(M\) (\(3 \le n \le 400\); \(10^8 \le M \le 10^9\)) β€” the number of computers and the modulo. It is guaranteed that \(M\) is prime.
Print one integer β€” the number of ways to turn on the computers modulo \(M\).
In the first example, these are the \(6\) orders in which Phoenix can turn on all computers: \([1,3]\). Turn on computer \(1\), then \(3\). Note that computer \(2\) turns on automatically after computer \(3\) is turned on manually, but we only consider the sequence of computers that are turned on manually. \([3,1]\). Turn on computer \(3\), then \(1\). \([1,2,3]\). Turn on computer \(1\), \(2\), then \(3\). \([2,1,3]\) \([2,3,1]\) \([3,2,1]\)
Input: 3 100000007 | Output: 6
Hard
3
730
179
77
15
1,512
A
1512A
A. Spy Detected!
800
brute force; implementation
You are given an array \(a\) consisting of \(n\) (\(n \ge 3\)) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array \([4, 11, 4, 4]\) all numbers except one are equal to \(4\)).Print the index of the element that does not equal others. The numbers in the array are numbered from one.
The first line contains a single integer \(t\) (\(1 \le t \le 100\)). Then \(t\) test cases follow.The first line of each test case contains a single integer \(n\) (\(3 \le n \le 100\)) β€” 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 100\)).It is guaranteed that all the numbers except one in the \(a\) array are the same.
For each test case, output a single integer β€” the index of the element that is not equal to others.
Input: 4 4 11 13 11 11 5 1 4 4 4 4 10 3 3 3 3 10 3 3 3 3 3 3 20 20 10 | Output: 2 1 5 3
Beginner
2
348
407
99
15
252
A
252A
A. Little Xor
1,100
brute force; implementation
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive ""OR"", that is denoted as ""xor"" in Pascal and ""^"" in C/C++/Java.
The first line contains integer n (1 ≀ n ≀ 100) β€” the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.
Print a single integer β€” the required maximal xor of a segment of consecutive elements.
In the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
Input: 51 2 1 1 2 | Output: 3
Easy
2
426
218
87
2
132
E
132E
E. Bits of merry old England
2,700
flows; graphs
Another feature of Shakespeare language is that the variables are named after characters of plays by Shakespeare, and all operations on them (value assignment, output etc.) look like a dialog with other characters. New values of variables are defined in a rather lengthy way, so a programmer should try to minimize their usage.You have to print the given sequence of n integers. To do this, you have m variables and two types of operations on them: variable=integer print(variable) Any of the m variables can be used as variable. Variables are denoted by lowercase letters between ""a"" and ""z"", inclusive. Any integer number can be used as integer.Let's say that the penalty for using first type of operations equals to the number of set bits in the number integer. There is no penalty on using second type of operations. Find and output the program which minimizes the penalty for printing the given sequence of numbers.
The first line of input contains integers n and m (1 ≀ n ≀ 250, 1 ≀ m ≀ 26). The second line contains the sequence to be printed. Each element of the sequence is an integer between 1 and 109, inclusive. The sequence has to be printed in the given order (from left to right).
Output the number of lines in the optimal program and the optimal penalty. Next, output the program itself, one command per line. If there are several programs with minimal penalty, output any of them (you have only to minimize the penalty).
Input: 7 21 2 2 4 2 1 2 | Output: 11 4b=1print(b)a=2print(a)print(a)b=4print(b)print(a)b=1print(b)print(a)
Master
2
924
274
241
1
755
G
755G
G. PolandBall and Many Other Balls
3,200
combinatorics; divide and conquer; dp; fft; math; number theory
PolandBall is standing in a row with Many Other Balls. More precisely, there are exactly n Balls. Balls are proud of their home land β€” and they want to prove that it's strong.The Balls decided to start with selecting exactly m groups of Balls, each consisting either of single Ball or two neighboring Balls. Each Ball can join no more than one group.The Balls really want to impress their Enemies. They kindly asked you to calculate number of such divisions for all m where 1 ≀ m ≀ k. Output all these values modulo 998244353, the Enemies will be impressed anyway.
There are exactly two numbers n and k (1 ≀ n ≀ 109, 1 ≀ k < 215), denoting the number of Balls and the maximim number of groups, respectively.
You should output a sequence of k values. The i-th of them should represent the sought number of divisions into exactly i groups, according to PolandBall's rules.
In the first sample case we can divide Balls into groups as follows: {1}, {2}, {3}, {12}, {23}.{12}{3}, {1}{23}, {1}{2}, {1}{3}, {2}{3}.{1}{2}{3}.Therefore, output is: 5 5 1.
Input: 3 3 | Output: 5 5 1
Master
6
564
142
162
7
1,840
E
1840E
E. Character Blocking
1,600
data structures; hashing; implementation
You are given two strings of equal length \(s_1\) and \(s_2\), consisting of lowercase Latin letters, and an integer \(t\).You need to answer \(q\) queries, numbered from \(1\) to \(q\). The \(i\)-th query comes in the \(i\)-th second of time. Each query is one of three types: block the characters at position \(pos\) (indexed from \(1\)) in both strings for \(t\) seconds; swap two unblocked characters; determine if the two strings are equal at the time of the query, ignoring blocked characters. Note that in queries of the second type, the characters being swapped can be from the same string or from \(s_1\) and \(s_2\).
The first line of the input contains a single integer \(T\) (\(1 \le T \le 10^4\)) β€” the number of test cases.Then follow the descriptions of the test cases.The first line of each test case contains a string \(s_1\) consisting of lowercase Latin letters (length no more than \(2 \cdot 10^5\)).The second line of each test case contains a string \(s_2\) consisting of lowercase Latin letters (length no more than \(2 \cdot 10^5\)).The strings have equal length.The third line of each test case contains two integers \(t\) and \(q\) (\(1 \le t, q \le 2 \cdot 10^5\)). The number \(t\) indicates the number of seconds for which a character is blocked. The number \(q\) corresponds to the number of queries.Each of the next \(q\) lines of each test case contains a single query. Each query is one of three types: ""\(1\ \ \ pos\)"" β€” block the characters at position \(pos\) in both strings for \(t\) seconds; ""\(2\ \ \ 1/\;\!2\ \ \ pos_1\ \ \ 1/\;\!2\ \ \ pos_2\)"" β€” swap two unblocked characters. The second number in the query indicates the number of the string from which the first character for the swap is taken. The third number in the query indicates the position in that string of that character. The fourth number in the query indicates the number of the string from which the second character for the swap is taken. The fifth number in the query indicates the position in that string of that character; ""\(3\)"" β€” determine if the two strings are equal at the time of the query, ignoring blocked characters. For queries of the first type, it is guaranteed that at the time of the query, the characters at position \(pos\) are not blocked.For queries of the second type, it is guaranteed that the characters being swapped are not blocked.All values of \(pos, pos_1, pos_2\) are in the range from \(1\) to the length of the strings.The sum of the values of \(q\) over all test cases, as well as the total length of the strings \(s_1\), does not exceed \(2 \cdot 10^5\).
For each query of the third type, output ""YES"" if the two strings \(s_1\) and \(s_2\) are equal at the time of the query, ignoring blocked characters, and ""NO"" otherwise.You can output each letter in any case (lowercase or uppercase). For example, the strings ""yEs"", ""yes"", ""Yes"" and ""YES"" will be accepted as a positive answer.
Let's look at the strings \(s_1\) and \(s_2\) after each of the \(q\) queries. Blocked characters will be denoted in red.First example input:(\(codeforces\), \(codeblocks\)) \(\rightarrow\) (\(codeforces\), \(codeblocks\)) \(\rightarrow\) (\(code\color{red}{f}orces\), \(code\color{red}{b}locks\)) \(\rightarrow\) (\(code\color{red}{fo}rces\), \(code\color{red}{bl}ocks\)) \(\rightarrow\) (\(code\color{red}{for}ces\), \(code\color{red}{blo}cks\)) \(\rightarrow\) (\(code\color{red}{for}c\color{red}{e}s\), \(code\color{red}{blo}c\color{red}{k}s\)) \(\rightarrow\) (\(code\color{red}{for}c\color{red}{e}s\), \(code\color{red}{blo}c\color{red}{k}s\)) \(\rightarrow\) (\(codef\color{red}{or}c\color{red}{e}s\), \(codeb\color{red}{lo}c\color{red}{k}s\))Second example input:(\(cool\), \(club\)) \(\rightarrow\) (\(cuol\), \(clob\)) \(\rightarrow\) (\(cuol\), \(cbol\)) \(\rightarrow\) (\(c\color{red}{u}ol\), \(c\color{red}{b}ol\)) \(\rightarrow\) (\(c\color{red}{u}ol\), \(c\color{red}{b}ol\)) \(\rightarrow\) (\(cuol\), \(cbol\))
Input: 2codeforcescodeblocks5 731 51 61 71 933coolclub2 52 1 2 2 32 2 2 2 41 233 | Output: NO YES NO YES NO
Medium
3
626
1,977
340
18
268
D
268D
D. Wall Bars
2,300
dp
Manao is working for a construction company. Recently, an order came to build wall bars in a children's park. Manao was commissioned to develop a plan of construction, which will enable the company to save the most money.After reviewing the formal specifications for the wall bars, Manao discovered a number of controversial requirements and decided to treat them to the company's advantage. His resulting design can be described as follows: Let's introduce some unit of length. The construction center is a pole of height n. At heights 1, 2, ..., n exactly one horizontal bar sticks out from the pole. Each bar sticks in one of four pre-fixed directions. A child can move from one bar to another if the distance between them does not exceed h and they stick in the same direction. If a child is on the ground, he can climb onto any of the bars at height between 1 and h. In Manao's construction a child should be able to reach at least one of the bars at heights n - h + 1, n - h + 2, ..., n if he begins at the ground. The figure to the left shows what a common set of wall bars looks like. The figure to the right shows Manao's construction Manao is wondering how many distinct construction designs that satisfy his requirements exist. As this number can be rather large, print the remainder after dividing it by 1000000009 (109 + 9). Two designs are considered distinct if there is such height i, that the bars on the height i in these designs don't stick out in the same direction.
A single line contains two space-separated integers, n and h (1 ≀ n ≀ 1000, 1 ≀ h ≀ min(n, 30)).
In a single line print the remainder after dividing the number of designs by 1000000009 (109 + 9).
Consider several designs for h = 2. A design with the first bar sticked out in direction d1, the second β€” in direction d2 and so on (1 ≀ di ≀ 4) is denoted as string d1d2...dn.Design ""1231"" (the first three bars are sticked out in different directions, the last one β€” in the same as first). A child can reach neither the bar at height 3 nor the bar at height 4.Design ""414141"". A child can reach the bar at height 5. To do this, he should first climb at the first bar, then at the third and then at the fifth one. He can also reach bar at height 6 by the route second β†’ fourth β†’ sixth bars.Design ""123333"". The child can't reach the upper two bars.Design ""323323"". The bar at height 6 can be reached by the following route: first β†’ third β†’ fourth β†’ sixth bars.
Input: 5 1 | Output: 4
Expert
1
1,486
96
98
2
1,859
B
1859B
B. Olya and Game with Arrays
1,000
constructive algorithms; greedy; math; sortings
Artem suggested a game to the girl Olya. There is a list of \(n\) arrays, where the \(i\)-th array contains \(m_i \ge 2\) positive integers \(a_{i,1}, a_{i,2}, \ldots, a_{i,m_i}\).Olya can move at most one (possibly \(0\)) integer from each array to another array. Note that integers can be moved from one array only once, but integers can be added to one array multiple times, and all the movements are done at the same time.The beauty of the list of arrays is defined as the sum \(\sum_{i=1}^n \min_{j=1}^{m_i} a_{i,j}\). In other words, for each array, we find the minimum value in it and then sum up these values.The goal of the game is to maximize the beauty of the list of arrays. Help Olya win this challenging game!
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 25000\)) β€” the number of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 25000\)) β€” the number of arrays in the list.This is followed by descriptions of the arrays. Each array description consists of two lines.The first line contains a single integer \(m_i\) (\(2 \le m_i \le 50000\)) β€” the number of elements in the \(i\)-th array.The next line contains \(m_i\) integers \(a_{i, 1}, a_{i, 2}, \ldots, a_{i, m_i}\) (\(1 \le a_{i,j} \le 10^9\)) β€” the elements of the \(i\)-th array.It is guaranteed that the sum of \(m_i\) over all test cases does not exceed \(50000\).
For each test case, output a single line containing a single integer β€” the maximum beauty of the list of arrays that Olya can achieve.
In the first test case, we can move the integer \(3\) from the second array to the first array. Then the beauty is \(\min(1, 2, 3) + \min(4) = 5\). It can be shown that this is the maximum possible beauty.In the second test case, there is only one array, so regardless of the movements, the beauty will be \(\min(100, 1, 6) = 1\).
Input: 3221 224 313100 1 6341001 7 1007 538 11 622 9 | Output: 5 1 19
Beginner
4
723
755
134
18
1,060
B
1060B
B. Maximum Sum of Digits
1,100
greedy
You are given a positive integer \(n\).Let \(S(x)\) be sum of digits in base 10 representation of \(x\), for example, \(S(123) = 1 + 2 + 3 = 6\), \(S(0) = 0\).Your task is to find two integers \(a, b\), such that \(0 \leq a, b \leq n\), \(a + b = n\) and \(S(a) + S(b)\) is the largest possible among all such pairs.
The only line of input contains an integer \(n\) \((1 \leq n \leq 10^{12})\).
Print largest \(S(a) + S(b)\) among all pairs of integers \(a, b\), such that \(0 \leq a, b \leq n\) and \(a + b = n\).
In the first example, you can choose, for example, \(a = 17\) and \(b = 18\), so that \(S(17) + S(18) = 1 + 7 + 1 + 8 = 17\). It can be shown that it is impossible to get a larger answer.In the second test example, you can choose, for example, \(a = 5000000001\) and \(b = 4999999999\), with \(S(5000000001) + S(4999999999) = 91\). It can be shown that it is impossible to get a larger answer.
Input: 35 | Output: 17
Easy
1
316
77
119
10
875
E
875E
E. Delivery Club
2,600
binary search; data structures; dp
Petya and Vasya got employed as couriers. During the working day they are to deliver packages to n different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate s1, Vasya is at the point with the coordinate s2, and the clients are at the points x1, x2, ..., xn in the order of the required visit.The guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the i-th client is delivered, the one who delivers the package to the (i + 1)-st client is sent to the path (it can be the same person who went to the point xi, or the other). The friend who is not busy in delivering the current package, is standing still.To communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules.
The first line contains three integers n, s1, s2 (1 ≀ n ≀ 100 000, 0 ≀ s1, s2 ≀ 109) β€” number of points of delivery and starting positions of Petya and Vasya.The second line contains n integers x1, x2, ..., xn β€” customers coordinates (0 ≀ xi ≀ 109), in the order to make a delivery. It is guaranteed, that among the numbers s1, s2, x1, ..., xn there are no two equal.
Output the only integer, minimum possible maximal distance between couriers during delivery.
In the first test case the initial distance between the couriers is 10. This value will be the answer, for example, Petya can perform both deliveries, and Vasya will remain at the starting point.In the second test case you can optimally act, for example, like this: Vasya delivers the package to the first customer, Petya to the second and, finally, Vasya delivers the package to the third client. With this order of delivery, the distance between the couriers will never exceed 1.In the third test case only two variants are possible: if the delivery of a single package is carried out by Petya, the maximum distance between them will be 5 - 2 = 3. If Vasya will deliver the package, the maximum distance is 4 - 2 = 2. The latter method is optimal.
Input: 2 0 105 6 | Output: 10
Expert
3
1,181
367
92
8
1,201
B
1201B
B. Zero Array
1,500
greedy; math
You are given an array \(a_1, a_2, \ldots, a_n\).In one operation you can choose two elements \(a_i\) and \(a_j\) (\(i \ne j\)) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.
The first line contains a single integer \(n\) (\(2 \le n \le 10^5\)) β€” the size of the array.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)) β€” the elements of the array.
Print ""YES"" if it is possible to make all elements zero, otherwise print ""NO"".
In the first example, you can make all elements equal to zero in \(3\) operations: Decrease \(a_1\) and \(a_2\), Decrease \(a_3\) and \(a_4\), Decrease \(a_3\) and \(a_4\) In the second example, one can show that it is impossible to make all elements equal to zero.
Input: 4 1 1 2 2 | Output: YES
Medium
2
248
213
82
12
1,838
D
1838D
D. Bracket Walk
2,100
data structures; greedy; strings
There is a string \(s\) of length \(n\) consisting of the characters '(' and ')'. You are walking on this string. You start by standing on top of the first character of \(s\), and you want to make a sequence of moves such that you end on the \(n\)-th character. In one step, you can move one space to the left (if you are not standing on the first character), or one space to the right (if you are not standing on the last character). You may not stay in the same place, however you may visit any character, including the first and last character, any number of times.At each point in time, you write down the character you are currently standing on. We say the string is walkable if there exists some sequence of moves that take you from the first character to the last character, such that the string you write down is a regular bracket sequence.A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences ""()()"", ""(())"" are regular (the resulting expressions are: ""(1)+(1)"", ""((1+1)+1)""), and "")("" and ""("" are not.One possible valid walk on \(s=\mathtt{(())()))}\). The red dot indicates your current position, and the red string indicates the string you have written down. Note that the red string is a regular bracket sequence at the end of the process.You are given \(q\) queries. Each query flips the value of a character from '(' to ')' or vice versa. After each query, determine whether the string is walkable.Queries are cumulative, so the effects of each query carry on to future queries.
The first line of the input contains two integers \(n\) and \(q\) (\(1 \le n, q \le 2\cdot 10^5\)) β€” the size of the string and the number of queries, respectively.The second line of the input contains a string \(s\) of size \(n\), consisting of the characters '(' and ')' β€” the initial bracket string.Each of the next \(q\) lines contains a single integer \(i\) (\(1\le i \le n\)) β€” the index of the character to flip for that query.
For each query, print ""YES"" if the string is walkable after that query, and ""NO"" otherwise.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In the first example: After the first query, the string is (())()()(). This string is a regular bracket sequence, so it is walkable by simply moving to the right. After the second query, the string is (())()))(). If you move right once, then left once, then walk right until you hit the end of the string, you produce the string (((())()))(), which is a regular bracket sequence. After the third query, the string is ()))()))(). We can show that this string is not walkable. In the second example, the strings after the queries are ()) and ()(, neither of which are walkable.
Input: 10 9 (())()())) 9 7 2 6 3 6 7 4 8 | Output: YES YES NO NO YES NO YES NO NO
Hard
3
1,677
434
256
18
165
E
165E
E. Compatible Numbers
2,200
bitmasks; brute force; dfs and similar; dp
Two integers x and y are compatible, if the result of their bitwise ""AND"" equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.You are given an array of integers a1, a2, ..., an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.
The first line contains an integer n (1 ≀ n ≀ 106) β€” the number of elements in the given array. The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 4Β·106) β€” the elements of the given array. The numbers in the array can coincide.
Print n integers ansi. If ai isn't compatible with any other element of the given array a1, a2, ..., an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi = 0, and also ansi occurs in the array a1, a2, ..., an.
Input: 290 36 | Output: 36 90
Hard
4
553
254
243
1
630
L
630L
L. Cracking the Code
1,400
implementation; math
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose β€” to show the developer the imperfection of their protection.The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455 422 043 125 550 171 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.Vasya is going to write a keygen program implementing this algorithm. Can you do the same?
The only line of the input contains a positive integer five digit number for which the activation code should be found.
Output exactly 5 digits without spaces between them β€” the found activation code of the program.
Input: 12345 | Output: 71232
Easy
2
1,123
119
95
6
976
F
976F
F. Minimal k-covering
2,500
flows; graphs
You are given a bipartite graph G = (U, V, E), U is the set of vertices of the first part, V is the set of vertices of the second part and E is the set of edges. There might be multiple edges.Let's call some subset of its edges k-covering iff the graph has each of its vertices incident to at least k edges. Minimal k-covering is such a k-covering that the size of the subset is minimal possible.Your task is to find minimal k-covering for each , where minDegree is the minimal degree of any vertex in graph G.
The first line contains three integers n1, n2 and m (1 ≀ n1, n2 ≀ 2000, 0 ≀ m ≀ 2000) β€” the number of vertices in the first part, the number of vertices in the second part and the number of edges, respectively.The i-th of the next m lines contain two integers ui and vi (1 ≀ ui ≀ n1, 1 ≀ vi ≀ n2) β€” the description of the i-th edge, ui is the index of the vertex in the first part and vi is the index of the vertex in the second part.
For each print the subset of edges (minimal k-covering) in separate line.The first integer cntk of the k-th line is the number of edges in minimal k-covering of the graph. Then cntk integers follow β€” original indices of the edges which belong to the minimal k-covering, these indices should be pairwise distinct. Edges are numbered 1 through m in order they are given in the input.
Input: 3 3 71 22 31 33 23 32 12 1 | Output: 0 3 3 7 4 6 1 3 6 7 4 5
Expert
2
510
434
381
9
1,670
A
1670A
A. Prof. Slim
800
greedy; implementation; sortings
One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were happy sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.Given an array of \(n\) integers \(a_1,a_2,\ldots,a_n\), where \(a_{i} \neq 0\), check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order. select two indices \(i\) and \(j\) (\(1 \le i,j \le n\)) such that \(a_i\) and \(a_j\) have different signs. In other words, one must be positive and one must be negative. swap the signs of \(a_{i}\) and \(a_{j}\). For example if you select \(a_i=3\) and \(a_j=-2\), then they will change to \(a_i=-3\) and \(a_j=2\). Prof. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^{5}\)) β€” the length of the array \(a\).The next line contain \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^9 \le a_{i} \le 10^9\), \(a_{i} \neq 0\)) separated by spaces describing elements of the array \(a\). It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(10^5\).
For each test case, print ""YES"" if the array can be sorted in the non-decreasing order, otherwise print ""NO"". You can print each letter in any case (upper or lower).
In the first test case, there is no way to make the array sorted using the operation any number of times.In the second test case, the array is already sorted.In the third test case, we can swap the sign of the \(1\)-st element with the sign of the \(5\)-th element, and the sign of the \(3\)-rd element with the sign of the \(6\)-th element, this way the array will be sorted.In the fourth test case, there is no way to make the array sorted using the operation any number of times.
Input: 477 3 2 -11 -13 -17 -2364 10 25 47 71 96671 -35 7 -4 -11 -256-45 9 -48 -67 -55 7 | Output: NO YES YES NO
Beginner
3
1,120
504
169
16
227
A
227A
A. Where do I Turn?
1,300
geometry
Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point C and began to terrorize the residents of the surrounding villages.A brave hero decided to put an end to the dragon. He moved from point A to fight with Gorynych. The hero rode from point A along a straight road and met point B on his way. The hero knows that in this land for every pair of roads it is true that they are either parallel to each other, or lie on a straight line, or are perpendicular to each other. He also knows well that points B and C are connected by a road. So the hero must either turn 90 degrees to the left or continue riding straight ahead or turn 90 degrees to the right. But he forgot where the point C is located.Fortunately, a Brave Falcon flew right by. It can see all three points from the sky. The hero asked him what way to go to get to the dragon's lair.If you have not got it, you are the falcon. Help the hero and tell him how to get him to point C: turn left, go straight or turn right.At this moment the hero is believed to stand at point B, turning his back to point A.
The first input line contains two space-separated integers xa, ya (|xa|, |ya| ≀ 109) β€” the coordinates of point A. The second line contains the coordinates of point B in the same form, the third line contains the coordinates of point C.It is guaranteed that all points are pairwise different. It is also guaranteed that either point B lies on segment AC, or angle ABC is right.
Print a single line. If a hero must turn left, print ""LEFT"" (without the quotes); If he must go straight ahead, print ""TOWARDS"" (without the quotes); if he should turn right, print ""RIGHT"" (without the quotes).
The picture to the first sample: The red color shows points A, B and C. The blue arrow shows the hero's direction. The green color shows the hero's trajectory.The picture to the second sample:
Input: 0 00 11 1 | Output: RIGHT
Easy
1
1,115
377
216
2
1,326
D2
1326D2
D2. Prefix-Suffix Palindrome (Hard version)
1,800
binary search; greedy; hashing; string suffix structures; strings
This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string \(s\), consisting of lowercase English letters. Find the longest string, \(t\), which satisfies the following conditions: The length of \(t\) does not exceed the length of \(s\). \(t\) is a palindrome. There exists two strings \(a\) and \(b\) (possibly empty), such that \(t = a + b\) ( ""\(+\)"" represents concatenation), and \(a\) is prefix of \(s\) while \(b\) is suffix of \(s\).
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 10^5\)), the number of test cases. The next \(t\) lines each describe a test case.Each test case is a non-empty string \(s\), consisting of lowercase English letters.It is guaranteed that the sum of lengths of strings over all test cases does not exceed \(10^6\).
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
In the first test, the string \(s = \)""a"" satisfies all conditions.In the second test, the string ""abcdfdcba"" satisfies all conditions, because: Its length is \(9\), which does not exceed the length of the string \(s\), which equals \(11\). It is a palindrome. ""abcdfdcba"" \(=\) ""abcdfdc"" \(+\) ""ba"", and ""abcdfdc"" is a prefix of \(s\) while ""ba"" is a suffix of \(s\). It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string ""c"" is correct, because ""c"" \(=\) ""c"" \(+\) """" and \(a\) or \(b\) can be empty. The other possible solution for this test is ""s"".
Input: 5 a abcdfdcecba abbaxyzyx codeforces acbba | Output: a abcdfdcba xyzyx c abba
Medium
5
607
370
156
13
1,623
E
1623E
E. Middle Duplication
2,500
data structures; dfs and similar; greedy; strings; trees
A binary tree of \(n\) nodes is given. Nodes of the tree are numbered from \(1\) to \(n\) and the root is the node \(1\). Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote \(l_u\) and \(r_u\) as the left and the right child of the node \(u\) respectively, \(l_u = 0\) if \(u\) does not have the left child, and \(r_u = 0\) if the node \(u\) does not have the right child.Each node has a string label, initially is a single character \(c_u\). Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let \(f(u)\) be the string representation of the tree rooted at the node \(u\). \(f(u)\) is defined as follows: $$$\( f(u) = \begin{cases} \texttt{<empty string>}, & \text{if }u = 0; \\ f(l_u) + c_u + f(r_u) & \text{otherwise}, \end{cases} \)\( where \)+\( denotes the string concatenation operation.This way, the string representation of the tree is \)f(1)\(.For each node, we can duplicate its label at most once, that is, assign \)c_u\( with \)c_u + c_u\(, but only if \)u\( is the root of the tree, or if its parent also has its label duplicated.You are given the tree and an integer \)k\(. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most \)k\( nodes?A string \)a\( is lexicographically smaller than a string \)b\( if and only if one of the following holds: \)a\( is a prefix of \)b\(, but \)a \ne b\(; in the first position where \)a\( and \)b\( differ, the string \)a\( has a letter that appears earlier in the alphabet than the corresponding letter in \)b$$$.
The first line contains two integers \(n\) and \(k\) (\(1 \le k \le n \le 2 \cdot 10^5\)).The second line contains a string \(c\) of \(n\) lower-case English letters, where \(c_i\) is the initial label of the node \(i\) for \(1 \le i \le n\). Note that the given string \(c\) is not the initial string representation of the tree.The \(i\)-th of the next \(n\) lines contains two integers \(l_i\) and \(r_i\) (\(0 \le l_i, r_i \le n\)). If the node \(i\) does not have the left child, \(l_i = 0\), and if the node \(i\) does not have the right child, \(r_i = 0\).It is guaranteed that the given input forms a binary tree, rooted at \(1\).
Print a single line, containing the lexicographically smallest string representation of the tree if at most \(k\) nodes have their labels duplicated.
The images below present the tree for the examples. The number in each node is the node number, while the subscripted letter is its label. To the right is the string representation of the tree, with each letter having the same color as the corresponding node.Here is the tree for the first example. Here we duplicated the labels of nodes \(1\) and \(3\). We should not duplicate the label of node \(2\) because it would give us the string ""bbaaab"", which is lexicographically greater than ""baaaab"". In the second example, we can duplicate the labels of nodes \(1\) and \(2\). Note that only duplicating the label of the root will produce a worse result than the initial string. In the third example, we should not duplicate any character at all. Even though we would want to duplicate the label of the node \(3\), by duplicating it we must also duplicate the label of the node \(2\), which produces a worse result. There is no way to produce string ""darkkcyan"" from a tree with the initial string representation ""darkcyan"" :(.
Input: 4 3 abab 2 3 0 0 0 4 0 0 | Output: baaaab
Expert
5
1,675
637
149
16
160
A
160A
A. Twins
900
greedy; sortings
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. ""But why split the money equally?"" β€” you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.
The first line contains integer n (1 ≀ n ≀ 100) β€” the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≀ ai ≀ 100) β€” the coins' values. All numbers are separated with spaces.
In the single line print the single number β€” the minimum needed number of coins.
In the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.
Input: 23 3 | Output: 2
Beginner
2
1,545
211
80
1
1,054
A
1054A
A. Elevator or Stairs?
800
implementation
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor \(x\), Egor on the floor \(y\) (not on the same floor with Masha).The house has a staircase and an elevator. If Masha uses the stairs, it takes \(t_1\) seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in \(t_2\) seconds. The elevator moves with doors closed. The elevator spends \(t_3\) seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor.Coming out of the apartment on her floor, Masha noticed that the elevator is now on the floor \(z\) and has closed doors. Now she has to choose whether to use the stairs or use the elevator. If the time that Masha needs to get to the Egor's floor by the stairs is strictly less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator.Help Mary to understand whether to use the elevator or the stairs.
The only line contains six integers \(x\), \(y\), \(z\), \(t_1\), \(t_2\), \(t_3\) (\(1 \leq x, y, z, t_1, t_2, t_3 \leq 1000\)) β€” the floor Masha is at, the floor Masha wants to get to, the floor the elevator is located on, the time it takes Masha to pass between two floors by stairs, the time it takes the elevator to pass between two floors and the time it takes for the elevator to close or open the doors.It is guaranteed that \(x \ne y\).
If the time it will take to use the elevator is not greater than the time it will take to use the stairs, print Β«YESΒ» (without quotes), otherwise print Β«NO> (without quotes).You can print each letter in any case (upper or lower).
In the first example:If Masha goes by the stairs, the time she spends is \(4 \cdot 4 = 16\), because she has to go \(4\) times between adjacent floors and each time she spends \(4\) seconds. If she chooses the elevator, she will have to wait \(2\) seconds while the elevator leaves the \(4\)-th floor and goes to the \(5\)-th. After that the doors will be opening for another \(1\) second. Then Masha will enter the elevator, and she will have to wait for \(1\) second for the doors closing. Next, the elevator will spend \(4 \cdot 2 = 8\) seconds going from the \(5\)-th floor to the \(1\)-st, because the elevator has to pass \(4\) times between adjacent floors and spends \(2\) seconds each time. And finally, it will take another \(1\) second before the doors are open and Masha can come out. Thus, all the way by elevator will take \(2 + 1 + 1 + 8 + 1 = 13\) seconds, which is less than \(16\) seconds, so Masha has to choose the elevator.In the second example, it is more profitable for Masha to use the stairs, because it will take \(13\) seconds to use the elevator, that is more than the \(10\) seconds it will takes to go by foot.In the third example, the time it takes to use the elevator is equal to the time it takes to walk up by the stairs, and is equal to \(12\) seconds. That means Masha will take the elevator.
Input: 5 1 4 4 2 1 | Output: YES
Beginner
1
1,283
445
229
10
1,972
A
1972A
A. Contest Proposal
800
brute force; greedy; two pointers
A contest contains \(n\) problems and the difficulty of the \(i\)-th problem is expected to be at most \(b_i\). There are already \(n\) problem proposals and the difficulty of the \(i\)-th problem is \(a_i\). Initially, both \(a_1, a_2, \ldots, a_n\) and \(b_1, b_2, \ldots, b_n\) are sorted in non-decreasing order.Some of the problems may be more difficult than expected, so the writers must propose more problems. When a new problem with difficulty \(w\) is proposed, the most difficult problem will be deleted from the contest, and the problems will be sorted in a way that the difficulties are non-decreasing.In other words, in each operation, you choose an integer \(w\), insert it into the array \(a\), sort array \(a\) in non-decreasing order, and remove the last element from it.Find the minimum number of new problems to make \(a_i\le b_i\) for all \(i\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1\le t\le 100\)). The description of the test cases follows.The first line of each test case contains only one positive integer \(n\) (\(1 \leq n \leq 100\)), representing the number of problems.The second line of each test case contains an array \(a\) of length \(n\) (\(1\le a_1\le a_2\le\cdots\le a_n\le 10^9\)).The third line of each test case contains an array \(b\) of length \(n\) (\(1\le b_1\le b_2\le\cdots\le b_n\le 10^9\)).
For each test case, print an integer as your answer in a new line.
In the first test case: Propose a problem with difficulty \(w=800\) and \(a\) becomes \([800,1000,1400,2000,2000,2200]\). Propose a problem with difficulty \(w=1800\) and \(a\) becomes \([800,1000,1400,1800,2000,2000]\). It can be proved that it's impossible to reach the goal by proposing fewer new problems.In the second test case: Propose a problem with difficulty \(w=1\) and \(a\) becomes \([1,4,5,6,7,8]\). Propose a problem with difficulty \(w=2\) and \(a\) becomes \([1,2,4,5,6,7]\). Propose a problem with difficulty \(w=3\) and \(a\) becomes \([1,2,3,4,5,6]\). It can be proved that it's impossible to reach the goal by proposing fewer new problems.
Input: 261000 1400 2000 2000 2200 2700800 1200 1500 1800 2200 300064 5 6 7 8 91 2 3 4 5 6 | Output: 2 3
Beginner
3
865
532
66
19
1,028
H
1028H
H. Make Square
2,900
math
We call an array \(b_1, b_2, \ldots, b_m\) good, if there exist two indices \(i < j\) such that \(b_i \cdot b_j\) is a perfect square.Given an array \(b_1, b_2, \ldots, b_m\), in one action you can perform one of the following: multiply any element \(b_i\) by any prime \(p\); divide any element \(b_i\) by prime \(p\), if \(b_i\) is divisible by \(p\). Let \(f(b_1, b_2, \ldots, b_m)\) be the minimum number of actions needed to make the array \(b\) good.You are given an array of \(n\) integers \(a_1, a_2, \ldots, a_n\) and \(q\) queries of the form \(l_i, r_i\). For each query output \(f(a_{l_i}, a_{l_i + 1}, \ldots, a_{r_i})\).
The first line contains two integers \(n\) and \(q\) (\(2 \le n \le 194\,598\), \(1 \le q \le 1\,049\,658\)) β€” the length of the array and the number of queries.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 5\,032\,107\)) β€” the elements of the array.Each of the next \(q\) lines contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i < r_i \le n\)) β€” the parameters of a query.
Output \(q\) lines β€” the answers for each query in the order they are given in the input.
In the first query of the first sample you can multiply second number by 7 to get 259 and multiply the third one by 37 to get 1036. Then \(a_2 \cdot a_3 = 268\,324 = 518^2\).In the second query subarray is already good because \(a_4 \cdot a_6 = 24^2\).In the third query you can divide 50 by 2 to get 25. Then \(a_6 \cdot a_8 = 30^2\).
Input: 10 1034 37 28 16 44 36 43 50 22 131 34 86 109 103 108 95 61 41 72 6 | Output: 2013011100
Master
1
634
414
89
10
923
C
923C
C. Perfect Security
1,800
data structures; greedy; strings; trees
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai < 230) representing the encrypted message.The third line contains N integers P1, P2, ..., PN (0 ≀ Pi < 230) representing the permuted encryption key.
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
In the first case, the solution is (10, 3, 28), since , and . Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Input: 38 4 1317 2 7 | Output: 10 3 28
Medium
4
1,999
297
139
9
2,080
C
2080C
2,300
*special
Expert
1
0
0
0
20
1,334
C
1334C
C. Circle of Monsters
1,600
brute force; constructive algorithms; greedy; math
You are playing another computer game, and now you have to slay \(n\) monsters. These monsters are standing in a circle, numbered clockwise from \(1\) to \(n\). Initially, the \(i\)-th monster has \(a_i\) health.You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by \(1\) (deals \(1\) damage to it). Furthermore, when the health of some monster \(i\) becomes \(0\) or less than \(0\), it dies and explodes, dealing \(b_i\) damage to the next monster (monster \(i + 1\), if \(i < n\), or monster \(1\), if \(i = n\)). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.You have to calculate the minimum number of bullets you have to fire to kill all \(n\) monsters in the circle.
The first line contains one integer \(T\) (\(1 \le T \le 150000\)) β€” the number of test cases.Then the test cases follow, each test case begins with a line containing one integer \(n\) (\(2 \le n \le 300000\)) β€” the number of monsters. Then \(n\) lines follow, each containing two integers \(a_i\) and \(b_i\) (\(1 \le a_i, b_i \le 10^{12}\)) β€” the parameters of the \(i\)-th monster in the circle.It is guaranteed that the total number of monsters in all test cases does not exceed \(300000\).
For each test case, print one integer β€” the minimum number of bullets you have to fire to kill all of the monsters.
Input: 1 3 7 15 2 14 5 3 | Output: 6
Medium
4
904
494
115
13
1,256
D
1256D
D. Binary String Minimizing
1,500
greedy
You are given a binary string of length \(n\) (i. e. a string consisting of \(n\) characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than \(k\) moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices \(i\) and \(i+1\) arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer \(q\) independent test cases.
The first line of the input contains one integer \(q\) (\(1 \le q \le 10^4\)) β€” the number of test cases.The first line of the test case contains two integers \(n\) and \(k\) (\(1 \le n \le 10^6, 1 \le k \le n^2\)) β€” the length of the string and the number of moves you can perform.The second line of the test case contains one string consisting of \(n\) characters '0' and '1'.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\) (\(\sum n \le 10^6\)).
For each test case, print the answer on it: the lexicographically minimum possible string of length \(n\) you can obtain from the given one if you can perform no more than \(k\) moves.
In the first example, you can change the string as follows: \(1\underline{10}11010 \rightarrow \underline{10}111010 \rightarrow 0111\underline{10}10 \rightarrow 011\underline{10}110 \rightarrow 01\underline{10}1110 \rightarrow 01011110\). In the third example, there are enough operations to make the string sorted.
Input: 3 8 5 11011010 7 9 1111100 7 11 1111100 | Output: 01011110 0101111 0011111
Medium
1
587
484
184
12
1,854
A2
1854A2
A2. Dual (Hard Version)
1,900
constructive algorithms; math
Popskyy & tiasu - Dualβ €The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.You are given an array \(a_1, a_2,\dots, a_n\) of integers (positive, negative or \(0\)). You can perform multiple operations on the array (possibly \(0\) operations).In one operation, you choose \(i, j\) (\(1 \leq i, j \leq n\), they can be equal) and set \(a_i := a_i + a_j\) (i.e., add \(a_j\) to \(a_i\)).Make the array non-decreasing (i.e., \(a_i \leq a_{i+1}\) for \(1 \leq i \leq n-1\)) in at most \(31\) operations. You do not need to minimize the number of operations.
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 contains a single integer \(n\) (\(1 \le n \le 20\)) β€” the length of the array.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-20 \le a_i \le 20\)) β€” the array before performing the operations.
For each test case, output your operations in the following format.The first line should contain an integer \(k\) (\(0 \le k \le 31\)) β€” the number of operations.The next \(k\) lines represent the \(k\) operations in order. Each of these \(k\) lines should contain two integers \(i\) and \(j\) (\(1 \leq i, j \leq n\)) β€” the corresponding operation consists in adding \(a_j\) to \(a_i\).After all the operations, the array \(a_1, a_2,\dots, a_n\) must be non-decreasing.
In the first test case, by adding \(a_1 = 2\) to \(a_2\), we get the array \([2, 3]\) which is non-decreasing.In the second test case, the array changes as: \([1, 2, -10, 3]\) \([1, 2, -10, 6]\) \([1, 2, -10, 12]\) \([1, 2, 2, 12]\) In the third test case, the final array is \([2, 3, 3, 3, 3]\).
Input: 1022 141 2 -10 352 1 1 1 180 0 0 0 0 0 0 051 2 -4 3 -101011 12 13 14 15 -15 -16 -17 -18 -1971 9 3 -4 -3 -2 -1310 9 8201 -14 2 -10 6 -5 10 -13 10 7 -14 19 -5 19 1 18 -16 -7 12 820-15 -17 -13 8 14 -13 10 -4 11 -4 -16 -6 15 -4 -2 7 -9 5 -5 17 | Output: 1 2 1 3 4 4 4 4 3 4 4 2 1 3 1 4 1 5 1 0 7 3 4 3 4 5 4 5 4 5 4 5 4 5 4 15 6 1 6 1 6 1 7 2 7 2 7 2 8 3 8 3 8 3 9 4 9 4 9 4 10 5 10 5 10 5 8 3 4 3 4 2 4 2 4 2 4 2 4 1 4 1 4 3 2 1 3 1 3 1 31 14 1 18 7 13 11 15 11 6 4 5 17 19 6 19 12 10 5 11 12 1 17 15 19 16 10 14 2 16 11 20 7 7 6 9 5 3 6 6 14 17 18 18 14 12 3 17 16 8 18 13 16 9 8 14 8 16 2 11 8 12 7 31 5 12 19 13 9 1 5 17 18 19 6 16 15 8 6 9 15 14 7 10 19 7 17 20 14 4 15 20 4 3 1 8 16 12 16 15 5 6 12 10 11 15 20 3 20 19 13 14 11 14 18 10 7 3 12 17 4 7 13 2 11 13
Hard
2
682
390
470
18
762
E
762E
E. Radio stations
2,200
binary search; data structures
In the lattice points of the coordinate line there are n radio stations, the i-th of which is described by three integers: xi β€” the coordinate of the i-th station on the line, ri β€” the broadcasting range of the i-th station, fi β€” the broadcasting frequency of the i-th station. We will say that two radio stations with numbers i and j reach each other, if the broadcasting range of each of them is more or equal to the distance between them. In other words min(ri, rj) β‰₯ |xi - xj|.Let's call a pair of radio stations (i, j) bad if i < j, stations i and j reach each other and they are close in frequency, that is, |fi - fj| ≀ k.Find the number of bad pairs of radio stations.
The first line contains two integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 10) β€” the number of radio stations and the maximum difference in the frequencies for the pair of stations that reach each other to be considered bad.In the next n lines follow the descriptions of radio stations. Each line contains three integers xi, ri and fi (1 ≀ xi, ri ≀ 109, 1 ≀ fi ≀ 104) β€” the coordinate of the i-th radio station, it's broadcasting range and it's broadcasting frequency. No two radio stations will share a coordinate.
Output the number of bad pairs of radio stations.
Input: 3 21 3 103 2 54 10 8 | Output: 1
Hard
2
675
507
49
7
514
E
514E
E. Darth Vader and Tree
2,200
dp; matrices
When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes.But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' β€” you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7.
The first line contains two space-separated integers n and x (1 ≀ n ≀ 105, 0 ≀ x ≀ 109) β€” the number of children of each node and the distance from the root within the range of which you need to count the nodes.The next line contains n space-separated integers di (1 ≀ di ≀ 100) β€” the length of the edge that connects each node with its i-th child.
Print a single number β€” the number of vertexes in the tree at distance from the root equal to at most x.
Pictures to the sample (the yellow color marks the nodes the distance to which is at most three)
Input: 3 31 2 3 | Output: 8
Hard
2
738
348
104
5
1,372
E
1372E
E. Omkar and Last Floor
2,900
dp; greedy; two pointers
Omkar is building a house. He wants to decide how to make the floor plan for the last floor.Omkar's floor starts out as \(n\) rows of \(m\) zeros (\(1 \le n,m \le 100\)). Every row is divided into intervals such that every \(0\) in the row is in exactly \(1\) interval. For every interval for every row, Omkar can change exactly one of the \(0\)s contained in that interval to a \(1\). Omkar defines the quality of a floor as the sum of the squares of the sums of the values in each column, i. e. if the sum of the values in the \(i\)-th column is \(q_i\), then the quality of the floor is \(\sum_{i = 1}^m q_i^2\).Help Omkar find the maximum quality that the floor can have.
The first line contains two integers, \(n\) and \(m\) (\(1 \le n,m \le 100\)), which are the number of rows and number of columns, respectively.You will then receive a description of the intervals in each row. For every row \(i\) from \(1\) to \(n\): The first row contains a single integer \(k_i\) (\(1 \le k_i \le m\)), which is the number of intervals on row \(i\). The \(j\)-th of the next \(k_i\) lines contains two integers \(l_{i,j}\) and \(r_{i,j}\), which are the left and right bound (both inclusive), respectively, of the \(j\)-th interval of the \(i\)-th row. It is guaranteed that all intervals other than the first interval will be directly after the interval before it. Formally, \(l_{i,1} = 1\), \(l_{i,j} \leq r_{i,j}\) for all \(1 \le j \le k_i\), \(r_{i,j-1} + 1 = l_{i,j}\) for all \(2 \le j \le k_i\), and \(r_{i,k_i} = m\).
Output one integer, which is the maximum possible quality of an eligible floor plan.
The given test case corresponds to the following diagram. Cells in the same row and have the same number are a part of the same interval. The most optimal assignment is: The sum of the \(1\)st column is \(4\), the sum of the \(2\)nd column is \(2\), the sum of the \(3\)rd and \(4\)th columns are \(0\), and the sum of the \(5\)th column is \(4\).The quality of this floor plan is \(4^2 + 2^2 + 0^2 + 0^2 + 4^2 = 36\). You can show that there is no floor plan with a higher quality.
Input: 4 5 2 1 2 3 5 2 1 3 4 5 3 1 1 2 4 5 5 3 1 1 2 2 3 5 | Output: 36
Master
3
675
845
84
13
288
E
288E
E. Polo the Penguin and Lucky Numbers
2,800
dp; implementation; math
Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Polo the Penguin have two positive integers l and r (l < r), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other.Let's assume that n is the number of distinct lucky numbers, each of them cannot be greater than r or less than l, and ai is the i-th (in increasing order) number of them. Find a1Β·a2 + a2Β·a3 + ... + an - 1Β·an. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).
The first line contains a positive integer l, and the second line contains a positive integer r (1 ≀ l < r ≀ 10100000). The numbers are given without any leading zeroes.It is guaranteed that the lengths of the given numbers are equal to each other and that both of them are lucky numbers.
In the single line print a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).
Input: 47 | Output: 28
Master
3
731
288
98
2
1,658
D1
1658D1
D1. 388535 (Easy Version)
1,600
bitmasks; math
This is the easy version of the problem. The difference in the constraints between both versions is colored below in red. You can make hacks only if all versions of the problem are solved.Marin and Gojou are playing hide-and-seek with an array.Gojou initially performs the following steps: First, Gojou chooses \(2\) integers \(l\) and \(r\) such that \(l \leq r\). Then, Gojou makes an array \(a\) of length \(r-l+1\) which is a permutation of the array \([l,l+1,\ldots,r]\). Finally, Gojou chooses a secret integer \(x\) and sets \(a_i\) to \(a_i \oplus x\) for all \(i\) (where \(\oplus\) denotes the bitwise XOR operation). Marin is then given the values of \(l,r\) and the final array \(a\). She needs to find the secret integer \(x\) to win. Can you help her?Note that there may be multiple possible \(x\) that Gojou could have chosen. Marin can find any possible \(x\) that could have resulted in the final value of \(a\).
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^5\)) β€” the number of test cases.In the first line of each test case contains two integers \(l\) and \(r\) (\( \color{red}{\boldsymbol{0} \boldsymbol{=} \boldsymbol{l}} \le r < 2^{17}\)).The second line contains \(r - l + 1\) integers of \(a_1,a_2,\ldots,a_{r-l+1}\) (\(0 \le a_i < 2^{17}\)). It is guaranteed that \(a\) can be generated using the steps performed by Gojou.It is guaranteed that the sum of \(r - l + 1\) over all test cases does not exceed \(2^{17}\).
For each test case print an integer \(x\). If there are multiple answers, print any.
In the first test case, the original array is \([3, 2, 1, 0]\). In the second test case, the original array is \([0, 3, 2, 1]\).In the third test case, the original array is \([2, 1, 0]\).
Input: 30 33 2 1 00 34 7 6 50 21 2 3 | Output: 0 4 3
Medium
2
929
533
84
16
34
C
34C
C. Page Numbers
1,300
expression parsing; implementation; sortings; strings
Β«BersoftΒ» company is working on a new version of its most popular text editor β€” Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces).Your task is to write a part of the program, responsible for Β«standardizationΒ» of this sequence. Your program gets the sequence, keyed by the user, as input. The program should output this sequence in format l1-r1,l2-r2,...,lk-rk, where ri + 1 < li + 1 for all i from 1 to k - 1, and li ≀ ri. The new sequence should contain all the page numbers, keyed by the user, and nothing else. If some page number appears in the input sequence several times, its appearances, starting from the second one, should be ignored. If for some element i from the new sequence li = ri, this element should be output as li, and not as Β«li - liΒ».For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6.
The only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer numbers. It's guaranteed, that this sequence consists of positive integer numbers, not exceeding 1000, separated with a comma, doesn't contain any other characters, apart from digits and commas, can't end with a comma, and the numbers don't contain leading zeroes. Also it doesn't start with a comma or contain more than one comma in a row.
Output the sequence in the required format.
Input: 1,2,3,1,1,2,6,6,2 | Output: 1-3,6
Easy
4
993
464
43
0
915
C
915C
C. Permute Digits
1,700
dp; greedy
You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.It is allowed to leave a as it is.
The first line contains integer a (1 ≀ a ≀ 1018). The second line contains integer b (1 ≀ b ≀ 1018). Numbers don't have leading zeroes. It is guaranteed that answer exists.
Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.
Input: 123222 | Output: 213
Medium
2
233
172
296
9
1,708
A
1708A
A. Difference Operations
800
greedy; math
You are given an array \(a\) consisting of \(n\) positive integers.You are allowed to perform this operation any number of times (possibly, zero): choose an index \(i\) (\(2 \le i \le n\)), and change \(a_i\) to \(a_i - a_{i-1}\). Is it possible to make \(a_i=0\) for all \(2\le i\le n\)?
The input consists of multiple test cases. The first line contains a single integer \(t\) (\(1\le t\le 100\)) β€” the number of test cases. The description of the test cases follows.The first line contains one integer \(n\) (\(2 \le n \le 100\)) β€” the length of array \(a\).The second line contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(1 \le a_i \le 10^9\)).
For each test case, print ""YES"" (without quotes), if it is possible to change \(a_i\) to \(0\) for all \(2 \le i \le n\), and ""NO"" (without quotes) otherwise.You can print letters in any case (upper or lower).
In the first test case, the initial array is \([5,10]\). You can perform \(2\) operations to reach the goal: Choose \(i=2\), and the array becomes \([5,5]\). Choose \(i=2\), and the array becomes \([5,0]\). In the second test case, the initial array is \([1,2,3]\). You can perform \(4\) operations to reach the goal: Choose \(i=3\), and the array becomes \([1,2,1]\). Choose \(i=2\), and the array becomes \([1,1,1]\). Choose \(i=3\), and the array becomes \([1,1,0]\). Choose \(i=2\), and the array becomes \([1,0,0]\). In the third test case, you can choose indices in the order \(4\), \(3\), \(2\).
Input: 425 1031 2 341 1 1 199 9 8 2 4 4 3 5 3 | Output: YES YES YES NO
Beginner
2
288
360
213
17
1,965
C
1965C
C. Folding Strip
2,300
constructive algorithms; greedy; strings
You have a strip of paper with a binary string \(s\) of length \(n\). You can fold the paper in between any pair of adjacent digits.A set of folds is considered valid if after the folds, all characters that are on top of or below each other match. Note that all folds are made at the same time, so the characters don't have to match in between folds.For example, these are valid foldings of \(s = \mathtt{110110110011}\) and \(s = \mathtt{01110}\): The length of the folded strip is the length seen from above after all folds are made. So for the two above examples, after the folds shown above, the lengths would be \(7\) and \(3\), respectively.Notice that for the above folding of \(s = \mathtt{01110}\), if we made either of the two folds on their own, that would not be a valid folding. However, because we don't check for validity until all folds are made, this folding is valid.After performing a set of valid folds, what is the minimum length strip you can form?
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” 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 \le 2\cdot 10^5\)) β€” the size of the strip.The second line of each test case contains a string \(s\) of \(n\) characters '0' and '1' β€” a description of the digits on the strip.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot 10^5\).
For each test case, output a single integer β€” the minimum possible length of the strip after a valid folding.
For the first example case, one optimal folding is to fold the strip in the middle, which produces a strip of length 3.The third and fourth example cases correspond to the images above. Note that the folding shown above for \(s = \mathtt{110110110011}\) is not of minimal length.
Input: 66101101101211011011001150111041111201 | Output: 3 1 3 3 1 2
Expert
3
970
496
109
19
271
A
271A
A. Beautiful Year
800
brute force
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
The single line contains integer y (1000 ≀ y ≀ 9000) β€” the year number.
Print a single integer β€” the minimum year number that is strictly larger than y and all it's digits are distinct. It is guaranteed that the answer exists.
Input: 1987 | Output: 2013
Beginner
1
337
71
154
2
219
E
219E
E. Parking Lot
2,200
data structures
A parking lot in the City consists of n parking spaces, standing in a line. The parking spaces are numbered from 1 to n from left to right. When a car arrives at the lot, the operator determines an empty parking space for it. For the safety's sake the chosen place should be located as far from the already occupied places as possible. That is, the closest occupied parking space must be as far away as possible. If there are several such places, then the operator chooses the place with the minimum index from them. If all parking lot places are empty, then the car gets place number 1.We consider the distance between the i-th and the j-th parking spaces equal to 4Β·|i - j| meters.You are given the parking lot records of arriving and departing cars in the chronological order. For each record of an arriving car print the number of the parking lot that was given to this car.
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of parking places and the number of records correspondingly. Next m lines contain the descriptions of the records, one per line. The i-th line contains numbers ti, idi (1 ≀ ti ≀ 2; 1 ≀ idi ≀ 106). If ti equals 1, then the corresponding record says that the car number idi arrived at the parking lot. If ti equals 2, then the corresponding record says that the car number idi departed from the parking lot. Records about arriving to the parking lot and departing from the parking lot are given chronologically. All events occurred consecutively, no two events occurred simultaneously.It is guaranteed that all entries are correct: each car arrived at the parking lot at most once and departed from the parking lot at most once, there is no record of a departing car if it didn't arrive at the parking lot earlier, there are no more than n cars on the parking lot at any moment. You can consider the cars arbitrarily numbered from 1 to 106, all numbers are distinct. Initially all places in the parking lot are empty.
For each entry of an arriving car print the number of its parking space. Print the numbers of the spaces in the order, in which the cars arrive to the parking lot.
Input: 7 111 151 1231231 31 52 1231232 151 212 31 61 71 8 | Output: 17427413
Hard
1
878
1,108
163
2
1,109
F
1109F
F. Sasha and Algorithm of Silence's Sounds
3,200
data structures; trees
One fine day Sasha went to the park for a walk. In the park, he saw that his favorite bench is occupied, and he had to sit down on the neighboring one. He sat down and began to listen to the silence. Suddenly, he got a question: what if in different parts of the park, the silence sounds in different ways? So it was. Let's divide the park into \(1 \times 1\) meter squares and call them cells, and numerate rows from \(1\) to \(n\) from up to down, and columns from \(1\) to \(m\) from left to right. And now, every cell can be described with a pair of two integers \((x, y)\), where \(x\) β€” the number of the row, and \(y\) β€” the number of the column. Sasha knows that the level of silence in the cell \((i, j)\) equals to \(f_{i,j}\), and all \(f_{i,j}\) form a permutation of numbers from \(1\) to \(n \cdot m\). Sasha decided to count, how many are there pleasant segments of silence?Let's take some segment \([l \ldots r]\). Denote \(S\) as the set of cells \((i, j)\) that \(l \le f_{i,j} \le r\). Then, the segment of silence \([l \ldots r]\) is pleasant if there is only one simple path between every pair of cells from \(S\) (path can't contain cells, which are not in \(S\)). In other words, set \(S\) should look like a tree on a plain. Sasha has done this task pretty quickly, and called the algorithm β€” ""algorithm of silence's sounds"".Time passed, and the only thing left from the algorithm is a legend. To prove the truthfulness of this story, you have to help Sasha and to find the number of different pleasant segments of silence. Two segments \([l_1 \ldots r_1]\), \([l_2 \ldots r_2]\) are different, if \(l_1 \neq l_2\) or \(r_1 \neq r_2\) or both at the same time.
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 1000\), \(1 \le n \cdot m \le 2 \cdot 10^5\)) β€” the size of the park.Each from next \(n\) lines contains \(m\) integers \(f_{i,j}\) (\(1 \le f_{i,j} \le n \cdot m\)) β€” the level of silence in the cell with number \((i, j)\).It is guaranteed, that all \(f_{i,j}\) are different.
Print one integer β€” the number of pleasant segments of silence.
In the first example, all segments of silence are pleasant.In the second example, pleasant segments of silence are the following:
Input: 1 51 2 3 4 5 | Output: 15
Master
2
1,686
348
63
11
1,184
B3
1184B3
B3. The Doctor Meets Vader (Hard)
2,700
flows; shortest paths
The rebels have saved enough gold to launch a full-scale attack. Now the situation is flipped, the rebels will send out the spaceships to attack the Empire bases!The galaxy can be represented as an undirected graph with \(n\) planets (nodes) and \(m\) wormholes (edges), each connecting two planets.A total of \(s\) rebel spaceships and \(b\) empire bases are located at different planets in the galaxy.Each spaceship is given a location \(x\), denoting the index of the planet on which it is located, an attacking strength \(a\), a certain amount of fuel \(f\), and a price to operate \(p\).Each base is given a location \(x\), a defensive strength \(d\), and a certain amount of gold \(g\).A spaceship can attack a base if both of these conditions hold: the spaceship's attacking strength is greater or equal than the defensive strength of the base the spaceship's fuel is greater or equal to the shortest distance, computed as the number of wormholes, between the spaceship's node and the base's node The rebels are very proud fighters. So, if a spaceship cannot attack any base, no rebel pilot will accept to operate it.If a spaceship is operated, the profit generated by that spaceship is equal to the gold of the base it attacks minus the price to operate the spaceship. Note that this might be negative. A spaceship that is operated will attack the base that maximizes its profit.Darth Vader likes to appear rich at all times. Therefore, whenever a base is attacked and its gold stolen, he makes sure to immediately refill that base with gold.Therefore, for the purposes of the rebels, multiple spaceships can attack the same base, in which case each spaceship will still receive all the gold of that base.The rebels have tasked Heidi and the Doctor to decide which set of spaceships to operate in order to maximize the total profit.However, as the war has been going on for a long time, the pilots have formed unbreakable bonds, and some of them refuse to operate spaceships if their friends are not also operating spaceships.They have a list of \(k\) dependencies of the form \(s_1, s_2\), denoting that spaceship \(s_1\) can be operated only if spaceship \(s_2\) is also operated.
The first line of input contains integers \(n\) and \(m\) (\(1 \leq n \leq 100\), \(0 \leq m \leq 10000\)), the number of nodes and the number of edges, respectively.The next \(m\) lines contain integers \(u\) and \(v\) (\(1 \leq u, v \leq n\)) denoting an undirected edge between the two nodes.The next line contains integers \(s\), \(b\) and \(k\) (\(1 \leq s, b \leq 10^5\), \(0 \leq k \leq 1000\)), the number of spaceships, bases, and dependencies, respectively.The next \(s\) lines contain integers \(x, a, f, p\) (\(1 \leq x \leq n\), \(0 \leq a, f, p \leq 10^9\)), denoting the location, attack, fuel, and price of the spaceship. Ships are numbered from \(1\) to \(s\).The next \(b\) lines contain integers \(x, d, g\) (\(1 \leq x \leq n\), \(0 \leq d, g \leq 10^9\)), denoting the location, defence, and gold of the base.The next \(k\) lines contain integers \(s_1\) and \(s_2\) (\(1 \leq s_1, s_2 \leq s\)), denoting a dependency of \(s_1\) on \(s_2\).
Print a single integer, the maximum total profit that can be achieved.
The optimal strategy is to operate spaceships 1, 2, and 4, which will attack bases 1, 1, and 2, respectively.
Input: 6 7 1 2 2 3 3 4 4 6 6 5 4 4 3 6 4 2 2 1 10 2 5 3 8 2 7 5 1 0 2 6 5 4 1 3 7 6 5 2 3 4 2 3 2 | Output: 2
Master
2
2,190
962
70
11
1,536
D
1536D
D. Omkar and Medians
2,000
data structures; greedy; implementation
Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array \(a\) with elements \(a_1, a_2, \ldots, a_{2k-1}\), is the array \(b\) with elements \(b_1, b_2, \ldots, b_{k}\) such that \(b_i\) is equal to the median of \(a_1, a_2, \ldots, a_{2i-1}\) for all \(i\). Omkar has found an array \(b\) of size \(n\) (\(1 \leq n \leq 2 \cdot 10^5\), \(-10^9 \leq b_i \leq 10^9\)). Given this array \(b\), Ray wants to test Omkar's claim and see if \(b\) actually is an OmkArray of some array \(a\). Can you help Ray?The median of a set of numbers \(a_1, a_2, \ldots, a_{2i-1}\) is the number \(c_{i}\) where \(c_{1}, c_{2}, \ldots, c_{2i-1}\) represents \(a_1, a_2, \ldots, a_{2i-1}\) sorted in nondecreasing order.
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases. Description of the test cases follows.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)) β€” the length of the array \(b\).The second line contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(-10^9 \leq b_i \leq 10^9\)) β€” the elements of \(b\).It is guaranteed the sum of \(n\) across all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output one line containing YES if there exists an array \(a\) such that \(b_i\) is the median of \(a_1, a_2, \dots, a_{2i-1}\) for all \(i\), and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).
In the second case of the first sample, the array \([4]\) will generate an OmkArray of \([4]\), as the median of the first element is \(4\).In the fourth case of the first sample, the array \([3, 2, 5]\) will generate an OmkArray of \([3, 3]\), as the median of \(3\) is \(3\) and the median of \(2, 3, 5\) is \(3\).In the fifth case of the first sample, the array \([2, 1, 0, 3, 4, 4, 3]\) will generate an OmkArray of \([2, 1, 2, 3]\) as the median of \(2\) is \(2\) the median of \(0, 1, 2\) is \(1\) the median of \(0, 1, 2, 3, 4\) is \(2\) and the median of \(0, 1, 2, 3, 3, 4, 4\) is \(3\). In the second case of the second sample, the array \([1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]\) will generate an OmkArray of \([1, 1, 3, 1, 0, -2, -1]\), as the median of \(1\) is \(1\) the median of \(0, 1, 4\) is \(1\) the median of \(0, 1, 3, 4, 5\) is \(3\) the median of \(-2, -2, 0, 1, 3, 4, 5\) is \(1\) the median of \(-4, -2, -2, -2, 0, 1, 3, 4, 5\) is \(0\) the median of \(-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5\) is \(-2\) and the median of \(-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5\) is \(-1\) For all cases where the answer is NO, it can be proven that it is impossible to find an array \(a\) such that \(b\) is the OmkArray of \(a\).
Input: 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 | Output: NO YES NO YES YES
Hard
3
805
512
266
15
767
E
767E
E. Change-free
2,400
greedy
Student Arseny likes to plan his life for n days ahead. He visits a canteen every day and he has already decided what he will order in each of the following n days. Prices in the canteen do not change and that means Arseny will spend ci rubles during the i-th day.There are 1-ruble coins and 100-ruble notes in circulation. At this moment, Arseny has m coins and a sufficiently large amount of notes (you can assume that he has an infinite amount of them). Arseny loves modern technologies, so he uses his credit card everywhere except the canteen, but he has to pay in cash in the canteen because it does not accept cards.Cashier always asks the student to pay change-free. However, it's not always possible, but Arseny tries to minimize the dissatisfaction of the cashier. Cashier's dissatisfaction for each of the days is determined by the total amount of notes and coins in the change. To be precise, if the cashier gives Arseny x notes and coins on the i-th day, his dissatisfaction for this day equals xΒ·wi. Cashier always gives change using as little coins and notes as possible, he always has enough of them to be able to do this. ""Caution! Angry cashier"" Arseny wants to pay in such a way that the total dissatisfaction of the cashier for n days would be as small as possible. Help him to find out how he needs to pay in each of the n days!Note that Arseny always has enough money to pay, because he has an infinite amount of notes. Arseny can use notes and coins he received in change during any of the following days.
The first line contains two integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ 109) β€” the amount of days Arseny planned his actions for and the amount of coins he currently has. The second line contains a sequence of integers c1, c2, ..., cn (1 ≀ ci ≀ 105) β€” the amounts of money in rubles which Arseny is going to spend for each of the following days. The third line contains a sequence of integers w1, w2, ..., wn (1 ≀ wi ≀ 105) β€” the cashier's dissatisfaction coefficients for each of the following days.
In the first line print one integer β€” minimum possible total dissatisfaction of the cashier.Then print n lines, the i-th of then should contain two numbers β€” the amount of notes and the amount of coins which Arseny should use to pay in the canteen on the i-th day.Of course, the total amount of money Arseny gives to the casher in any of the days should be no less than the amount of money he has planned to spend. It also shouldn't exceed 106 rubles: Arseny never carries large sums of money with him.If there are multiple answers, print any of them.
Input: 5 42117 71 150 243 2001 1 1 1 1 | Output: 791 171 02 02 432 0
Expert
1
1,530
495
551
7
1,862
E
1862E
E. Kolya and Movie Theatre
1,600
constructive algorithms; data structures; greedy
Recently, Kolya found out that a new movie theatre is going to be opened in his city soon, which will show a new movie every day for \(n\) days. So, on the day with the number \(1 \le i \le n\), the movie theatre will show the premiere of the \(i\)-th movie. Also, Kolya found out the schedule of the movies and assigned the entertainment value to each movie, denoted by \(a_i\).However, the longer Kolya stays without visiting a movie theatre, the larger the decrease in entertainment value of the next movie. That decrease is equivalent to \(d \cdot cnt\), where \(d\) is a predetermined value and \(cnt\) is the number of days since the last visit to the movie theatre. It is also known that Kolya managed to visit another movie theatre a day before the new one opened β€” the day with the number \(0\). So if we visit the movie theatre the first time on the day with the number \(i\), then \(cnt\) β€” the number of days since the last visit to the movie theatre will be equal to \(i\).For example, if \(d = 2\) and \(a = [3, 2, 5, 4, 6]\), then by visiting movies with indices \(1\) and \(3\), \(cnt\) value for the day \(1\) will be equal to \(1 - 0 = 1\) and \(cnt\) value for the day \(3\) will be \(3 - 1 = 2\), so the total entertainment value of the movies will be \(a_1 - d \cdot 1 + a_3 - d \cdot 2 = 3 - 2 \cdot 1 + 5 - 2 \cdot 2 = 2\).Unfortunately, Kolya only has time to visit at most \(m\) movies. Help him create a plan to visit the cinema in such a way that the total entertainment value of all the movies he visits is maximized.
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. The description of the test cases follows.The first line of each test case contains three integers \(n\), \(m\), and \(d\) (\(1 \le n \le 2 \cdot 10^5\), \(1 \le m \le n\), \(1 \le d \le 10^9\)).The second line of each set of input data contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^9 \le a_i \le 10^9\)) β€” the entertainment values of the movies.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single integer β€” the maximum total entertainment value that Kolya can get.
The first test case is explained in the problem statement.In the second test case, it is optimal not to visit any movies.In the third test case, it is optimal to visit movies with numbers \(2\), \(3\), \(5\), \(6\), so the total entertainment value of the visited movies will be \(45 - 6 \cdot 2 + 1 - 6 \cdot 1 + 39 - 6 \cdot 2 + 11 - 6 \cdot 1 = 60\).
Input: 65 2 23 2 5 4 64 3 21 1 1 16 6 6-82 45 1 -77 39 115 2 23 2 5 4 82 1 1-1 26 3 2-8 8 -2 -1 9 0 | Output: 2 0 60 3 0 7
Medium
3
1,545
590
103
18
757
B
757B
B. Bash's Big Day
1,400
greedy; math; number theory
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
The input consists of two lines.The first line contains an integer n (1 ≀ n ≀ 105), the number of Pokemon in the lab.The next line contains n space separated integers, where the i-th of them denotes si (1 ≀ si ≀ 105), the strength of the i-th Pokemon.
Print single integer β€” the maximum number of Pokemons Bash can take.
gcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd β‰  1.
Input: 32 3 4 | Output: 2
Easy
3
688
251
68
7
1,019
B
1019B
B. The hat
2,000
binary search; interactive
This is an interactive problem.Imur Ishakov decided to organize a club for people who love to play the famous game Β«The hatΒ». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≀ i ≀ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.You can ask questions of form Β«which number was received by student i?Β», and the goal is to determine whether the desired pair exists in no more than 60 questions.
At the beginning the even integer n (2 ≀ n ≀ 100 000) is given β€” the total number of students.You are allowed to ask no more than 60 questions.
To ask the question about the student i (1 ≀ i ≀ n), you should print Β«? iΒ». Then from standard output you can read the number ai received by student i ( - 109 ≀ ai ≀ 109).When you find the desired pair, you should print Β«! iΒ», where i is any student who belongs to the pair (1 ≀ i ≀ n). If you determined that such pair doesn't exist, you should output Β«! -1Β». In both cases you should immediately terminate the program.The query that contains your answer is not counted towards the limit of 60 queries.Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language.HackingUse the following format for hacking:In the first line, print one even integer n (2 ≀ n ≀ 100 000) β€” the total number of students.In the second line print n integers ai ( - 109 ≀ ai ≀ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1.The hacked solution will not have direct access to the sequence ai.
Input-output in statements illustrates example interaction.In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2In the second sample the selection sequence is 1, 2, 3, 2, 1, 0.
Input: 822 | Output: ? 4? 8! 4
Hard
2
1,177
143
1,121
10
1,271
D
1271D
D. Portals
2,100
data structures; dp; greedy; implementation; sortings
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer \(n\) castles of your opponent.Let's describe the game process in detail. Initially you control an army of \(k\) warriors. Your enemy controls \(n\) castles; to conquer the \(i\)-th castle, you need at least \(a_i\) warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β€” formally, after you capture the \(i\)-th castle, \(b_i\) warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter \(c_i\), and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle: if you are currently in the castle \(i\), you may leave one warrior to defend castle \(i\); there are \(m\) one-way portals connecting the castles. Each portal is characterised by two numbers of castles \(u\) and \(v\) (for each portal holds \(u > v\)). A portal can be used as follows: if you are currently in the castle \(u\), you may send one warrior to defend castle \(v\). Obviously, when you order your warrior to defend some castle, he leaves your army.You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle \(i\) (but only before capturing castle \(i + 1\)) you may recruit new warriors from castle \(i\), leave a warrior to defend castle \(i\), and use any number of portals leading from castle \(i\) to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle \(i\) won't be available to you.If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β€” your score will be calculated afterwards).Can you determine an optimal strategy of capturing and defending the castles?
The first line contains three integers \(n\), \(m\) and \(k\) (\(1 \le n \le 5000\), \(0 \le m \le \min(\frac{n(n - 1)}{2}, 3 \cdot 10^5)\), \(0 \le k \le 5000\)) β€” the number of castles, the number of portals and initial size of your army, respectively.Then \(n\) lines follow. The \(i\)-th line describes the \(i\)-th castle with three integers \(a_i\), \(b_i\) and \(c_i\) (\(0 \le a_i, b_i, c_i \le 5000\)) β€” the number of warriors required to capture the \(i\)-th castle, the number of warriors available for hire in this castle and its importance value.Then \(m\) lines follow. The \(i\)-th line describes the \(i\)-th portal with two integers \(u_i\) and \(v_i\) (\(1 \le v_i < u_i \le n\)), meaning that the portal leads from the castle \(u_i\) to the castle \(v_i\). There are no two same portals listed.It is guaranteed that the size of your army won't exceed \(5000\) under any circumstances (i. e. \(k + \sum\limits_{i = 1}^{n} b_i \le 5000\)).
If it's impossible to capture all the castles, print one integer \(-1\).Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
The best course of action in the first example is as follows: capture the first castle; hire warriors from the first castle, your army has \(11\) warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has \(13\) warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has \(12\) warriors now. This course of action (and several other ones) gives \(5\) as your total score.The best course of action in the second example is as follows: capture the first castle; hire warriors from the first castle, your army has \(11\) warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has \(13\) warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has \(12\) warriors now; send one warrior to protect the first castle through the third portal, your army has \(11\) warriors now. This course of action (and several other ones) gives \(22\) as your total score.In the third example it's impossible to capture the last castle: you need \(14\) warriors to do so, but you can accumulate no more than \(13\) without capturing it.
Input: 4 3 7 7 4 17 3 0 8 11 2 0 13 3 5 3 1 2 1 4 3 | Output: 5
Hard
5
2,346
956
167
12
1,487
E
1487E
E. Cheap Dinner
2,000
brute force; data structures; graphs; greedy; implementation; sortings; two pointers
Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.There are \(n_1\) different types of first courses Ivan can buy (the \(i\)-th of them costs \(a_i\) coins), \(n_2\) different types of second courses (the \(i\)-th of them costs \(b_i\) coins), \(n_3\) different types of drinks (the \(i\)-th of them costs \(c_i\) coins) and \(n_4\) different types of desserts (the \(i\)-th of them costs \(d_i\) coins).Some dishes don't go well with each other. There are \(m_1\) pairs of first courses and second courses that don't go well with each other, \(m_2\) pairs of second courses and drinks, and \(m_3\) pairs of drinks and desserts that don't go well with each other.Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!
The first line contains four integers \(n_1\), \(n_2\), \(n_3\) and \(n_4\) (\(1 \le n_i \le 150000\)) β€” the number of types of first courses, second courses, drinks and desserts, respectively.Then four lines follow. The first line contains \(n_1\) integers \(a_1, a_2, \dots, a_{n_1}\) (\(1 \le a_i \le 10^8\)), where \(a_i\) is the cost of the \(i\)-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way (\(1 \le b_i, c_i, d_i \le 10^8\)).The next line contains one integer \(m_1\) (\(0 \le m_1 \le 200000\)) β€” the number of pairs of first and second courses that don't go well with each other. Each of the next \(m_1\) lines contains two integers \(x_i\) and \(y_i\) (\(1 \le x_i \le n_1\); \(1 \le y_i \le n_2\)) denoting that the first course number \(x_i\) doesn't go well with the second course number \(y_i\). All these pairs are different.The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other (\(0 \le m_2, m_3 \le 200000\)).
If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print \(-1\). Otherwise, print one integer β€” the minimum total cost of the dinner.
The best option in the first example is to take the first course \(2\), the second course \(1\), the drink \(2\) and the dessert \(1\).In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.
Input: 4 3 2 1 1 2 3 4 5 6 7 8 9 10 2 1 2 1 1 2 3 1 3 2 1 1 1 | Output: 26
Hard
7
965
1,129
205
14
2,112
B
2112B
B. Shrinking Array
1,100
brute force; greedy
Let's call an array \(b\) beautiful if it consists of at least two elements and there exists a position \(i\) such that \(|b_i - b_{i + 1}| \le 1\) (where \(|x|\) is the absolute value of \(x\)).You are given an array \(a\), and as long as it consists of at least two elements, you can perform the following operation: Choose two adjacent positions \(i\) and \(i + 1\) in the array \(a\). Choose an integer \(x\) such that \(\min(a_i, a_{i + 1}) \le x \le \max(a_i, a_{i + 1})\). Remove the numbers \(a_i\) and \(a_{i + 1}\) from the array, and insert the number \(x\) in their place. Obviously, the size of the array will decrease by \(1\). Calculate the minimum number of operations required to make the array beautiful, or report that it is impossible.
The first line contains one integer \(t\) (\(1 \le t \le 200\)) β€” the number of test cases.The first line of each test case contains one integer \(n\) (\(2 \le n \le 1000\)) β€” the size of the array \(a\).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^6\)) β€” the array \(a\) itself.
For each test case, output one integer β€” the minimum number of operations needed to make the array \(a\) beautiful, or \(-1\) if it is impossible to make it beautiful.
In the first test case, the given array is already beautiful, as \(|a_2 - a_3| = |3 - 3| = 0\).In the second test case, it is impossible to make the array beautiful, as applying the operation would reduce its size to less than two.In the third test case, you can, for example, choose \(a_1\) and \(a_2\) and replace them with the number \(2\). The resulting array \([2, 3, 7]\) is beautiful.In the fourth test case, you can, for example, choose \(a_2\) and \(a_3\) and replace them with the number \(3\). The resulting array \([1, 3, 2]\) is beautiful.
Input: 441 3 3 726 943 1 3 741 3 5 2 | Output: 0 -1 1 1
Easy
2
755
319
167
21
1,632
D
1632D
D. New Year Concert
2,000
binary search; data structures; greedy; math; number theory; two pointers
New Year is just around the corner, which means that in School 179, preparations for the concert are in full swing.There are \(n\) classes in the school, numbered from \(1\) to \(n\), the \(i\)-th class has prepared a scene of length \(a_i\) minutes.As the main one responsible for holding the concert, Idnar knows that if a concert has \(k\) scenes of lengths \(b_1\), \(b_2\), \(\ldots\), \(b_k\) minutes, then the audience will get bored if there exist two integers \(l\) and \(r\) such that \(1 \le l \le r \le k\) and \(\gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r) = r - l + 1\), where \(\gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r)\) is equal to the greatest common divisor (GCD) of the numbers \(b_l\), \(b_{l + 1}\), \(\ldots\), \(b_{r - 1}\), \(b_r\).To avoid boring the audience, Idnar can ask any number of times (possibly zero) for the \(t\)-th class (\(1 \le t \le k\)) to make a new scene \(d\) minutes in length, where \(d\) can be any positive integer. Thus, after this operation, \(b_t\) is equal to \(d\). Note that \(t\) and \(d\) can be different for each operation.For a sequence of scene lengths \(b_1\), \(b_2\), \(\ldots\), \(b_{k}\), let \(f(b)\) be the minimum number of classes Idnar has to ask to change their scene if he wants to avoid boring the audience.Idnar hasn't decided which scenes will be allowed for the concert, so he wants to know the value of \(f\) for each non-empty prefix of \(a\). In other words, Idnar wants to know the values of \(f(a_1)\), \(f(a_1\),\(a_2)\), \(\ldots\), \(f(a_1\),\(a_2\),\(\ldots\),\(a_n)\).
The first line contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the number of classes in the school.The second line contains \(n\) positive integers \(a_1\), \(a_2\), \(\ldots\), \(a_n\) (\(1 \le a_i \le 10^9\)) β€” the lengths of the class scenes.
Print a sequence of \(n\) integers in a single line β€” \(f(a_1)\), \(f(a_1\),\(a_2)\), \(\ldots\), \(f(a_1\),\(a_2\),\(\ldots\),\(a_n)\).
In the first test we can change \(1\) to \(2\), so the answer is \(1\).In the second test: \([1]\) can be changed into \([2]\), \([1, 4]\) can be changed into \([3, 4]\), \([1, 4, 2]\) can be changed into \([2, 3, 2]\).
Input: 1 1 | Output: 1
Hard
6
1,559
262
136
16
1,186
C
1186C
C. Vus the Cossack and Strings
1,800
implementation; math
Vus the Cossack has two binary strings, that is, strings that consist only of ""0"" and ""1"". We call these strings \(a\) and \(b\). It is known that \(|b| \leq |a|\), that is, the length of \(b\) is at most the length of \(a\).The Cossack considers every substring of length \(|b|\) in string \(a\). Let's call this substring \(c\). He matches the corresponding characters in \(b\) and \(c\), after which he counts the number of positions where the two strings are different. We call this function \(f(b, c)\).For example, let \(b = 00110\), and \(c = 11000\). In these strings, the first, second, third and fourth positions are different.Vus the Cossack counts the number of such substrings \(c\) such that \(f(b, c)\) is even.For example, let \(a = 01100010\) and \(b = 00110\). \(a\) has four substrings of the length \(|b|\): \(01100\), \(11000\), \(10001\), \(00010\). \(f(00110, 01100) = 2\); \(f(00110, 11000) = 4\); \(f(00110, 10001) = 4\); \(f(00110, 00010) = 1\). Since in three substrings, \(f(b, c)\) is even, the answer is \(3\).Vus can not find the answer for big strings. That is why he is asking you to help him.
The first line contains a binary string \(a\) (\(1 \leq |a| \leq 10^6\)) β€” the first string.The second line contains a binary string \(b\) (\(1 \leq |b| \leq |a|\)) β€” the second string.
Print one number β€” the answer.
The first example is explained in the legend.In the second example, there are five substrings that satisfy us: \(1010\), \(0101\), \(1111\), \(1111\).
Input: 01100010 00110 | Output: 3
Medium
2
1,130
185
30
11
2,127
A
2127A
A. Mix Mex Max
800
constructive algorithms; greedy; math
You are given an array \(a\) consisting of \(n\) non-negative integers. However, some elements of \(a\) are missing, and they are represented by \(βˆ’1\).We define that the array \(a\) is good if and only if the following holds for every \(1 \leq i \leq n-2\):$$$\( \operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) = \max([a_i, a_{i+1}, a_{i+2}]) - \min([a_i, a_{i+1}, a_{i+2}]), \)\(where \)\operatorname{mex}(b)\( denotes the minimum excluded (MEX)\)^{\text{βˆ—}}\( of the integers in \)b\(. You have to determine whether you can make \)a\( good after replacing each \)-1\( in \)a\( with a non-negative integer.\)^{\text{βˆ—}}\(The minimum excluded (MEX) of a collection of integers \)b_1, b_2, \ldots, b_k\( is defined as the smallest non-negative integer \)x\( which does not occur in the collection \)b\(. For example, \)\operatorname{mex}([2,2,1])=0\( because \)0\( does not belong to the array, and \)\operatorname{mex}([0,3,1,2])=4\( because \)0\(, \)1\(, \)2\(, and \)3\( appear in the array, but \)4$$$ does not.
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 a single integer \(n\) (\(3 \leq n \leq 100\)) β€” the length of \(a\).The second line contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(-1 \leq a_i \leq 100\)) β€” the elements of \(a\). \(a_i = -1\) denotes that this element is missing.
For each test case, output ""YES"" if it is possible to make \(a\) good, and ""NO"" otherwise.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In the first test case, we can put \( a_1 = a_2 = a_3 = 1 \). Then, \(\operatorname{mex}([a_1, a_2, a_3]) = \operatorname{mex}([1, 1, 1]) = 0\); \(\max([a_1, a_2, a_3]) = \max([1, 1, 1]) = 1\); \(\min([a_1, a_2, a_3]) = \min([1, 1, 1]) = 1\). And \(0 = 1 - 1\). Thus, the array \(a\) is good.In the second test case, none of the elements in \(a\) is missing. And we have \(\operatorname{mex}([a_1, a_2, a_3]) = \max([a_1, a_2, a_3]) - \min([a_1, a_2, a_3])\), \(\operatorname{mex}([a_2, a_3, a_4]) = \max([a_2, a_3, a_4]) - \min([a_2, a_3, a_4])\), but \(\operatorname{mex}([a_3, a_4, a_5]) \ne \max([a_3, a_4, a_5]) - \min([a_3, a_4, a_5])\). Thus, the array \(a\) cannot be good.In the third test case, none of \(a_1\), \(a_2\), or \(a_3\) is missing. However, \(\operatorname{mex}([a_1, a_2, a_3]) = \operatorname{mex}([5, 5, 1]) = 0\); \(\max([a_1, a_2, a_3]) = \max([5, 5, 1]) = 5\); \(\min([a_1, a_2, a_3]) = \min([5, 5, 1]) = 1\). And \(0\ne 5 - 1\). So the array \(a\) cannot be good, no matter how you replace the missing elements.
Input: 83-1 -1 -151 1 1 1 065 5 1 -1 -1 14-1 -1 0 -14-1 1 1 -133 3 -150 0 0 0 073 0 1 4 -1 2 3 | Output: YES NO NO NO YES YES NO NO
Beginner
3
1,011
437
255
21
1,131
D
1131D
D. Gourmet choice
2,000
dfs and similar; dp; dsu; graphs; greedy
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review β€” in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named Β«PoissonΒ», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of \(n\) dishes on the first day and a set of \(m\) dishes on the second day. He made a table \(a\) of size \(n \times m\), in which he described his impressions. If, according to the expert, dish \(i\) from the first set was better than dish \(j\) from the second set, then \(a_{ij}\) is equal to "">"", in the opposite case \(a_{ij}\) is equal to ""<"". Dishes also may be equally good, in this case \(a_{ij}\) is ""="".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if \(a_{ij}\) is ""<"", then the number assigned to dish \(i\) from the first set should be less than the number of dish \(j\) from the second set, if \(a_{ij}\) is "">"", then it should be greater, and finally if \(a_{ij}\) is ""="", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
The first line contains integers \(n\) and \(m\) (\(1 \leq n, m \leq 1000\)) β€” the number of dishes in both days.Each of the next \(n\) lines contains a string of \(m\) symbols. The \(j\)-th symbol on \(i\)-th line is \(a_{ij}\). All strings consist only of ""<"", "">"" and ""="".
The first line of output should contain ""Yes"", if it's possible to do a correct evaluation for all the dishes, or ""No"" otherwise.If case an answer exist, on the second line print \(n\) integers β€” evaluations of dishes from the first set, and on the third line print \(m\) integers β€” evaluations of dishes from the second set.
In the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be \(2\), for all dishes of the first day.In the third sample, the table is contradictory β€” there is no possible evaluation of the dishes that satisfies it.
Input: 3 4 >>>> >>>> >>>> | Output: Yes 2 2 2 1 1 1 1
Hard
5
2,052
281
329
11
2,029
F
2029F
F. Palindrome Everywhere
2,500
constructive algorithms; graphs; greedy
You are given a cycle with \(n\) vertices numbered from \(0\) to \(n-1\). For each \(0\le i\le n-1\), there is an undirected edge between vertex \(i\) and vertex \(((i+1)\bmod n)\) with the color \(c_i\) (\(c_i=\texttt{R}\) or \(\texttt{B}\)).Determine whether the following condition holds for every pair of vertices \((i,j)\) (\(0\le i<j\le n-1\)): There exists a palindrome route between vertex \(i\) and vertex \(j\). Note that the route may not be simple. Formally, there must exist a sequence \(p=[p_0,p_1,p_2,\ldots,p_m]\) such that: \(p_0=i\), \(p_m=j\); For each \(0\leq x\le m-1\), either \(p_{x+1}=(p_x+1)\bmod n\) or \(p_{x+1}=(p_{x}-1)\bmod n\); For each \(0\le x\le y\le m-1\) satisfying \(x+y=m-1\), the edge between \(p_x\) and \(p_{x+1}\) has the same color as the edge between \(p_y\) and \(p_{y+1}\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^5\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains an integer \(n\) (\(3\leq n\leq10^6\)) β€” the number of vertices in the cycle.The second line contains a string \(c\) of length \(n\) (\(c_i=\texttt{R}\) or \(\texttt{B}\)) β€” the color of each edge.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
For each test case, print ""YES"" (without quotes) if there is a palindrome route between any pair of nodes, and ""NO"" (without quotes) otherwise.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In the first test case, it is easy to show that there is a palindrome route between any two vertices.In the second test case, for any two vertices, there exists a palindrome route with only red edges.In the third test case, the cycle is as follows: \(0\color{red}{\overset{\texttt{R}}{\longleftrightarrow}}1\color{blue}{\overset{\texttt{B}}{\longleftrightarrow}}2\color{blue}{\overset{\texttt{B}}{\longleftrightarrow}}3\color{red}{\overset{\texttt{R}}{\longleftrightarrow}}4\color{blue}{\overset{\texttt{B}}{\longleftrightarrow}}0\). Take \((i,j)=(0,3)\) as an example, then \(0\color{red}{\overset{\texttt{R}}{\longrightarrow}}1\color{blue}{\overset{\texttt{B}}{\longrightarrow}}2\color{blue}{\overset{\texttt{B}}{\longrightarrow}}3\color{red}{\overset{\texttt{R}}{\longrightarrow}}4\color{blue}{\overset{\texttt{B}}{\longrightarrow}}0\color{blue}{\overset{\texttt{B}}{\longrightarrow}}4\color{red}{\overset{\texttt{R}}{\longrightarrow}}3\) is a palindrome route. Thus, the condition holds for \((i,j)=(0,3)\).In the fourth test case, when \((i,j)=(0,2)\), there does not exist a palindrome route.
Input: 75RRRRR5RRRRB5RBBRB6RBRBRB6RRBBRB5RBRBR12RRBRRBRRBRRB | Output: YES YES YES NO NO YES NO
Expert
3
819
511
308
20
1,697
E
1697E
E. Coloring
2,400
brute force; combinatorics; constructive algorithms; dp; geometry; graphs; greedy; implementation; math
You are given \(n\) points on the plane, the coordinates of the \(i\)-th point are \((x_i, y_i)\). No two points have the same coordinates.The distance between points \(i\) and \(j\) is defined as \(d(i,j) = |x_i - x_j| + |y_i - y_j|\).For each point, you have to choose a color, represented by an integer from \(1\) to \(n\). For every ordered triple of different points \((a,b,c)\), the following constraints should be met: if \(a\), \(b\) and \(c\) have the same color, then \(d(a,b) = d(a,c) = d(b,c)\); if \(a\) and \(b\) have the same color, and the color of \(c\) is different from the color of \(a\), then \(d(a,b) < d(a,c)\) and \(d(a,b) < d(b,c)\). Calculate the number of different ways to choose the colors that meet these constraints.
The first line contains one integer \(n\) (\(2 \le n \le 100\)) β€” the number of points.Then \(n\) lines follow. The \(i\)-th of them contains two integers \(x_i\) and \(y_i\) (\(0 \le x_i, y_i \le 10^8\)).No two points have the same coordinates (i. e. if \(i \ne j\), then either \(x_i \ne x_j\) or \(y_i \ne y_j\)).
Print one integer β€” the number of ways to choose the colors for the points. Since it can be large, print it modulo \(998244353\).
In the first test, the following ways to choose the colors are suitable: \([1, 1, 1]\); \([2, 2, 2]\); \([3, 3, 3]\); \([1, 2, 3]\); \([1, 3, 2]\); \([2, 1, 3]\); \([2, 3, 1]\); \([3, 1, 2]\); \([3, 2, 1]\).
Input: 3 1 0 3 0 2 1 | Output: 9
Expert
9
747
316
129
16