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,715
E
1715E
E. Long Way Home
2,400
data structures; divide and conquer; dp; geometry; graphs; greedy; shortest paths
Stanley lives in a country that consists of \(n\) cities (he lives in city \(1\)). There are bidirectional roads between some of the cities, and you know how long it takes to ride through each of them. Additionally, there is a flight between each pair of cities, the flight between cities \(u\) and \(v\) takes \((u - v)^2\) time.Stanley is quite afraid of flying because of watching ""Sully: Miracle on the Hudson"" recently, so he can take at most \(k\) flights. Stanley wants to know the minimum time of a journey to each of the \(n\) cities from the city \(1\).
In the first line of input there are three integers \(n\), \(m\), and \(k\) (\(2 \leq n \leq 10^{5}\), \(1 \leq m \leq 10^{5}\), \(1 \leq k \leq 20\)) β€” the number of cities, the number of roads, and the maximal number of flights Stanley can take.The following \(m\) lines describe the roads. Each contains three integers \(u\), \(v\), \(w\) (\(1 \leq u, v \leq n\), \(u \neq v\), \(1 \leq w \leq 10^{9}\)) β€” the cities the road connects and the time it takes to ride through. Note that some pairs of cities may be connected by more than one road.
Print \(n\) integers, \(i\)-th of which is equal to the minimum time of traveling to city \(i\).
In the first sample, it takes no time to get to city 1; to get to city 2 it is possible to use a flight between 1 and 2, which will take 1 unit of time; to city 3 you can get via a road from city 1, which will take 1 unit of time. In the second sample, it also takes no time to get to city 1. To get to city 2 Stanley should use a flight between 1 and 2, which will take 1 unit of time. To get to city 3 Stanley can ride between cities 1 and 2, which will take 3 units of time, and then use a flight between 2 and 3. To get to city 4 Stanley should use a flight between 1 and 2, then take a ride from 2 to 4, which will take 5 units of time.
Input: 3 1 2 1 3 1 | Output: 0 1 1
Expert
7
565
547
96
17
659
B
659B
B. Qualifying Contest
1,300
constructive algorithms; sortings
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
The first line of the input contains two integers n and m (2 ≀ n ≀ 100 000, 1 ≀ m ≀ 10 000, n β‰₯ 2m) β€” the number of participants of the qualifying contest and the number of regions in Berland.Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive).It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.
Print m lines. On the i-th line print the team of the i-th region β€” the surnames of the two team members in an arbitrary order, or a single character ""?"" (without the quotes) if you need to spend further qualifying contests in the region.
In the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: ""Petrov""-""Sidorov"", ""Ivanov""-""Sidorov"", ""Ivanov"" -""Petrov"", so it is impossible to determine a team uniquely.
Input: 5 2Ivanov 1 763Andreev 2 800Petrov 1 595Sidorov 1 790Semenov 2 503 | Output: Sidorov IvanovAndreev Semenov
Easy
2
1,379
740
240
6
1,714
B
1714B
B. Remove Prefix
800
data structures; greedy; implementation
Polycarp was presented with some sequence of integers \(a\) of length \(n\) (\(1 \le a_i \le n\)). A sequence can make Polycarp happy only if it consists of different numbers (i.e. distinct numbers).In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.In one move, he can: remove the first (leftmost) element of the sequence. For example, in one move, the sequence \([3, 1, 4, 3]\) will produce the sequence \([1, 4, 3]\), which consists of different numbers.Determine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence \(a\), after removing which all values in the sequence will be unique.
The first line of the input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.Each test case consists of two lines.The first line contains an integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the length of the given sequence \(a\).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le n\)) β€” elements of the given sequence \(a\).It is guaranteed that the sum of \(n\) values over all test cases does not exceed \(2 \cdot 10^5\).
For each test case print your answer on a separate line β€” the minimum number of elements that must be removed from the beginning of the sequence so that all remaining elements are different.
The following are the sequences that will remain after the removal of prefixes: \([1, 4, 3]\); \([1]\); \([1]\); \([6, 5, 4, 3, 2, 1]\); \([2, 1]\). It is easy to see that all the remaining sequences contain only distinct elements. In each test case, the shortest matching prefix was removed.
Input: 543 1 4 351 1 1 1 11166 5 4 3 2 171 2 1 7 1 2 1 | Output: 1 4 0 0 5
Beginner
3
774
485
190
17
1,500
E
1500E
E. Subset Trick
3,300
binary search; data structures
Vanya invented an interesting trick with a set of integers.Let an illusionist have a set of positive integers \(S\). He names a positive integer \(x\). Then an audience volunteer must choose some subset (possibly, empty) of \(S\) without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed \(x\). The sum of elements of an empty subset is considered to be \(0\).Vanya wants to prepare the trick for a public performance. He prepared some set of distinct positive integers \(S\). Vasya wants the trick to be successful. He calls a positive number \(x\) unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose.Vanya wants to count the number of unsuitable integers for the chosen set \(S\).Vanya plans to try different sets \(S\). He wants you to write a program that finds the number of unsuitable integers for the initial set \(S\), and after each change to the set \(S\). Vanya will make \(q\) changes to the set, and each change is one of the following two types: add a new integer \(a\) to the set \(S\), or remove some integer \(a\) from the set \(S\).
The first line contains two integers \(n\), \(q\) (\(1 \leq n, q \leq 200\,000\)) β€” the size of the initial set \(S\) and the number of changes.The next line contains \(n\) distinct integers \(s_1, s_2, \ldots, s_n\) (\(1 \leq s_i \leq 10^{13}\)) β€” the initial elements of \(S\).Each of the following \(q\) lines contain two integers \(t_i\), \(a_i\) (\(1 \leq t_i \leq 2\), \(1 \leq a_i \leq 10^{13}\)), describing a change: If \(t_i = 1\), then an integer \(a_i\) is added to the set \(S\). It is guaranteed that this integer is not present in \(S\) before this operation. If \(t_i = 2\), then an integer \(a_i\) is removed from the set \(S\). In is guaranteed that this integer is present in \(S\) before this operation.
Print \(q + 1\) lines.In the first line print the number of unsuitable integers for the initial set \(S\). In the next \(q\) lines print the number of unsuitable integers for \(S\) after each change.
In the first example the initial set is \(S = \{1, 2, 3\}\). For this set the trick can be unsuccessful for \(x \in \{1, 2, 3, 4\}\). For example, if \(x = 4\), the volunteer can choose the subset \(\{1, 2\}\) with sum \(3 \leq x\), and can choose the subset \(\{2, 3\}\) with sum \(5 > x\). However, in both cases the illusionist only know the same size of the subset (\(2\)), so he can't be sure answering making a guess. Since there is only one subset of size \(3\), and the sum of each subset of smaller size does not exceed \(5\), all \(x \ge 5\) are suitable.
Input: 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 | Output: 4 1 6 12 19 13 8 2 10 3 0 0
Master
2
1,258
723
199
15
813
A
813A
A. The Contest
1,100
implementation
Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment lj and ending moment rj. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that lx ≀ T ≀ rx.Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.
The first line contains one integer n (1 ≀ n ≀ 1000) β€” the number of problems. The second line contains n integers ai (1 ≀ ai ≀ 105) β€” the time Pasha needs to solve ith problem.The third line contains one integer m (0 ≀ m ≀ 1000) β€” the number of periods of time when the website is working. Next m lines represent these periods. jth line contains two numbers lj and rj (1 ≀ lj < rj ≀ 105) β€” the starting and the ending moment of jth period.It is guaranteed that the periods are not intersecting and are given in chronological order, so for every j > 1 the condition lj > rj - 1 is met.
If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted.Otherwise print ""-1"" (without brackets).
In the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.In the second example Pasha invents the solution only after the website stops working for the last time.In the third example Pasha sends the solution exactly at the end of the first period.
Input: 23 421 47 9 | Output: 7
Easy
1
1,218
585
202
8
1,778
B
1778B
B. The Forbidden Permutation
1,300
greedy; math
You are given a permutation \(p\) of length \(n\), an array of \(m\) distinct integers \(a_1, a_2, \ldots, a_m\) (\(1 \le a_i \le n\)), and an integer \(d\).Let \(\mathrm{pos}(x)\) be the index of \(x\) in the permutation \(p\). The array \(a\) is not good if \(\mathrm{pos}(a_{i}) < \mathrm{pos}(a_{i + 1}) \le \mathrm{pos}(a_{i}) + d\) for all \(1 \le i < m\). For example, with the permutation \(p = [4, 2, 1, 3, 6, 5]\) and \(d = 2\): \(a = [2, 3, 6]\) is a not good array. \(a = [2, 6, 5]\) is good because \(\mathrm{pos}(a_1) = 2\), \(\mathrm{pos}(a_2) = 5\), so the condition \(\mathrm{pos}(a_2) \le \mathrm{pos}(a_1) + d\) is not satisfied. \(a = [1, 6, 3]\) is good because \(\mathrm{pos}(a_2) = 5\), \(\mathrm{pos}(a_3) = 4\), so the condition \(\mathrm{pos}(a_2) < \mathrm{pos}(a_3)\) is not satisfied. In one move, you can swap two adjacent elements of the permutation \(p\). What is the minimum number of moves needed such that the array \(a\) becomes good? It can be shown that there always exists a sequence of moves so that the array \(a\) becomes good.A permutation is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array) and \([1,3,4]\) is also not a permutation (\(n=3\), but there is \(4\) in the array).
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 three integers \(n\), \(m\) and \(d\) (\(2\leq n \leq 10^5\), \(2\leq m\leq n\), \(1 \le d \le n\)), the length of the permutation \(p\), the length of the array \(a\) and the value of \(d\). The second line contains \(n\) integers \(p_1, p_2, \ldots, p_n\) (\(1\leq p_i \leq n\), \(p_i \ne p_j\) for \(i \ne j\)). The third line contains \(m\) distinct integers \(a_1, a_2, \ldots, a_m\) (\(1\leq a_i \leq n\), \(a_i \ne a_j\) for \(i \ne j\)).The sum of \(n\) over all test cases doesn't exceed \(5 \cdot 10^5\).
For each test case, print the minimum number of moves needed such that the array \(a\) becomes good.
In the first case, \(pos(a_1)=1\), \(pos(a_2)=3\). To make the array good, one way is to swap \(p_3\) and \(p_4\). After that, the array \(a\) will be good because the condition \(\mathrm{pos}(a_2) \le \mathrm{pos}(a_1) + d\) won't be satisfied.In the second case, \(pos(a_1)=1\), \(pos(a_2)=4\). The \(3\) moves could be: Swap \(p_3\) and \(p_4\). Swap \(p_2\) and \(p_3\). Swap \(p_1\) and \(p_2\). After these moves, the permutation \(p\) will be \([2,5,4,3,1]\). The array \(a\) will be good because the condition \(\mathrm{pos}(a_1) < \mathrm{pos}(a_2)\) won't be satisfied. It can be shown that you can't make the array \(a\) good with fewer moves.In the third case, \(pos(a_1)=1\), \(pos(a_2)=3\), \(pos(a_3)=5\). The \(2\) moves can be: Swap \(p_4\) and \(p_5\). Swap \(p_3\) and \(p_4\). After these moves, the permutation \(p\) will be \([3,4,2,1,5]\). The array \(a\) will be good because the condition \(\mathrm{pos}(a_2) < \mathrm{pos}(a_3)\) won't be satisfied. It can be shown that you can't make the array \(a\) good with fewer moves.In the fourth case, \(pos(a_1)=2\), \(pos(a_2)=1\). The array \(a\) is already good.In the fifth case, \(pos(a_1)=2\), \(pos(a_2)=5\). The \(2\) moves are: Swap \(p_1\) and \(p_2\). Swap \(p_5\) and \(p_6\).
Input: 54 2 21 2 3 41 35 2 45 4 3 2 15 25 3 33 4 1 5 23 1 22 2 11 22 16 2 41 2 3 4 5 62 5 | Output: 1 3 2 0 2
Easy
2
1,377
717
100
17
254
A
254A
A. Cards with Numbers
1,200
constructive algorithms; sortings
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
The first line contains integer n (1 ≀ n ≀ 3Β·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≀ ai ≀ 5000) β€” the numbers that are written on the cards. The numbers on the line are separated by single spaces.
If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β€” the indices of the cards that form the pairs.Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.
Input: 320 30 10 30 20 10 | Output: 4 21 56 3
Easy
2
399
246
431
2
1,359
D
1359D
D. Yet Another Yet Another Task
2,000
data structures; dp; implementation; two pointers
Alice and Bob are playing yet another card game. This time the rules are the following. There are \(n\) cards lying in a row in front of them. The \(i\)-th card has value \(a_i\). First, Alice chooses a non-empty consecutive segment of cards \([l; r]\) (\(l \le r\)). After that Bob removes a single card \(j\) from that segment \((l \le j \le r)\). The score of the game is the total value of the remaining cards on the segment \((a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r)\). In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is \(0\).Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.What segment should Alice choose so that the score is maximum possible? Output the maximum score.
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) β€” the number of cards.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-30 \le a_i \le 30\)) β€” the values on the cards.
Print a single integer β€” the final score of the game.
In the first example Alice chooses a segment \([1;5]\) β€” the entire row of cards. Bob removes card \(3\) with the value \(10\) from the segment. Thus, the final score is \(5 + (-2) + (-1) + 4 = 6\).In the second example Alice chooses a segment \([1;4]\), so that Bob removes either card \(1\) or \(3\) with the value \(5\), making the answer \(5 + 2 + 3 = 10\).In the third example Alice can choose any of the segments of length \(1\): \([1;1]\), \([2;2]\) or \([3;3]\). Bob removes the only card, so the score is \(0\). If Alice chooses some other segment then the answer will be less than \(0\).
Input: 5 5 -2 10 -1 4 | Output: 6
Hard
4
839
208
53
13
977
A
977A
A. Wrong Subtraction
800
implementation
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: if the last digit of the number is non-zero, she decreases the number by one; if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). You are given an integer number \(n\). Tanya will subtract one from it \(k\) times. Your task is to print the result after all \(k\) subtractions.It is guaranteed that the result will be positive integer number.
The first line of the input contains two integer numbers \(n\) and \(k\) (\(2 \le n \le 10^9\), \(1 \le k \le 50\)) β€” the number from which Tanya will subtract and the number of subtractions correspondingly.
Print one integer number β€” the result of the decreasing \(n\) by one \(k\) times.It is guaranteed that the result will be positive integer number.
The first example corresponds to the following sequence: \(512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50\).
Input: 512 4 | Output: 50
Beginner
1
585
207
146
9
1
C
1C
C. Ancient Berland Circus
2,100
geometry; math
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges.Recently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time.You are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.
The input file consists of three lines, each of them contains a pair of numbers –– coordinates of the pillar. Any coordinate doesn't exceed 1000 by absolute value, and is given with at most six digits after decimal point.
Output the smallest possible area of the ancient arena. This number should be accurate to at least 6 digits after the decimal point. It's guaranteed that the number of angles in the optimal polygon is not larger than 100.
Input: 0.000000 0.0000001.000000 1.0000000.000000 1.000000 | Output: 1.00000000
Hard
2
671
221
221
0
1,346
E
1346E
F. Dune II: Battle For Arrakis
1,700
*special; dp; graphs
You're at the last mission in one very old and very popular strategy game Dune II: Battle For Arrakis. The map of the mission can be represented as a rectangular matrix of size \(n \times m\). Initially, there are \(a_{i, j}\) units of your army in the cell \((i, j)\).You want to prepare for the final battle, so you want to move all your army into exactly one cell of the map (i.e. \(nm-1\) cells should contain \(0\) units of the army and the remaining cell should contain the entire army).To do this, you can do some (possibly, zero) number of moves. During one move, you can select exactly one unit from some cell and move it to one of the adjacent by side cells. I.e. from the cell \((i, j)\) you can move the unit to cells: \((i - 1, j)\); \((i, j - 1)\); \((i + 1, j)\); \((i, j + 1)\). Of course, you want to move all your army into exactly one cell as fast as possible. So, you want to know the minimum number of moves you need to do that.And, of course, life goes on, so the situation on the map changes. There are \(q\) updates, the \(i\)-th update is denoted by three integers \(x, y, z\). This update affects the army in the cell \((x, y)\): after this update, the number of units in the cell \((x, y)\) becomes \(z\) (i.e. you replace \(a_{x, y}\) with \(z\)).Also, you want to determine, for each \(i\), the minimum number of moves needed to move your entire army into exactly one cell with the first \(i\) updates applied to the initial map. In other words, the map after the \(i\)-th update equals the initial map with the first \(i\) updates applied to it.
The first line of the input contains three integers \(n, m\) and \(q\) (\(1 \le n, m \le 1000; 1 \le q \le 5000\)) β€” the size of the matrix and the number of updates correspondingly.The next \(n\) lines contain \(m\) integers each, where the \(j\)-th integer in the \(i\)-th line is \(a_{i, j}\) (\(1 \le a_{i, j} \le 10^9\)) β€” the number of units in the cell \((i, j)\).The next \(q\) lines contain three integers each, where the \(i\)-th line contains three integers \(x_i, y_i\) and \(z_i\) (\(1 \le x_i \le n; 1 \le y_i \le m; 1 \le z_i \le 10^9\)) β€” the cell in which the number of units updates and the new number of units in this cell correspondingly.
Print \(q+1\) integers \(r_0, r_1, r_2, \dots, r_n\), where \(r_0\) is the minimum number of moves you need to move all your army into exactly one cell, and \(r_i\) for all \(i\) from \(1\) to \(q\) is the minimum number of moves you need to move all your army into exactly one cell after the first \(i\) updates.
Input: 3 3 1 1 2 3 2 1 2 1 1 2 2 3 100 | Output: 21 22
Medium
3
1,575
658
313
13
2,043
C
2043C
C. Sums on Segments
1,600
binary search; brute force; data structures; dp; greedy; math
You are given an array \(a\) of \(n\) integers, where all elements except for at most one are equal to \(-1\) or \(1\). The remaining element \(x\) satisfies \(-10^9 \le x \le 10^9\).Find all possible sums of subarrays of \(a\), including the empty subarray, whose sum is defined as \(0\). In other words, find all integers \(x\) such that the array \(a\) has at least one subarray (possibly empty) with sum equal to \(x\). A subarray is a contiguous subsegment of an array.Output these sums in ascending order. Each sum should be printed only once, even if it is achieved by multiple subarrays.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Then, \(t\) test cases follow.Each test case consists of two lines: The first line contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the size of the array. The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10^9 \le a_i \le 10^9\)) β€” the elements of the array \(a\). In the array \(a\), there is at most one element that is neither \(1\) nor \(-1\). Additional constraint on the input: the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output two lines: In the first line, print a single integer β€” the number of distinct subarray sums. In the second line, print these sums in ascending order. Each sum should be printed only once, even if it is produced by multiple subarrays.
Let's define \(a[i,j]\) as the subarray of \(a\) from position \(i\) to position \(j\).Consider the first test case of the example: \(-1\) is produced by \(a[2,2]\); \(0\) is produced by the empty subarray; \(1\) is produced by \(a[4,4]\); \(2\) is produced by \(a[4,5]\); \(9\) is produced by \(a[2,3]\); \(10\) is produced by \(a[1,3]\); \(11\) is produced by \(a[3,4]\); \(12\) is produced by \(a[3,5]\).
Input: 551 -1 10 1 15-1 -1 -1 -1 -12-1 227 131 4 -1 | Output: 8 -1 0 1 2 9 10 11 12 6 -5 -4 -3 -2 -1 0 4 -1 0 1 2 4 0 1 7 8 6 -1 0 1 3 4 5
Medium
6
595
587
260
20
80
A
80A
A. Panoramix's Prediction
800
brute force
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
The first and only input line contains two positive integers β€” n and m (2 ≀ n < m ≀ 50). It is guaranteed that n is prime.Pretests contain all the cases with restrictions 2 ≀ n < m ≀ 4.
Print YES, if m is the next prime number after n, or NO otherwise.
Input: 3 5 | Output: YES
Beginner
1
1,154
185
66
0
1,160
A2
1160A2
A2. Collaboration
0
*special
Consider several locations in integer points on the plane. One of the locations is the base where workers wait. Every other location contains one job.Each job has the following characteristics: work duration, the required number of workers, and also the earliest possible moment of starting the job and the latest possible moment of completing it. In order to complete the job, the required number of workers must simultaneously start working on it, and then be continuously present at the location for the duration of the job. Each job must either be fully done exactly once, or left untouched.Our task is to determine what should the workers do so that we have more profit. any worker can contribute to any job. We can use as many workers as we like, but each worker must take part in doing at least one job.Each worker starts at the base at a certain moment, then moves between locations and does the jobs, and finally gets back to the base and stops completely. A worker can move along coordinate axes, and spends one minute increasing or decreasing any one of his coordinates by \(1\). We have to pay the worker \(240\) credits for appearing in our solution, and additionally \(1\) credit per minute, up to the moment when the worker stops completely.We get rewarded for each job that is done. For a job with duration \(d\) and the required number of workers \(p\), we get a reward of \(d \cdot p \cdot (p + 5)\) credits. The jobs which are not done don't contribute to this sum.InputThe first line contains an integer \(n\) from \(500\) to \(2000\): the number of locations. Each of the following \(n\) lines contains six integers and describes one location in the format \(x\) \(y\) \(d\) \(p\) \(l\) \(h\). The coordinates \(x\) and \(y\) are integers from \(0\) to \(100\). The duration \(d\) is an integer from \(5\) to \(30\) minutes. The required number of workers \(p\) is an integer from \(1\) to \(7\) people. The earliest possible start moment \(l\) and the latest possible completion moment \(h\) are integers from \(200\) to \(800\) minutes, chosen so that \(60 \le h - l \le 300\).The first location is the base. It is an exclusion to the rules above and has the format \(x\) \(y\) \(0\) \(0\) \(0\) \(0\). All given points \((x, y)\) are distinct.In all tests, the number \(n\), as well as all points, durations, numbers of required workers, and time spans are chosen randomly, independently, and uniformly from the available choices.OutputPrint instructions for each worker as a block of a few lines which look as follows: start (at-moment) (at-location)The first line of a block. Determines the moment when the worker starts at the base. The location must be the base, and so have the number \(1\). arrive (at-moment) (at-location)We want the worker to arrive at this moment to this location. If he can not make it in time after the previous command, the solution is considered incorrect. Locations are numbered from \(1\) to \(n\) in input order. work (start-moment) (end-moment) (at-location)We want the worker to do the job at this location in this exact time interval. The location must be equal to the location in the previous arrival command. If the worker can not make it in time after the previous command, or the given time interval has wrong length or exceeds the time span of the location, the solution is considered incorrect. This command must be present at least once in each block. Recall that each job must be either completed simultaneously by the required number of workers, or left untouched, otherwise, the solution will be considered incorrect. endThe last line of a block. The worker must be in the same position where he started. At each moment, there may be arbitrarily many workers in each location. All moments in the output must be integers from \(0\) to \(1000\), and all location numbers must be integers from \(1\) to \(n\).Print consecutive blocks one under the other, with no gaps.ExampleInput45 15 0 0 0 02 13 30 2 200 4003 12 29 1 350 60039 21 9 4 671 757Outputstart 335 1arrive 340 2work 340 370 2arrive 372 3work 372 401 3arrive 406 1endstart 335 1arrive 340 2work 340 370 2arrive 375 1endExplanationThe reward for the job at location \(2\) is \(30 \cdot 2 \cdot (2 + 5) = 420\) credits.The reward for the job at location \(3\) is \(29 \cdot 1 \cdot (1 + 5) = 174\) credits.The job at location \(4\) is not completed.We have to pay \(240 + 71 = 311\) credits to the first worker.We also have to pay \(240 + 40 = 280\) credits to the second worker.Profit: \(420 + 174 - 311 - 280 = 3\).Note that this example is too short (\(n < 500\)) and so does not appear in the testing system. It is included for explanatory purposes only.ScoringEach test is scored independently. The score for a test is the profit divided by \(1000\). It the profit is negative, the score is equal to zero. If a solution did not output a valid answer on a certain test, the result for this test is also zero.TestingYour solution will be checked on sets of tests generated in advance. A solution's score is the sum of its results on all the tests. If a solution did not output a valid answer on a certain test, the result for this test is zero.During the main phase of the contest, there are two ways to submit a solution. The first one, problem A1, is to check on examples. There are \(10\) example tests which are also available for local testing. As soon as the solution is checked, you can see reports for all examples by clicking on the submission result. The tests for A1 are open, you can download them from the links https://assets.codeforces.com/rounds/1160/codeforces-vrt-2019.tar.gz (for Linux) and https://assets.codeforces.com/rounds/1160/codeforces-vrt-2019.zip (for Windows). After testing, you can click the verdict of your submission to see the result for each test. The second way, problem A2, is to check on preliminary tests. There are \(100\) preliminary tests which are generated in advance but kept secret. The score for preliminary tests (but not for example tests) is used in the preliminary scoreboard. This score does not affect the final results, but nevertheless allows to roughly compare a solution with others. After the main phase ends, for each participant, the system chooses the final solution: consider all solutions sent for preliminary testing; choose the ones which got a total score strictly greater than zero; define the final solution as the one of chosen solutions which has the latest submission time. Note that the solutions sent only to be checked on examples are not considered when choosing the final solution.During final testing, all final solutions will be checked on the same set of a large number (\(\approx 1000\)) of final tests. The score for final tests determines the final scoreboard. The winner is the contestant whose solution gets the highest total score. In case two or more participants have equal total score, the contestants with such score tie for the same place.
Beginner
1
6,959
0
0
11
1,993
B
1993B
B. Parity and Sum
1,100
constructive algorithms; greedy
Given an array \(a\) of \(n\) positive integers.In one operation, you can pick any pair of indexes \((i, j)\) such that \(a_i\) and \(a_j\) have distinct parity, then replace the smaller one with the sum of them. More formally: If \(a_i < a_j\), replace \(a_i\) with \(a_i + a_j\); Otherwise, replace \(a_j\) with \(a_i + a_j\). Find the minimum number of operations needed to make all elements of the array have the same parity.
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 a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)) β€” the elements of array \(a\).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 number of operations required.
In the first test case, all integers already have the same parity. Therefore, no operation is needed.In the third test case, we can perform two operations \((1, 2)\) and \((1, 3)\). The array \(a\) transforms as follows: \(a = [\color{red}2, \color{red}3, 4] \longrightarrow [\color{red}5, 3, \color{red}4] \longrightarrow [5, 3, 9]\).In the fourth test case, an example of an optimal sequence of operations is \((1, 2)\), \((1, 3)\), \((1, 4)\), and \((1, 4)\). The array \(a\) transforms as follows: \(a = [\color{red}3, \color{red}2, 2, 8] \longrightarrow [\color{red}3, 5, \color{red}2, 8] \longrightarrow [\color{red}3, 5, 5, \color{red}8] \longrightarrow [\color{red}{11}, 5, 5, \color{red}8] \longrightarrow [11, 5, 5, 19]\).
Input: 751 3 5 7 944 4 4 432 3 443 2 2 864 3 6 1 2 163 6 1 2 1 25999999996 999999997 999999998 999999999 1000000000 | Output: 0 0 2 4 3 3 3
Easy
2
429
406
88
19
1,422
D
1422D
D. Returning Home
2,300
graphs; shortest paths; sortings
Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.Let's represent the city as an area of \(n \times n\) square blocks. Yura needs to move from the block with coordinates \((s_x,s_y)\) to the block with coordinates \((f_x,f_y)\). In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are \(m\) instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate \(x\) or with the same coordinate \(y\) as the location.Help Yura to find the smallest time needed to get home.
The first line contains two integers \(n\) and \(m\) β€” the size of the city and the number of instant-movement locations (\(1 \le n \le 10^9\), \(0 \le m \le 10^5\)).The next line contains four integers \(s_x\) \(s_y\) \(f_x\) \(f_y\) β€” the coordinates of Yura's initial position and the coordinates of his home (\( 1 \le s_x, s_y, f_x, f_y \le n\)).Each of the next \(m\) lines contains two integers \(x_i\) \(y_i\) β€” coordinates of the \(i\)-th instant-movement location (\(1 \le x_i, y_i \le n\)).
In the only line print the minimum time required to get home.
In the first example Yura needs to reach \((5, 5)\) from \((1, 1)\). He can do that in \(5\) minutes by first using the second instant-movement location (because its \(y\) coordinate is equal to Yura's \(y\) coordinate), and then walking \((4, 1) \to (4, 2) \to (4, 3) \to (5, 3) \to (5, 4) \to (5, 5)\).
Input: 5 3 1 1 5 5 1 2 4 1 3 3 | Output: 5
Expert
3
807
500
61
14
1,889
C1
1889C1
C1. Doremy's Drying Plan (Easy Version)
2,000
brute force; data structures; dp; greedy; sortings
The only differences between the two versions of this problem are the constraint on \(k\), the time limit and the memory limit. You can make hacks only if all versions of the problem are solved.Doremy lives in a rainy country consisting of \(n\) cities numbered from \(1\) to \(n\).The weather broadcast predicted the distribution of rain in the next \(m\) days. In the \(i\)-th day, it will rain in the cities in the interval \([l_i, r_i]\). A city is called dry if it will never rain in that city in the next \(m\) days.It turns out that Doremy has a special power. She can choose \(k\) days (in the easy version, \(k = 2\)), and during these days it will not rain. Doremy wants to calculate the maximum number of dry cities after using the special power.
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 three integers \(n\), \(m\) and \(k\) (\(1\le n\le 2\cdot 10^5\), \(2 \le m \le 2\cdot 10^5\), \(k = 2\)) β€” the number of cities, the number of days, and the number of days of rain that Doremy can prevent.Then, \(m\) lines follow. The \(i\)-th line contains two integers \(l_i\), \(r_i\) (\(1\le l_i\le r_i\le n\)) β€” the rain coverage on day \(i\).It is guaranteed that the sum of \(n\) and the sum of \(m\) over all test cases do not exceed \(2\cdot 10^5\).
For each test case, output one integer β€” the maximum number of dry cities.
In the first test case, if Doremy prevents rain \(1,2\), then city \(2\) will be dry; rain \(2,3\), then no city will be dry; rain \(1,3\), then no city will be dry; So there is at most \(1\) dry city.In the second test case, if Doremy prevents rain \(1,2\), then city \(1,2\) will be dry; rain \(2,3\), then city \(4,5\) will be dry; rain \(1,3\), then city \(1,5\) will be dry. So there are at most \(2\) dry cities.In the third test case, it is optimal to prevent rain \(2,5\).In the forth test case, there is always \(4\) days of rain that wets all the cities and cannot be prevented.
Input: 62 3 21 21 21 15 3 21 32 43 510 6 21 56 102 23 75 81 4100 6 21 1001 1001 1001 1001 1001 1001000 2 21 11 120 5 29 203 310 1111 136 18 | Output: 1 2 3 0 1000 15
Hard
5
757
663
74
18
1,845
E
1845E
E. Boxes and Balls
2,500
dp; implementation; math
There are \(n\) boxes placed in a line. The boxes are numbered from \(1\) to \(n\). Some boxes contain one ball inside of them, the rest are empty. At least one box contains a ball and at least one box is empty.In one move, you have to choose a box with a ball inside and an adjacent empty box and move the ball from one box into another. Boxes \(i\) and \(i+1\) for all \(i\) from \(1\) to \(n-1\) are considered adjacent to each other. Boxes \(1\) and \(n\) are not adjacent.How many different arrangements of balls exist after exactly \(k\) moves are performed? Two arrangements are considered different if there is at least one such box that it contains a ball in one of them and doesn't contain a ball in the other one.Since the answer might be pretty large, print its remainder modulo \(10^9+7\).
The first line contains two integers \(n\) and \(k\) (\(2 \le n \le 1500\); \(1 \le k \le 1500\)) β€” the number of boxes and the number of moves.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(a_i \in \{0, 1\}\)) β€” \(0\) denotes an empty box and \(1\) denotes a box with a ball inside. There is at least one \(0\) and at least one \(1\).
Print a single integer β€” the number of different arrangements of balls that can exist after exactly \(k\) moves are performed, modulo \(10^9+7\).
In the first example, there are the following possible arrangements: 0 1 1 0 β€” obtained after moving the ball from box \(1\) to box \(2\); 1 0 0 1 β€” obtained after moving the ball from box \(3\) to box \(4\); 1 1 0 0 β€” obtained after moving the ball from box \(3\) to box \(2\). In the second example, there are the following possible arrangements: 1 0 1 0 β€” three ways to obtain that: just reverse the operation performed during the first move; 0 1 0 1 β€” obtained from either of the first two arrangements after the first move.
Input: 4 1 1 0 1 0 | Output: 3
Expert
3
802
356
145
18
274
D
274D
D. Lovely Matrix
2,200
dfs and similar; graphs; greedy; sortings
Lenny had an n Γ— m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely.One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix.Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers.
The first line of the input contains two positive integers n and m (1 ≀ nΒ·m ≀ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries.
If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on.
Input: 3 31 -1 -11 2 12 -1 1 | Output: 3 1 2
Hard
4
706
311
348
2
293
D
293D
D. Ksusha and Square
2,700
geometry; math; probabilities; two pointers
Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be?A pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points p, q (p β‰  q) and q, p are considered the same.Help Ksusha! Count the required expectation.
The first line contains integer n (3 ≀ n ≀ 105) β€” the number of vertices of Ksusha's convex polygon. Next n lines contain the coordinates of the polygon vertices in clockwise or counterclockwise order. The i-th line contains integers xi, yi (|xi|, |yi| ≀ 106) β€” the coordinates of the vertex that goes i-th in that order.
Print a single real number β€” the required expected area. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6.
Input: 30 05 55 0 | Output: 4.6666666667
Master
4
692
321
152
2
2,080
B
2080B
1,700
*special
Medium
1
0
0
0
20
995
E
995E
E. Number Clicker
2,700
divide and conquer; graphs; meet-in-the-middle; number theory
Allen is playing Number Clicker on his phone.He starts with an integer \(u\) on the screen. Every second, he can press one of 3 buttons. Turn \(u \to u+1 \pmod{p}\). Turn \(u \to u+p-1 \pmod{p}\). Turn \(u \to u^{p-2} \pmod{p}\). Allen wants to press at most 200 buttons and end up with \(v\) on the screen. Help him!
The first line of the input contains 3 positive integers: \(u, v, p\) (\(0 \le u, v \le p-1\), \(3 \le p \le 10^9 + 9\)). \(p\) is guaranteed to be prime.
On the first line, print a single integer \(\ell\), the number of button presses. On the second line, print integers \(c_1, \dots, c_\ell\), the button presses. For \(1 \le i \le \ell\), \(1 \le c_i \le 3\).We can show that the answer always exists.
In the first example the integer on the screen changes as \(1 \to 2 \to 3\).In the second example the integer on the screen changes as \(3 \to 2\).
Input: 1 3 5 | Output: 21 1
Master
4
317
154
249
9
607
E
607E
E. Cross Sum
3,300
binary search; geometry
Genos has been given n distinct lines on the Cartesian plane. Let be a list of intersection points of these lines. A single point might appear multiple times in this list if it is the intersection of multiple pairs of lines. The order of the list does not matter.Given a query point (p, q), let be the corresponding list of distances of all points in to the query point. Distance here refers to euclidean distance. As a refresher, the euclidean distance between two points (x1, y1) and (x2, y2) is .Genos is given a point (p, q) and a positive integer m. He is asked to find the sum of the m smallest elements in . Duplicate elements in are treated as separate elements. Genos is intimidated by Div1 E problems so he asked for your help.
The first line of the input contains a single integer n (2 ≀ n ≀ 50 000) β€” the number of lines.The second line contains three integers x, y and m (|x|, |y| ≀ 1 000 000, ) β€” the encoded coordinates of the query point and the integer m from the statement above. The query point (p, q) is obtained as . In other words, divide x and y by 1000 to get the actual query point. denotes the length of the list and it is guaranteed that .Each of the next n lines contains two integers ai and bi (|ai|, |bi| ≀ 1 000 000) β€” the parameters for a line of the form: . It is guaranteed that no two lines are the same, that is (ai, bi) β‰  (aj, bj) if i β‰  j.
Print a single real number, the sum of m smallest elements of . Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.To clarify, 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 .
In the first sample, the three closest points have distances and .In the second sample, the two lines y = 1000x - 1000 and intersect at (2000000, 1999999000). This point has a distance of from ( - 1000, - 1000).In the third sample, the three lines all intersect at the point (1, 1). This intersection point is present three times in since it is the intersection of three pairs of lines. Since the distance between the intersection point and the query point is 2, the answer is three times that or 6.
Input: 41000 1000 31000 0-1000 00 50000 -5000 | Output: 14.282170363
Master
2
737
639
298
6
1,611
F
1611F
F. ATM and Students
1,800
binary search; data structures; two pointers
Polycarp started working at a bank. He was assigned to monitor the ATM. The ATM initially contains \(s\) rubles.A queue of \(n\) students lined up to him. Each student wants to either withdraw a certain amount of money or deposit it into an account. If \(a_i\) is positive, then the student credits that amount of money via ATM. Otherwise, the student withdraws \(|a_i|\) rubles.In the beginning, the ATM is turned off and an arbitrary number of students are not served. At some point, Polycarp turns on the ATM, which has an initial amount of \(s\) rubles. Then, the remaining students start queueing at the ATM. If at some point in time there is less money in the ATM than the student wants to withdraw, then the student is not served and Polycarp turns off the ATM and does not turn it on anymore.More formally, the students that are served are forming a contiguous subsequence.Polycarp wants the ATM to serve the maximum number of students. Help him in this matter. Print the numbers of the first and last student, or determine that he will not be able to serve anyone.In other words, find such a longest continuous segment of students that, starting with the sum of \(s\) at the ATM, all these students will be served. ATM serves students consistently (i.e. one after another in the order of the queue).
The first line of the input contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.Each test case consists of two lines. The first one contains integers \(n\) and \(s\) (\(1 \le n \le 2\cdot10^5\); \(0 \le s \le 10^9\)) β€” the length of the \(a\) array and the initial amount of rubles in the ATM. The second contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10^9 \le a_i \le 10^9\)) β€” elements of the \(a\) array. Note that \(a_i\) can be zero.It is guaranteed that the sum of the values \(n\) over all test cases does not exceed \(2\cdot10^5\).
Print \(t\) lines, each line must contain the answer to the corresponding set of input data: if the answer exists, print the numbers of the first and last served student. If there is no solution, then print -1 on the line.If there are several possible answers, print any.
In the first test case, the only correct answer is 2 4, since when serving students, the number of rubles at the ATM does not become negative, and this is the maximum number of students that can be served.In the second test case, the answer is -1, as there is not enough money for any student at the ATM.In the third test case, the answer can be either 1 2 or 4 5.
Input: 3 4 10 -16 2 -6 8 3 1000 -100000 -100000 -100000 6 0 2 6 -164 1 -1 -6543 | Output: 2 4 -1 1 2
Medium
3
1,308
570
271
16
339
D
339D
D. Xenia and Bit Operations
1,700
data structures; trees
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query.
Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query.
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Input: 2 41 6 3 51 43 41 21 2 | Output: 1333
Medium
2
1,436
267
88
3
1,453
E
1453E
E. Dog Snacks
2,300
binary search; dfs and similar; dp; greedy; trees
Gildong is playing with his dog, Badugi. They're at a park that has \(n\) intersections and \(n-1\) bidirectional roads, each \(1\) meter in length and connecting two intersections with each other. The intersections are numbered from \(1\) to \(n\), and for every \(a\) and \(b\) (\(1 \le a, b \le n\)), it is possible to get to the \(b\)-th intersection from the \(a\)-th intersection using some set of roads.Gildong has put one snack at every intersection of the park. Now Gildong will give Badugi a mission to eat all of the snacks. Badugi starts at the \(1\)-st intersection, and he will move by the following rules: Badugi looks for snacks that are as close to him as possible. Here, the distance is the length of the shortest path from Badugi's current location to the intersection with the snack. However, Badugi's sense of smell is limited to \(k\) meters, so he can only find snacks that are less than or equal to \(k\) meters away from himself. If he cannot find any such snack, he fails the mission. Among all the snacks that Badugi can smell from his current location, he chooses a snack that minimizes the distance he needs to travel from his current intersection. If there are multiple such snacks, Badugi will choose one arbitrarily. He repeats this process until he eats all \(n\) snacks. After that, he has to find the \(1\)-st intersection again which also must be less than or equal to \(k\) meters away from the last snack he just ate. If he manages to find it, he completes the mission. Otherwise, he fails the mission. Unfortunately, Gildong doesn't know the value of \(k\). So, he wants you to find the minimum value of \(k\) that makes it possible for Badugi to complete his mission, if Badugi moves optimally.
Each test contains one or more test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)).The first line of each test case contains one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β€” the number of intersections of the park.The next \(n-1\) lines contain two integers \(u\) and \(v\) (\(1 \le u,v \le n\), \(u \ne v\)) each, which means there is a road between intersection \(u\) and \(v\). All roads are bidirectional and distinct.It is guaranteed that: For each test case, for every \(a\) and \(b\) (\(1 \le a, b \le n\)), it is possible to get to the \(b\)-th intersection from the \(a\)-th intersection. The sum of \(n\) in all test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, print one integer β€” the minimum possible value of \(k\) such that Badugi can complete the mission.
In the first case, Badugi can complete his mission with \(k=2\) by moving as follows: Initially, Badugi is at the \(1\)-st intersection. The closest snack is obviously at the \(1\)-st intersection, so he just eats it. Next, he looks for the closest snack, which can be either the one at the \(2\)-nd or the one at the \(3\)-rd intersection. Assume that he chooses the \(2\)-nd intersection. He moves to the \(2\)-nd intersection, which is \(1\) meter away, and eats the snack. Now the only remaining snack is on the \(3\)-rd intersection, and he needs to move along \(2\) paths to get to it. After eating the snack at the \(3\)-rd intersection, he needs to find the \(1\)-st intersection again, which is only \(1\) meter away. As he gets back to it, he completes the mission. In the second case, the only possible sequence of moves he can make is \(1\) – \(2\) – \(3\) – \(4\) – \(1\). Since the distance between the \(4\)-th intersection and the \(1\)-st intersection is \(3\), \(k\) needs to be at least \(3\) for Badugi to complete his mission.In the third case, Badugi can make his moves as follows: \(1\) – \(5\) – \(6\) – \(7\) – \(8\) – \(2\) – \(3\) – \(4\) – \(1\). It can be shown that this is the only possible sequence of moves for Badugi to complete his mission with \(k=3\).
Input: 3 3 1 2 1 3 4 1 2 2 3 3 4 8 1 2 2 3 3 4 1 5 5 6 6 7 5 8 | Output: 2 3 3
Expert
5
1,734
705
118
14
1,249
B2
1249B2
B2. Books Exchange (hard version)
1,300
dfs and similar; dsu; math
The only difference between easy and hard versions is constraints.There are \(n\) kids, each of them is reading a unique book. At the end of any day, the \(i\)-th kid will give his book to the \(p_i\)-th kid (in case of \(i = p_i\) the kid will give his book to himself). It is guaranteed that all values of \(p_i\) are distinct integers from \(1\) to \(n\) (i.e. \(p\) is a permutation). The sequence \(p\) doesn't change from day to day, it is fixed.For example, if \(n=6\) and \(p=[4, 6, 1, 3, 5, 2]\) then at the end of the first day the book of the \(1\)-st kid will belong to the \(4\)-th kid, the \(2\)-nd kid will belong to the \(6\)-th kid and so on. At the end of the second day the book of the \(1\)-st kid will belong to the \(3\)-th kid, the \(2\)-nd kid will belong to the \(2\)-th kid and so on.Your task is to determine the number of the day the book of the \(i\)-th child is returned back to him for the first time for every \(i\) from \(1\) to \(n\).Consider the following example: \(p = [5, 1, 2, 4, 3]\). The book of the \(1\)-st kid will be passed to the following kids: after the \(1\)-st day it will belong to the \(5\)-th kid, after the \(2\)-nd day it will belong to the \(3\)-rd kid, after the \(3\)-rd day it will belong to the \(2\)-nd kid, after the \(4\)-th day it will belong to the \(1\)-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer \(q\) independent queries.
The first line of the input contains one integer \(q\) (\(1 \le q \le 1000\)) β€” the number of queries. Then \(q\) queries follow.The first line of the query contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the number of kids in the query. The second line of the query contains \(n\) integers \(p_1, p_2, \dots, p_n\) (\(1 \le p_i \le n\), all \(p_i\) are distinct, i.e. \(p\) is a permutation), where \(p_i\) is the kid which will get the book of the \(i\)-th kid.It is guaranteed that \(\sum n \le 2 \cdot 10^5\) (sum of \(n\) over all queries does not exceed \(2 \cdot 10^5\)).
For each query, print the answer on it: \(n\) integers \(a_1, a_2, \dots, a_n\), where \(a_i\) is the number of the day the book of the \(i\)-th child is returned back to him for the first time in this query.
Input: 6 5 1 2 3 4 5 3 2 3 1 6 4 6 2 1 5 3 1 1 4 3 4 1 2 5 5 1 2 4 3 | Output: 1 1 1 1 1 3 3 3 2 3 3 2 1 3 1 2 2 2 2 4 4 4 1 4
Easy
3
1,537
590
208
12
147
B
147B
B. Smile House
2,500
binary search; graphs; matrices
A smile house is created to raise the mood. It has n rooms. Some of the rooms are connected by doors. For each two rooms (number i and j), which are connected by a door, Petya knows their value cij β€” the value which is being added to his mood when he moves from room i to room j.Petya wondered whether he can raise his mood infinitely, moving along some cycle? And if he can, then what minimum number of rooms he will need to visit during one period of a cycle?
The first line contains two positive integers n and m (), where n is the number of rooms, and m is the number of doors in the Smile House. Then follows the description of the doors: m lines each containing four integers i, j, cij ΠΈ cji (1 ≀ i, j ≀ n, i β‰  j, - 104 ≀ cij, cji ≀ 104). It is guaranteed that no more than one door connects any two rooms. No door connects the room with itself.
Print the minimum number of rooms that one needs to visit during one traverse of the cycle that can raise mood infinitely. If such cycle does not exist, print number 0.
Cycle is such a sequence of rooms a1, a2, ..., ak, that a1 is connected with a2, a2 is connected with a3, ..., ak - 1 is connected with ak, ak is connected with a1. Some elements of the sequence can coincide, that is, the cycle should not necessarily be simple. The number of rooms in the cycle is considered as k, the sequence's length. Note that the minimum possible length equals two.
Input: 4 41 2 -10 31 3 1 -102 4 -10 -13 4 0 -3 | Output: 4
Expert
3
461
389
168
1
1,535
A
1535A
A. Fair Playoff
800
brute force; implementation
Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.It is known that in a match between two players, the one whose skill is greater will win. The skill of the \(i\)-th player is equal to \(s_i\) and all skill levels are pairwise different (i. e. there are no two identical values in the array \(s\)).The tournament is called fair if the two players with the highest skills meet in the finals.Determine whether the given tournament is fair.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.A single line of test case contains four integers \(s_1, s_2, s_3, s_4\) (\(1 \le s_i \le 100\)) β€” skill of the players. It is guaranteed that all the numbers in the array are different.
For each testcase, output YES if the tournament is fair, or NO otherwise.
Consider the example: in the first test case, players \(2\) and \(3\) with skills \(7\) and \(9\) advance to the finals; in the second test case, players \(2\) and \(4\) with skills \(5\) and \(9\) advance to the finals. The player with skill \(6\) does not advance, but the player with skill \(5\) advances to the finals, so the tournament is not fair; in the third test case, players \(1\) and \(3\) with skills \(5\) and \(8\) advance to the finals; in the fourth test case, players \(1\) and \(3\) with skills \(6\) and \(3\) advance to the finals. The player with skill \(5\) does not advance, but the player with skill \(3\) advances to the finals, so the tournament is not fair.
Input: 4 3 7 9 5 4 5 6 9 5 3 8 1 6 5 3 2 | Output: YES NO YES NO
Beginner
2
651
283
73
15
837
C
837C
C. Two Seals
1,500
brute force; implementation
One very important person has a piece of paper in the form of a rectangle a Γ— b.Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi Γ— yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?
The first line contains three integer numbers n, a and b (1 ≀ n, a, b ≀ 100).Each of the next n lines contain two numbers xi, yi (1 ≀ xi, yi ≀ 100).
Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.
In the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.In the third example there is no such pair of seals that they both can fit on a piece of paper.
Input: 2 2 21 22 1 | Output: 4
Medium
2
634
148
105
8
1,608
C
1608C
C. Game Master
1,700
data structures; dfs and similar; dp; graphs; greedy; two pointers
\(n\) players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of \(n-1\) battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 10^5\)) β€” the number of players.The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \leq a_i \leq 10^9\), \(a_i \neq a_j\) for \(i \neq j\)), where \(a_i\) is the strength of the \(i\)-th player on the first map. The third line of each test case contains \(n\) integers \(b_1, b_2, \dots, b_n\) (\(1 \leq b_i \leq 10^9\), \(b_i \neq b_j\) for \(i \neq j\)), where \(b_i\) is the strength of the \(i\)-th player on the second map. It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case print a string of length \(n\). \(i\)-th character should be ""1"" if the \(i\)-th player can win the tournament, or ""0"" otherwise.
In the first test case, the \(4\)-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.
Input: 3 4 1 2 3 4 1 2 3 4 4 11 12 20 21 44 22 11 30 1 1000000000 1000000000 | Output: 0001 1111 1
Medium
6
707
767
152
16
1,385
G
1385G
G. Columns Swaps
2,300
2-sat; dfs and similar; dsu; graphs; implementation
You are given a table \(a\) of size \(2 \times n\) (i.e. two rows and \(n\) columns) consisting of integers from \(1\) to \(n\).In one move, you can choose some column \(j\) (\(1 \le j \le n\)) and swap values \(a_{1, j}\) and \(a_{2, j}\) in it. Each column can be chosen no more than once.Your task is to find the minimum number of moves required to obtain permutations of size \(n\) in both first and second rows of the table or determine if it is impossible to do that.You have to answer \(t\) independent test cases.Recall that the permutation of size \(n\) is such an array of size \(n\) that contains each integer from \(1\) to \(n\) exactly once (the order of elements doesn't matter).
The first line of the input contains one integer \(t\) (\(1 \le t \le 2 \cdot 10^4\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of the test case contains one integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the number of columns in the table. The second line of the test case contains \(n\) integers \(a_{1, 1}, a_{1, 2}, \dots, a_{1, n}\) (\(1 \le a_{1, i} \le n\)), where \(a_{1, i}\) is the \(i\)-th element of the first row of the table. The third line of the test case contains \(n\) integers \(a_{2, 1}, a_{2, 2}, \dots, a_{2, n}\) (\(1 \le a_{2, i} \le n\)), where \(a_{2, i}\) is the \(i\)-th element of the second row of the table.It is guaranteed that the sum of \(n\) does not exceed \(2 \cdot 10^5\) (\(\sum n \le 2 \cdot 10^5\)).
For each test case print the answer: -1 if it is impossible to obtain permutation of size \(n\) in both first and the second rows of the table, or one integer \(k\) in the first line, where \(k\) is the minimum number of moves required to obtain permutations in both rows, and \(k\) distinct integers \(pos_1, pos_2, \dots, pos_k\) in the second line (\(1 \le pos_i \le n\)) in any order β€” indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any.
Input: 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 | Output: 0 2 2 3 1 1 2 3 4 2 3 4 -1
Expert
5
693
770
527
13
938
B
938B
B. Run For Your Prize
1,100
brute force; greedy
You and your friend are participating in a TV show ""Run For Your Prize"".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend β€” at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?
The first line contains one integer n (1 ≀ n ≀ 105) β€” the number of prizes.The second line contains n integers a1, a2, ..., an (2 ≀ ai ≀ 106 - 1) β€” the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.
Print one integer β€” the minimum number of seconds it will take to collect all prizes.
In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.
Input: 32 3 9 | Output: 8
Easy
2
1,008
264
85
9
1,096
C
1096C
C. Polygon for the Angle
1,600
brute force; geometry
You are given an angle \(\text{ang}\). The Jury asks You to find such regular \(n\)-gon (regular polygon with \(n\) vertices) that it has three vertices \(a\), \(b\) and \(c\) (they can be non-consecutive) with \(\angle{abc} = \text{ang}\) or report that there is no such \(n\)-gon. If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed \(998244353\).
The first line contains single integer \(T\) (\(1 \le T \le 180\)) β€” the number of queries. Each of the next \(T\) lines contains one integer \(\text{ang}\) (\(1 \le \text{ang} < 180\)) β€” the angle measured in degrees.
For each query print single integer \(n\) (\(3 \le n \le 998244353\)) β€” minimal possible number of vertices in the regular \(n\)-gon or \(-1\) if there is no such \(n\).
The answer for the first query is on the picture above.The answer for the second query is reached on a regular \(18\)-gon. For example, \(\angle{v_2 v_1 v_6} = 50^{\circ}\).The example angle for the third query is \(\angle{v_{11} v_{10} v_{12}} = 2^{\circ}\).In the fourth query, minimal possible \(n\) is \(180\) (not \(90\)).
Input: 4 54 50 2 178 | Output: 10 18 90 180
Medium
2
412
218
169
10
1,580
B
1580B
B. Mathematics Curriculum
2,600
brute force; combinatorics; dp; trees
Let \(c_1, c_2, \ldots, c_n\) be a permutation of integers \(1, 2, \ldots, n\). Consider all subsegments of this permutation containing an integer \(x\). Given an integer \(m\), we call the integer \(x\) good if there are exactly \(m\) different values of maximum on these subsegments.Cirno is studying mathematics, and the teacher asks her to count the number of permutations of length \(n\) with exactly \(k\) good numbers.Unfortunately, Cirno isn't good at mathematics, and she can't answer this question. Therefore, she asks you for help.Since the answer may be very big, you only need to tell her the number of permutations modulo \(p\).A permutation is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array) and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).A sequence \(a\) is a subsegment of a sequence \(b\) if \(a\) can be obtained from \(b\) by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
The first line contains four integers \(n, m, k, p\) (\(1 \le n \le 100, 1 \le m \le n, 1 \le k \le n, 1 \le p \le 10^9\)).
Output the number of permutations modulo \(p\).
In the first test case, there are four permutations: \([1, 3, 2, 4]\), \([2, 3, 1, 4]\), \([4, 1, 3, 2]\) and \([4, 2, 3, 1]\).Take permutation \([1, 3, 2, 4]\) as an example:For number \(1\), all subsegments containing it are: \([1]\), \([1, 3]\), \([1, 3, 2]\) and \([1, 3, 2, 4]\), and there're three different maxima \(1\), \(3\) and \(4\).Similarly, for number \(3\), there're two different maxima \(3\) and \(4\). For number \(2\), there're three different maxima \(2\), \(3\) and \(4\). And for number \(4\), there're only one, that is \(4\) itself.
Input: 4 3 2 10007 | Output: 4
Expert
4
1,171
123
47
15
2,035
H
2035H
H. Peak Productivity Forces
3,500
constructive algorithms
I'm peakly productive and this is deep.You are given two permutations\(^{\text{βˆ—}}\) \(a\) and \(b\), both of length \(n\).You can perform the following three-step operation on permutation \(a\): Choose an index \(i\) (\(1 \le i \le n\)). Cyclic shift \(a_1, a_2, \ldots, a_{i-1}\) by \(1\) to the right. If you had chosen \(i = 1\), then this range doesn't exist, and you cyclic shift nothing. Cyclic shift \(a_{i + 1}, a_{i + 2}, \ldots, a_n\) by \(1\) to the right. If you had chosen \(i = n\), then this range doesn't exist, and you cyclic shift nothing.After the operation, \(a_1,a_2,\ldots, a_{i-2},a_{i-1},a_i,a_{i + 1}, a_{i + 2},\ldots,a_{n-1}, a_n\) is transformed into \(a_{i-1},a_1,\ldots,a_{i-3},a_{i-2},a_i,a_n, a_{i + 1},\ldots,a_{n-2}, a_{n-1}\).Here are some examples of operations done on the identity permutation \([1,2,3,4,5,6,7]\) of length \(7\): If we choose \(i = 3\), it will become \([2, 1, 3, 7, 4, 5, 6]\). If we choose \(i = 1\), it will become \([1, 7, 2, 3, 4, 5, 6]\). If we choose \(i = 7\), it will become \([6, 1, 2, 3, 4, 5, 7]\). Notably, position \(i\) is not shifted. Find a construction using at most \(2n\) operations to make \(a\) equal to \(b\) or print \(-1\) if it is impossible. The number of operations does not need to be minimized. It can be shown that if it is possible to make \(a\) equal to \(b\), it is possible to do this within \(2n\) operations. \(^{\text{βˆ—}}\)A permutation of length \(n\) is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array), and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).
The first line contains a single integer \(t\) (\(1 \le t \le 5 \cdot 10^4\)) β€” the number of test cases.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 5 \cdot 10^5\)) β€” the lengths of permutations \(a\) and \(b\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) β€” the values of permutation \(a\).The third line of each test case contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \le b_i \le n\)) β€” the values of permutation \(b\).It is guaranteed that the sum of \(n\) over all test cases will not exceed \(5 \cdot 10^5\).
For each test case:If there is a sequence of operations to transform \(a\) into \(b\), output a single integer \(q\) (\(0\le q\le 2n\)) β€” the number of operations in the first line and \(q\) integers with the \(i\)-th number representing the index of the \(i\)-th operation in the second line.If there is no sequence of operations, output \(-1\) in the only line.
In the first case, you can do no operation since \(a=b\).In the second case, it can be proved \(a\) can not be transformed into \(b\).In the third case, \(a\) is transformed into \([2,3,1]\) after the first operation and into \(b\) after the second operation.
Input: 411121 22 132 1 33 2 187 8 3 5 4 6 1 22 1 6 4 5 3 8 7 | Output: 0 -1 2 1 3 7 3 4 5 1 2 1 1
Master
1
1,741
618
363
20
690
D1
690D1
D1. The Wall (easy)
1,200
""The zombies are lurking outside. Waiting. Moaning. And when they come...""""When they come?""""I hope the Wall is high enough.""Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
The first line of the input consists of two space-separated integers R and C, 1 ≀ R, C ≀ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. The input will contain at least one character B and it will be valid.
The number of wall segments in the input configuration.
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Input: 3 7...............BB.B.. | Output: 2
Easy
0
828
382
55
6
1,005
F
1005F
F. Berland and the Shortest Paths
2,100
brute force; dfs and similar; graphs; shortest paths
There are \(n\) cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from \(1\) to \(n\).It is known that, from the capital (the city with the number \(1\)), you can reach any other city by moving along the roads.The President of Berland plans to improve the country's road network. The budget is enough to repair exactly \(n-1\) roads. The President plans to choose a set of \(n-1\) roads such that: it is possible to travel from the capital to any other city along the \(n-1\) chosen roads, if \(d_i\) is the number of roads needed to travel from the capital to city \(i\), moving only along the \(n-1\) chosen roads, then \(d_1 + d_2 + \dots + d_n\) is minimized (i.e. as minimal as possible). In other words, the set of \(n-1\) roads should preserve the connectivity of the country, and the sum of distances from city \(1\) to all cities should be minimized (where you can only use the \(n-1\) chosen roads).The president instructed the ministry to prepare \(k\) possible options to choose \(n-1\) roads so that both conditions above are met.Write a program that will find \(k\) possible ways to choose roads for repair. If there are fewer than \(k\) ways, then the program should output all possible valid ways to choose roads.
The first line of the input contains integers \(n\), \(m\) and \(k\) (\(2 \le n \le 2\cdot10^5, n-1 \le m \le 2\cdot10^5, 1 \le k \le 2\cdot10^5\)), where \(n\) is the number of cities in the country, \(m\) is the number of roads and \(k\) is the number of options to choose a set of roads for repair. It is guaranteed that \(m \cdot k \le 10^6\).The following \(m\) lines describe the roads, one road per line. Each line contains two integers \(a_i\), \(b_i\) (\(1 \le a_i, b_i \le n\), \(a_i \ne b_i\)) β€” the numbers of the cities that the \(i\)-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Print \(t\) (\(1 \le t \le k\)) β€” the number of ways to choose a set of roads for repair. Recall that you need to find \(k\) different options; if there are fewer than \(k\) of them, then you need to find all possible different valid options.In the following \(t\) lines, print the options, one per line. Print an option as a string of \(m\) characters where the \(j\)-th character is equal to '1' if the \(j\)-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the \(t\) lines should be different.Since it is guaranteed that \(m \cdot k \le 10^6\), the total length of all the \(t\) lines will not exceed \(10^6\).If there are several answers, output any of them.
Input: 4 4 31 22 31 44 3 | Output: 211101011
Hard
4
1,389
694
810
10
1,839
C
1839C
C. Insert Zero and Invert Prefix
1,300
constructive algorithms
You have a sequence \(a_1, a_2, \ldots, a_n\) of length \(n\), each element of which is either \(0\) or \(1\), and a sequence \(b\), which is initially empty.You are going to perform \(n\) operations. On each of them you will increase the length of \(b\) by \(1\). On the \(i\)-th operation you choose an integer \(p\) between \(0\) and \(i-1\). You insert \(0\) in the sequence \(b\) on position \(p+1\) (after the first \(p\) elements), and then you invert the first \(p\) elements of \(b\). More formally: let's denote the sequence \(b\) before the \(i\)-th (\(1 \le i \le n\)) operation as \(b_1, b_2, \ldots, b_{i-1}\). On the \(i\)-th operation you choose an integer \(p\) between \(0\) and \(i-1\) and replace \(b\) with \(\overline{b_1}, \overline{b_2}, \ldots, \overline{b_{p}}, 0, b_{p+1}, b_{p+2}, \ldots, b_{i-1}\). Here, \(\overline{x}\) denotes the binary inversion. Hence, \(\overline{0} = 1\) and \(\overline{1} = 0\). You can find examples of operations in the Notes section.Determine if there exists a sequence of operations that makes \(b\) equal to \(a\). If such sequence of operations exists, find it.
Each test contains multiple test cases. 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 one integer \(n\) (\(1 \le n \le 10^5\)) β€” the length of the sequence \(a\).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 1\)) β€” the sequence \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case: output ""NO"", if it is impossible to make \(b\) equal to \(a\) using the given operations; otherwise, output ""YES"" in the first line and \(n\) integers \(p_1, p_2, \ldots, p_n\) (\(0 \le p_i \le i-1\)) in the second line β€” the description of sequence of operations that makes \(b\) equal to \(a\). Here, \(p_i\) should be the integer you choose on the \(i\)-th operation. If there are multiple solutions, you can output any of them.
In the first test case, Before the first operation, \(b = [\,]\). You choose \(p = 0\) and replace \(b\) with \([\, \underline{0} \,]\) On the second operation you choose \(p = 0\) and replace \(b\) with \([\, \underline{0}, 0 \,]\). On the third operation you choose \(p = 2\) and replace \(b\) with \([\, 1, 1, \underline{0} \,]\). On the fourth operation you choose \(p = 1\) and replace \(b\) with \([\, 0, \underline{0}, 1, 0 \,]\). On the fifth operation you choose \(p = 3\) and replace \(b\) with \([\, 1, 1, 0, \underline{0}, 0 \,]\). Hence, sequence \(b\) changes in the following way: \([\,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0} \,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0}, 0 \,]\) \(\xrightarrow{p \, = \, 2}\) \([\, 1, 1, \underline{0} \,]\) \(\xrightarrow{p \, = \, 1}\) \([\, 0, \underline{0}, 1, 0 \,]\) \(\xrightarrow{p \, = \, 3}\) \([\, 1, 1, 0, \underline{0}, 0 \,]\). In the end the sequence \(b\) is equal to the sequence \(a\), so this way to perform operations is one of the correct answers.In the second test case, \(n = 1\) and the only achiveable sequence \(b\) is \([\, 0 \, ]\).In the third test case, there are six possible sequences of operations: \([\,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0} \,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0}, 0 \,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0}, 0, 0 \,]\). \([\,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0} \,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0}, 0 \,]\) \(\xrightarrow{p \, = \, 1}\) \([\, 1, \underline{0}, 0 \,]\). \([\,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0} \,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0}, 0 \,]\) \(\xrightarrow{p \, = \, 2}\) \([\, 1, 1, \underline{0} \,]\). \([\,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0} \,]\) \(\xrightarrow{p \, = \, 1}\) \([\, 1, \underline{0} \,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0}, 1, 0 \,]\). \([\,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0} \,]\) \(\xrightarrow{p \, = \, 1}\) \([\, 1, \underline{0} \,]\) \(\xrightarrow{p \, = \, 1}\) \([\, 0, \underline{0}, 0 \,]\). \([\,]\) \(\xrightarrow{p \, = \, 0}\) \([\, \underline{0} \,]\) \(\xrightarrow{p \, = \, 1}\) \([\, 1, \underline{0} \,]\) \(\xrightarrow{p \, = \, 2}\) \([\, 0, 1, \underline{0} \,]\). None of them makes \(b\) equal to \([\, 0, 1, 1 \,]\), so the answer is ""NO"".
Input: 451 1 0 0 01130 1 161 0 0 1 1 0 | Output: YES 0 0 2 1 3 NO NO YES 0 1 0 2 4 2
Easy
1
1,123
466
455
18
1,194
E
1194E
E. Count The Rectangles
2,200
bitmasks; brute force; data structures; geometry; sortings
There are \(n\) segments drawn on a plane; the \(i\)-th segment connects two points (\(x_{i, 1}\), \(y_{i, 1}\)) and (\(x_{i, 2}\), \(y_{i, 2}\)). Each segment is non-degenerate, and is either horizontal or vertical β€” formally, for every \(i \in [1, n]\) either \(x_{i, 1} = x_{i, 2}\) or \(y_{i, 1} = y_{i, 2}\) (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices \(h_1\), \(h_2\), \(v_1\) and \(v_2\) such that \(h_1 < h_2\) and \(v_1 < v_2\) form a rectangle if the following conditions hold: segments \(h_1\) and \(h_2\) are horizontal; segments \(v_1\) and \(v_2\) are vertical; segment \(h_1\) intersects with segment \(v_1\); segment \(h_2\) intersects with segment \(v_1\); segment \(h_1\) intersects with segment \(v_2\); segment \(h_2\) intersects with segment \(v_2\). Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions \(h_1 < h_2\) and \(v_1 < v_2\) should hold.
The first line contains one integer \(n\) (\(1 \le n \le 5000\)) β€” the number of segments.Then \(n\) lines follow. The \(i\)-th line contains four integers \(x_{i, 1}\), \(y_{i, 1}\), \(x_{i, 2}\) and \(y_{i, 2}\) denoting the endpoints of the \(i\)-th segment. All coordinates of the endpoints are in the range \([-5000, 5000]\).It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
Print one integer β€” the number of ways to choose four segments so they form a rectangle.
The following pictures represent sample cases:
Input: 7 -1 4 -1 -2 6 -1 -2 -1 -2 3 6 3 2 -2 2 4 4 -1 4 3 5 3 5 1 5 2 1 2 | Output: 7
Hard
5
1,129
537
88
11
1,368
D
1368D
D. AND, OR and square sum
1,700
bitmasks; greedy; math
Gottfried learned about binary number representation. He then came up with this task and presented it to you.You are given a collection of \(n\) non-negative integers \(a_1, \ldots, a_n\). You are allowed to perform the following operation: choose two distinct indices \(1 \leq i, j \leq n\). If before the operation \(a_i = x\), \(a_j = y\), then after the operation \(a_i = x~\mathsf{AND}~y\), \(a_j = x~\mathsf{OR}~y\), where \(\mathsf{AND}\) and \(\mathsf{OR}\) are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).After all operations are done, compute \(\sum_{i=1}^n a_i^2\) β€” the sum of squares of all \(a_i\). What is the largest sum of squares you can achieve?
The first line contains a single integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)).The second line contains \(n\) integers \(a_1, \ldots, a_n\) (\(0 \leq a_i < 2^{20}\)).
Print a single integer β€” the largest possible sum of squares that can be achieved after several (possibly zero) operations.
In the first sample no operation can be made, thus the answer is \(123^2\).In the second sample we can obtain the collection \(1, 1, 7\), and \(1^2 + 1^2 + 7^2 = 51\).If \(x\) and \(y\) are represented in binary with equal number of bits (possibly with leading zeros), then each bit of \(x~\mathsf{AND}~y\) is set to \(1\) if and only if both corresponding bits of \(x\) and \(y\) are set to \(1\). Similarly, each bit of \(x~\mathsf{OR}~y\) is set to \(1\) if and only if at least one of the corresponding bits of \(x\) and \(y\) are set to \(1\). For example, \(x = 3\) and \(y = 5\) are represented as \(011_2\) and \(101_2\) (highest bit first). Then, \(x~\mathsf{AND}~y = 001_2 = 1\), and \(x~\mathsf{OR}~y = 111_2 = 7\).
Input: 1 123 | Output: 15129
Medium
3
772
167
123
13
1,076
E
1076E
E. Vasya and a Tree
1,900
data structures; trees
Vasya has a tree consisting of \(n\) vertices with root in vertex \(1\). At first all vertices has \(0\) written on it.Let \(d(i, j)\) be the distance between vertices \(i\) and \(j\), i.e. number of edges in the shortest path from \(i\) to \(j\). Also, let's denote \(k\)-subtree of vertex \(x\) β€” set of vertices \(y\) such that next two conditions are met: \(x\) is the ancestor of \(y\) (each vertex is the ancestor of itself); \(d(x, y) \le k\). Vasya needs you to process \(m\) queries. The \(i\)-th query is a triple \(v_i\), \(d_i\) and \(x_i\). For each query Vasya adds value \(x_i\) to each vertex from \(d_i\)-subtree of \(v_i\).Report to Vasya all values, written on vertices of the tree after processing all queries.
The first line contains single integer \(n\) (\(1 \le n \le 3 \cdot 10^5\)) β€” number of vertices in the tree.Each of next \(n - 1\) lines contains two integers \(x\) and \(y\) (\(1 \le x, y \le n\)) β€” edge between vertices \(x\) and \(y\). It is guarantied that given graph is a tree.Next line contains single integer \(m\) (\(1 \le m \le 3 \cdot 10^5\)) β€” number of queries.Each of next \(m\) lines contains three integers \(v_i\), \(d_i\), \(x_i\) (\(1 \le v_i \le n\), \(0 \le d_i \le 10^9\), \(1 \le x_i \le 10^9\)) β€” description of the \(i\)-th query.
Print \(n\) integers. The \(i\)-th integers is the value, written in the \(i\)-th vertex after processing all queries.
In the first exapmle initial values in vertices are \(0, 0, 0, 0, 0\). After the first query values will be equal to \(1, 1, 1, 0, 0\). After the second query values will be equal to \(1, 11, 1, 0, 0\). After the third query values will be equal to \(1, 11, 1, 100, 0\).
Input: 5 1 2 1 3 2 4 2 5 3 1 1 1 2 0 10 4 10 100 | Output: 1 11 1 100 0
Hard
2
730
556
118
10
178
D2
178D2
D2. Magic Squares
1,900
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.The magic square is a matrix of size n Γ— n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure: Magic squares You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n Γ— n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.It is guaranteed that a solution exists!
The first input line contains a single integer n. The next line contains n2 integers ai ( - 108 ≀ ai ≀ 108), separated by single spaces.The input limitations for getting 20 points are: 1 ≀ n ≀ 3 The input limitations for getting 50 points are: 1 ≀ n ≀ 4 It is guaranteed that there are no more than 9 distinct numbers among ai. The input limitations for getting 100 points are: 1 ≀ n ≀ 4
The first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.
Input: 31 2 3 4 5 6 7 8 9 | Output: 152 7 69 5 14 3 8
Hard
0
970
387
342
1
72
D
72D
D. Perse-script
2,300
*special; expression parsing
Two good friends were trying to make a new programming language called Perse-script.The most important part of this language is strings. A string in Perse-script is put between characters ""So for example ""Hello"" is a string. But Hello is a variable name or a keyword, which are not considered in this problem.Perse-script is function-based. So there are no operators in this language. For example for summing two numbers you have to write sum(a,b) and not a+b.There are several functions for working on strings. These include: concat(x,y) is a function which gets two strings x and y and puts y at the end of x and returns the result. For example concat(""Hello"",""World"") returns ""HelloWorld"". reverse(x) gets a single string x and reverses it. For example reverse(""Hello"") returns ""olleH"". substr(x,a,b) gets a string x and two integers a and b (1 ≀ a ≀ b ≀ n, where n is the length of x). And returns the substring of x between indexes a and b, inclusive. For example substr(""Hello"",2,4) returns ""ell"". substr(x,a,b,c) is another version of substr which works just like the last one but c is the step of adding. c is positive. For example substr(""HelloWorld"",1,10,2) returns ""Hlool"". This substr means that you put the ath character , and then every cth character until you reach b.You're going to manipulate the string part of Perse-script. Given a string expression, you should print its result. It is guaranteed that the expression contains only strings shown by characters "" and the above functions.Commands in Perse-script are case-insensitive. So to call substr function you can write SUBsTr(). But you can't print as the result ""hElLo"" instead of printing ""Hello"".See the samples for more information.
A single line containing the correct expression. It is guaranteed that the total length of this expression does not exceed 103 and that all the integers used in it are less than or equal to 100 by absolute value. The given string is non-empty.All strings in the input which are placed between ""s consist of uppercase and lowercase Latin letters only.
Print in single line the resulting string. It is guaranteed that an answer exists and that the length of the answer does not exceed 104. It is guaranteed that the answer is non-empty.
Input: ""HelloWorld"" | Output: ""HelloWorld""
Expert
2
1,735
351
183
0
856
C
856C
C. Eleventh Birthday
2,400
combinatorics; dp; math
It is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number ai written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112 = 1192 Γ— 11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.
Input data contains multiple test cases. The first line of the input data contains an integer t β€” the number of test cases (1 ≀ t ≀ 100). The descriptions of test cases follow.Each test is described by two lines.The first line contains an integer n (1 ≀ n ≀ 2000) β€” the number of cards in Borya's present.The second line contains n integers ai (1 ≀ ai ≀ 109) β€” numbers written on the cards.It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.
For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.
Input: 421 131 31 12312345 67 8491 2 3 4 5 6 7 8 9 | Output: 22231680
Expert
3
1,102
489
173
8
13
E
13E
E. Holes
2,700
data structures; dsu
Little Petya likes to play a lot. Most of all he likes to play a game Β«HolesΒ». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.
The first line contains two integers N and M (1 ≀ N ≀ 105, 1 ≀ M ≀ 105) β€” the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N β€” initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.
For each move of the type 1 output two space-separated numbers on a separate line β€” the number of the last hole the ball visited before leaving the row and the number of jumps it made.
Input: 8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2 | Output: 8 78 57 3
Master
2
881
528
184
0
1,023
F
1023F
F. Mobile Phone Network
2,600
dfs and similar; dsu; graphs; trees
You are managing a mobile phone network, and want to offer competitive prices to connect a network.The network has \(n\) nodes.Your competitor has already offered some connections between some nodes, with some fixed prices. These connections are bidirectional. There are initially \(m\) connections the competitor is offering. The \(i\)-th connection your competitor is offering will connect nodes \(fa_i\) and \(fb_i\) and costs \(fw_i\). You have a list of \(k\) connections that you want to offer. It is guaranteed that this set of connection does not form any cycle. The \(j\)-th of these connections will connect nodes \(ga_j\) and \(gb_j\). These connections are also bidirectional. The cost of these connections have not been decided yet.You can set the prices of these connections to any arbitrary integer value. These prices are set independently for each connection. After setting the prices, the customer will choose such \(n - 1\) connections that all nodes are connected in a single network and the total cost of chosen connections is minimum possible. If there are multiple ways to choose such networks, the customer will choose an arbitrary one that also maximizes the number of your connections in it.You want to set prices in such a way such that all your \(k\) connections are chosen by the customer, and the sum of prices of your connections is maximized.Print the maximum profit you can achieve, or \(-1\) if it is unbounded.
The first line of input will contain three integers \(n\), \(k\) and \(m\) (\(1 \leq n, k, m \leq 5 \cdot 10^5, k \leq n-1\)), the number of nodes, the number of your connections, and the number of competitor connections, respectively.The next \(k\) lines contain two integers \(ga_i\) and \(gb_i\) (\(1 \leq ga_i, gb_i \leq n\), \(ga_i \not= gb_i\)), representing one of your connections between nodes \(ga_i\) and \(gb_i\). Your set of connections is guaranteed to be acyclic.The next \(m\) lines contain three integers each, \(fa_i\), \(fb_i\) and \(fw_i\) (\(1 \leq fa_i, fb_i \leq n\), \(fa_i \not= fb_i\), \(1 \leq fw_i \leq 10^9\)), denoting one of your competitor's connections between nodes \(fa_i\) and \(fb_i\) with cost \(fw_i\). None of these connections connects a node to itself, and no pair of these connections connect the same pair of nodes. In addition, these connections are given by non-decreasing order of cost (that is, \(fw_{i-1} \leq fw_i\) for all valid \(i\)).Note that there may be some connections that appear in both your set and your competitor's set (though no connection will appear twice in one of this sets).It is guaranteed that the union of all of your connections and your competitor's connections form a connected network.
Print a single integer, the maximum possible profit you can achieve if you set the prices on your connections appropriately. If the profit is unbounded, print \(-1\).
In the first sample, it's optimal to give connection \(1-3\) cost \(3\), connection \(1-2\) cost \(3\), and connection \(3-4\) cost \(8\). In this case, the cheapest connected network has cost \(14\), and the customer will choose one that chooses all of your connections.In the second sample, as long as your first connection costs \(30\) or less, the customer chooses both your connections no matter what is the cost of the second connection, so you can get unbounded profit in this case.
Input: 4 3 61 23 41 32 3 33 1 41 2 44 2 84 3 84 1 10 | Output: 14
Expert
4
1,445
1,261
166
10
1,250
E
1250E
E. The Coronation
2,300
graphs; implementation
The coronation of King Berl XXII is soon! The whole royal family, including \(n\) daughters of Berl XXII, will be present.The King has ordered his jeweler to assemble \(n\) beautiful necklaces, so each of the princesses could wear exactly one necklace during the ceremony β€” and now these necklaces are finished. Each necklace consists of \(m\) gems attached to a gold chain. There are two types of gems used in the necklaces β€” emeralds and sapphires. So, each necklace can be represented by a sequence of \(m\) gems (listed from left to right), and each gem is either an emerald or a sapphire. Formally, the \(i\)-th necklace can be represented by a binary string \(s_i\) of length \(m\); if the \(j\)-th character of \(s_i\) is 0, then the \(j\)-th gem in the \(i\)-th necklace is an emerald; otherwise, this gem is a sapphire.Now, looking at the necklaces, the King is afraid that some of his daughters may envy the other daughters' necklaces. He wants all necklaces to look similar. Two necklaces are considered similar if there are at least \(k\) positions where these necklaces contain the same type of gems.For example, if there is a necklace represented by a sequence 01010111 and a necklace represented by a sequence 01100000, then there are \(3\) positions where these necklaces contain the same type of gems (both first gems are emeralds, both second gems are sapphires, and both fifth gems are emeralds). So if \(k = 3\), these necklaces are similar, and if \(k = 4\), they are not similar.The King thinks that if two of his daughters notice that their necklaces are not similar, then they may have a conflict β€” and, obviously, he doesn't want any conflicts during the coronation! So Berl XXII wants to tell some of his daughters to wear their necklaces backward. If a necklace is worn backward, then the sequence of gems in this necklace is reversed. For example, if a necklace is represented by a sequence 01100, then, if worn backward, it would be represented by a sequence 00110. The King wants to find the minimum number of necklaces to be worn backward during the coronation so that there are no conflicts.Berl XXII is too busy with preparation for the coronation, so he ordered you to resolve this issue for him. Help him β€” and he will give you a truly royal reward!
The first line contains one integer \(t\) (\(1 \le t \le 50\)) β€” the number of test cases. Then the test cases follow.Each test case begins with a line containing three integers \(n\), \(m\) and \(k\) (\(2 \le n \le 50\), \(1 \le k \le m \le 50\)) β€” the number of necklaces, the number of gems in each necklace, and the minimum number of positions where two necklaces have to have the same type of gems in order to look similar, respectively.Then \(n\) lines follow, the \(i\)-th of them contains a binary string \(s_i\) of length \(m\) representing the \(i\)-th necklace.
For each test case, print the answer as follows.If it is impossible to avoid the conflict, print -1 on a single line. In this case you should not output anything else for that test case.Otherwise, the first line of the test case answer should contain the single integer \(d\) β€” the minimum number of necklaces that are to be worn backward. The second line of the test case answer should contain the numbers of these necklaces (integers from \(1\) to \(n\)) in any order. If \(d = 0\) then leave the second line of the test case answer empty. If there are multiple answers, you may print any of them.
Input: 5 5 7 2 1010100 0010101 1111010 1000010 0000101 6 9 3 011111110 100111000 111100000 000111111 110100111 111110111 3 4 2 0001 1000 0000 3 4 4 0001 1000 0000 2 4 3 0001 1000 | Output: 2 1 3 1 3 0 -1 1 1
Expert
2
2,284
572
599
12
61
B
61B
B. Hard Work
1,300
strings
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include ""-"", "";"" and ""_"". These characters are my own invention of course! And I call them Signs. The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN You should indicate for any of my students if his answer was right or wrong. Do this by writing ""WA"" for Wrong answer or ""ACC"" for a correct answer. I should remind you that none of the strings (initial strings or answers) are empty. Finally, do these as soon as possible. You have less than 2 hours to complete this.
The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs (""-"", "";"" and ""_""). All the initial strings have length from 1 to 100, inclusively.In the fourth line there is a single integer n (0 ≀ n ≀ 1000), the number of students.Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs (""-"", "";"" and ""_""). Length is from 1 to 600, inclusively.
For each student write in a different line. Print ""WA"" if his answer is wrong or ""ACC"" if his answer is OK.
Input: Iran_Persian;W_o;n;d;e;r;f;u;l;7WonderfulPersianIranwonderful_PersIAN_IRAN;;_WONDERFUL___IRAN__PERSIAN__;;Ira__Persiann__WonderfulWonder;;fulPersian___;I;r;a;n;__________IranPersianWonderful__________PersianIran_is_Wonderful | Output: ACCACCACCWAACCACCWA
Easy
1
2,569
570
111
0
1
A
1A
A. Theatre Square
1,000
math
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a.What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
The input contains three positive integer numbers in the first line: n, m and a (1 ≀ n, m, a ≀ 109).
Write the needed number of flagstones.
Input: 6 6 4 | Output: 4
Beginner
1
527
100
38
0
489
C
489C
C. Given Length and Sum of Digits...
1,400
dp; greedy; implementation
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
The single line of the input contains a pair of integers m, s (1 ≀ m ≀ 100, 0 ≀ s ≀ 900) β€” the length and the sum of the digits of the required numbers.
In the output print the pair of the required non-negative integer numbers β€” first the minimum possible number, then β€” the maximum possible number. If no numbers satisfying conditions required exist, print the pair of numbers ""-1 -1"" (without the quotes).
Input: 2 15 | Output: 69 96
Easy
3
269
152
256
4
160
C
160C
C. Find Pair
1,700
implementation; math; sortings
You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≀ i, j ≀ n). In other words, let's consider all n2 pairs of numbers, picked from the given array.For example, in sequence a = {3, 1, 5} are 9 pairs of numbers: (3, 3), (3, 1), (3, 5), (1, 3), (1, 1), (1, 5), (5, 3), (5, 1), (5, 5).Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair (p1, q1) is lexicographically less than pair (p2, q2) only if either p1 < p2, or p1 = p2 and q1 < q2.Then the sequence, mentioned above, will be sorted like that: (1, 1), (1, 3), (1, 5), (3, 1), (3, 3), (3, 5), (5, 1), (5, 3), (5, 5)Let's number all the pair in the sorted list from 1 to n2. Your task is formulated like this: you should find the k-th pair in the ordered list of all possible pairs of the array you've been given.
The first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ n2). The second line contains the array containing n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109). The numbers in the array can coincide. All numbers are separated with spaces.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout, streams or the %I64d specificator instead.
In the single line print two numbers β€” the sought k-th pair.
In the first sample the sorted sequence for the given array looks as: (1, 1), (1, 2), (2, 1), (2, 2). The 4-th of them is pair (2, 2).The sorted sequence for the array from the second sample is given in the statement. The 2-nd pair there is (1, 3).
Input: 2 42 1 | Output: 2 2
Medium
3
973
400
60
1
1,701
C
1701C
C. Schedule Management
1,400
binary search; greedy; implementation; two pointers
There are \(n\) workers and \(m\) tasks. The workers are numbered from \(1\) to \(n\). Each task \(i\) has a value \(a_i\) β€” the index of worker who is proficient in this task.Every task should have a worker assigned to it. If a worker is proficient in the task, they complete it in \(1\) hour. Otherwise, it takes them \(2\) hours.The workers work in parallel, independently of each other. Each worker can only work on one task at once.Assign the workers to all tasks in such a way that the tasks are completed as early as possible. The work starts at time \(0\). What's the minimum time all tasks can be completed by?
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of testcases.The first line of each testcase contains two integers \(n\) and \(m\) (\(1 \le n \le m \le 2 \cdot 10^5\)) β€” the number of workers and the number of tasks.The second line contains \(m\) integers \(a_1, a_2, \dots, a_m\) (\(1 \le a_i \le n\)) β€” the index of the worker proficient in the \(i\)-th task.The sum of \(m\) over all testcases doesn't exceed \(2 \cdot 10^5\).
For each testcase, print a single integer β€” the minimum time all tasks can be completed by.
In the first testcase, the first worker works on tasks \(1\) and \(3\), and the second worker works on tasks \(2\) and \(4\). Since they both are proficient in the corresponding tasks, they take \(1\) hour on each. Both of them complete \(2\) tasks in \(2\) hours. Thus, all tasks are completed by \(2\) hours.In the second testcase, it's optimal to assign the first worker to tasks \(1, 2\) and \(3\) and the second worker to task \(4\). The first worker spends \(3\) hours, the second worker spends \(2\) hours (since they are not proficient in the taken task).In the third example, each worker can be assigned to the task they are proficient at. Thus, each of them complete their task in \(1\) hour.
Input: 42 41 2 1 22 41 1 1 15 55 1 3 2 41 11 | Output: 2 3 1 1
Easy
4
619
464
91
17
1,553
A
1553A
A. Digits Sum
800
math; number theory
Let's define \(S(x)\) to be the sum of digits of number \(x\) written in decimal system. For example, \(S(5) = 5\), \(S(10) = 1\), \(S(322) = 7\).We will call an integer \(x\) interesting if \(S(x + 1) < S(x)\). In each test you will be given one integer \(n\). Your task is to calculate the number of integers \(x\) such that \(1 \le x \le n\) and \(x\) is interesting.
The first line contains one integer \(t\) (\(1 \le t \le 1000\)) β€” number of test cases.Then \(t\) lines follow, the \(i\)-th line contains one integer \(n\) (\(1 \le n \le 10^9\)) for the \(i\)-th test case.
Print \(t\) integers, the \(i\)-th should be the answer for the \(i\)-th test case.
The first interesting number is equal to \(9\).
Input: 5 1 9 10 34 880055535 | Output: 0 1 1 3 88005553
Beginner
2
370
208
83
15
758
B
758B
B. Blown Garland
1,100
brute force; implementation; number theory
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like ""RYBGRYBGRY"", ""YBGRYBGRYBG"", ""BGRYB"", but can not look like ""BGRYG"", ""YBGRYBYGR"" or ""BGYBGY"". Letters denote colors: 'R' β€” red, 'B' β€” blue, 'Y' β€” yellow, 'G' β€” green.Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.
The first and the only line contains the string s (4 ≀ |s| ≀ 100), which describes the garland, the i-th symbol of which describes the color of the i-th light bulb in the order from the beginning of garland: 'R' β€” the light bulb is red, 'B' β€” the light bulb is blue, 'Y' β€” the light bulb is yellow, 'G' β€” the light bulb is green, '!' β€” the light bulb is dead. The string s can not contain other symbols except those five which were described. It is guaranteed that in the given string at least once there is each of four letters 'R', 'B', 'Y' and 'G'. It is guaranteed that the string s is correct garland with some blown light bulbs, it means that for example the line ""GRBY!!!B"" can not be in the input data.
In the only line print four integers kr, kb, ky, kg β€” the number of dead light bulbs of red, blue, yellow and green colors accordingly.
In the first example there are no dead light bulbs.In the second example it is obvious that one blue bulb is blown, because it could not be light bulbs of other colors on its place according to the statements.
Input: RYBGRYBGR | Output: 0 0 0 0
Easy
3
911
712
135
7
1,270
G
1270G
G. Subset with Zero Sum
2,700
constructive algorithms; dfs and similar; graphs; math
You are given \(n\) integers \(a_1, a_2, \dots, a_n\), such that for each \(1\le i \le n\) holds \(i-n\le a_i\le i-1\).Find some nonempty subset of these integers, whose sum is equal to \(0\). It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^6\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1\le n \le 10^6\)).The second line of each test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(i-n \le a_i \le i-1\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
For each test case, output two lines.In the first line, output \(s\) (\(1\le s \le n\)) β€” the number of elements in your subset.In the second line, output \(s\) integers \(i_1, i_2, \dots, i_s\) (\(1\le i_k \le n\)). All integers have to be pairwise different, and \(a_{i_1} + a_{i_2} + \dots + a_{i_s}\) has to be equal to \(0\). If there are several possible subsets with zero-sum, you can find any of them.
In the first example, we get sum is \(a_1 = 0\).In the second example, we get sum is \(a_1 + a_4 + a_3 + a_2 = 0\).
Input: 2 5 0 1 2 3 4 4 -3 1 1 1 | Output: 1 1 4 1 4 3 2
Master
4
338
441
409
12
1,146
G
1146G
G. Zoning Restrictions
2,700
dp; flows; graphs
You are planning to build housing on a street. There are \(n\) spots available on the street on which you can build a house. The spots are labeled from \(1\) to \(n\) from left to right. In each spot, you can build a house with an integer height between \(0\) and \(h\).In each spot, if a house has height \(a\), you can gain \(a^2\) dollars from it.The city has \(m\) zoning restrictions though. The \(i\)-th restriction says that if the tallest house from spots \(l_i\) to \(r_i\) is strictly more than \(x_i\), you must pay a fine of \(c_i\).You would like to build houses to maximize your profit (sum of dollars gained minus fines). Determine the maximum profit possible.
The first line contains three integers \(n,h,m\) (\(1 \leq n,h,m \leq 50\)) β€” the number of spots, the maximum height, and the number of restrictions, respectively.Each of the next \(m\) lines contains four integers \(l_i, r_i, x_i, c_i\) (\(1 \leq l_i \leq r_i \leq n\), \(0 \leq x_i \leq h\), \(1 \leq c_i \leq 5\,000\)).
Print a single integer denoting the maximum profit you can make.
In the first example, it's optimal to build houses with heights \([1, 3, 2]\). We get a gain of \(1^2+3^2+2^2 = 14\). We don't violate any restrictions, so there are no fees, so the total profit is \(14 - 0 = 14\).In the second example, it's optimal to build houses with heights \([10, 8, 8, 10]\). We get a gain of \(10^2+8^2+8^2+10^2 = 328\), and we violate the second restriction for a fee of \(39\), thus the total profit is \(328-39 = 289\). Note that even though there isn't a restriction on building \(1\), we must still limit its height to be at most \(10\).
Input: 3 3 3 1 1 1 1000 2 2 3 1000 3 3 2 1000 | Output: 14
Master
3
675
323
64
11
1,689
D
1689D
D. Lena and Matrix
1,900
data structures; dp; geometry; shortest paths
Lena is a beautiful girl who likes logical puzzles.As a gift for her birthday, Lena got a matrix puzzle!The matrix consists of \(n\) rows and \(m\) columns, and each cell is either black or white. The coordinates \((i,j)\) denote the cell which belongs to the \(i\)-th row and \(j\)-th column for every \(1\leq i \leq n\) and \(1\leq j \leq m\). To solve the puzzle, Lena has to choose a cell that minimizes the Manhattan distance to the farthest black cell from the chosen cell.More formally, let there be \(k \ge 1\) black cells in the matrix with coordinates \((x_i,y_i)\) for every \(1\leq i \leq k\). Lena should choose a cell \((a,b)\) that minimizes $$$\(\max_{i=1}^{k}(|a-x_i|+|b-y_i|).\)$$$As Lena has no skill, she asked you for help. Will you tell her the optimal cell to choose?
There are several test cases in the input data. The first line contains a single integer \(t\) (\(1\leq t\leq 10\,000\)) β€” the number of test cases. This is followed by the test cases description.The first line of each test case contains two integers \(n\) and \(m\) (\(2\leq n,m \leq 1000\)) β€” the dimensions of the matrix. The following \(n\) lines contain \(m\) characters each, each character is either 'W' or 'B'. The \(j\)-th character in the \(i\)-th of these lines is 'W' if the cell \((i,j)\) is white, and 'B' if the cell \((i,j)\) is black. It is guaranteed that at least one black cell exists.It is guaranteed that the sum of \(n\cdot m\) does not exceed \(10^6\).
For each test case, output the optimal cell \((a,b)\) to choose. If multiple answers exist, output any.
In the first test case the two black cells have coordinates \((1,1)\) and \((3,2)\). The four optimal cells are \((1,2)\), \((2,1)\), \((2,2)\) and \((3,1)\). It can be shown that no other cell minimizes the maximum Manhattan distance to every black cell.In the second test case it is optimal to choose the black cell \((2,2)\) with maximum Manhattan distance being \(2\).
Input: 5 3 2 BW WW WB 3 3 WWB WBW BWW 2 3 BBB BBB 5 5 BWBWB WBWBW BWBWB WBWBW BWBWB 9 9 WWWWWWWWW WWWWWWWWW BWWWWWWWW WWWWWWWWW WWWWBWWWW WWWWWWWWW WWWWWWWWW WWWWWWWWW WWWWWWWWB | Output: 2 1 2 2 1 2 3 3 6 5
Hard
4
790
676
103
16
1,648
D
1648D
D. Serious Business
2,800
data structures; divide and conquer; dp; implementation; shortest paths
Dima is taking part in a show organized by his friend Peter. In this show Dima is required to cross a \(3 \times n\) rectangular field. Rows are numbered from \(1\) to \(3\) and columns are numbered from \(1\) to \(n\).The cell in the intersection of the \(i\)-th row and the \(j\)-th column of the field contains an integer \(a_{i,j}\). Initially Dima's score equals zero, and whenever Dima reaches a cell in the row \(i\) and the column \(j\), his score changes by \(a_{i,j}\). Note that the score can become negative.Initially all cells in the first and the third row are marked as available, and all cells in the second row are marked as unavailable. However, Peter offered Dima some help: there are \(q\) special offers in the show, the \(i\)-th special offer allows Dima to mark cells in the second row between \(l_i\) and \(r_i\) as available, though Dima's score reduces by \(k_i\) whenever he accepts a special offer. Dima is allowed to use as many special offers as he wants, and might mark the same cell as available multiple times.Dima starts his journey in the cell \((1, 1)\) and would like to reach the cell \((3, n)\). He can move either down to the next row or right to the next column (meaning he could increase the current row or column by 1), thus making \(n + 1\) moves in total, out of which exactly \(n - 1\) would be horizontal and \(2\) would be vertical.Peter promised Dima to pay him based on his final score, so the sum of all numbers of all visited cells minus the cost of all special offers used. Please help Dima to maximize his final score.
The first input line contains two integers \(n\) and \(q\) (\(1 \le n, q \le 500\,000\)) β€” the number of columns in the field and the number of special offers.The next three lines describe the field, \(i\)-th of them contains \(n\) integers \(a_{i1}\), \(a_{i2}\), ..., \(a_{in}\) (\(-10^9 \le a_{ij} \le 10^9)\) β€” the values in the \(i\)-th row.The next \(q\) lines describe special offers: the \(i\)-th offer is described by 3 integers \(l_i\), \(r_i\) and \(k_i\) (\(1 \leq l_i \leq r_i \leq n\), \(1\leq k_i\leq 10^9\)) β€” the segment that becomes unblocked and the cost of this special offer.
Output one integer β€” the maximum final score Dima can achieve.
In the first example, it is optimal to use Peter's second offer of \(4\) rubles and go through the cells \((1, 1)\), \((1, 2)\), \((1, 3)\), \((2, 3)\), \((3, 3)\), \((3, 4)\), earning \(1 + 0 + 2 + 9 + 4 + 1 - 4 = 13\) rubles in total.In the second example, it is optimal to use Peter's second and third offers of \(2\) and \(3\) rubles, respectively, and go through the cells \((1, 1)\), \((2, 1)\), \((2, 2)\), \((2, 3)\), \((2, 4)\), \((3, 4)\), \((3, 5)\), earning \(-20 + 1 + 3 + 3 + 6 + 6 + 2 - 2 - 3= -4\) rubles.
Input: 4 3 1 0 2 -1 -3 1 9 2 3 2 4 1 1 2 5 2 3 4 1 4 14 | Output: 13
Master
5
1,572
596
62
16
13
B
13B
B. Letter A
2,000
geometry; implementation
Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4).
The first line contains one integer t (1 ≀ t ≀ 10000) β€” the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers β€” coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.
Output one line for each test case. Print Β«YESΒ» (without quotes), if the segments form the letter A and Β«NOΒ» otherwise.
Input: 34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1 | Output: YESNOYES
Hard
2
732
333
119
0
1,762
D
1762D
D. GCD Queries
2,100
constructive algorithms; interactive; number theory
This is an interactive problem.There is a secret permutation \(p\) of \([0,1,2,\ldots,n-1]\). Your task is to find \(2\) indices \(x\) and \(y\) (\(1 \leq x, y \leq n\), possibly \(x=y\)) such that \(p_x=0\) or \(p_y=0\). In order to find it, you are allowed to ask at most \(2n\) queries.In one query, you give two integers \(i\) and \(j\) (\(1 \leq i, j \leq n\), \(i \neq j\)) and receive the value of \(\gcd(p_i,p_j)^\dagger\).Note that the permutation \(p\) is fixed before any queries are made and does not depend on the queries.\(^\dagger\) \(\gcd(x, y)\) denotes the greatest common divisor (GCD) of integers \(x\) and \(y\). Note that \(\gcd(x,0)=\gcd(0,x)=x\) for all positive integers \(x\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 10^4\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(2 \leq n \leq 2 \cdot 10^4\)).After reading the integer \(n\) for each test case, you should begin the interaction.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^4\).
In the first test, the interaction proceeds as follows. SolutionJuryExplanation\(\texttt{2}\)There are 2 test cases.\(\texttt{2}\)In the first test case, the hidden permutation is \([1,0]\), with length \(2\).\(\texttt{? 1 2}\)\(\texttt{1}\)The solution requests \(\gcd(p_1,p_2)\), and the jury responds with \(1\).\(\texttt{! 1 2}\)\(\texttt{1}\)The solution knows that either \(p_1=0\) or \(p_2=0\), and prints the answer. Since the output is correct, the jury responds with \(1\) and continues to the next test case.\(\texttt{5}\)In the second test case, the hidden permutation is \([2,4,0,1,3]\), with length \(5\).\(\texttt{? 1 2}\)\(\texttt{2}\)The solution requests \(\gcd(p_1,p_2)\), and the jury responds with \(2\).\(\texttt{? 2 3}\)\(\texttt{4}\)The solution requests \(\gcd(p_2,p_3)\), and the jury responds with \(4\).\(\texttt{! 3 3}\)\(\texttt{1}\)The solution has somehow determined that \(p_3=0\), and prints the answer. Since the output is correct, the jury responds with \(1\). Note that the empty lines in the example input and output are for the sake of clarity, and do not occur in the real interaction.After each test case, make sure to read \(1\) or \(-1\).
Input: 2 2 1 1 5 2 4 1 | Output: ? 1 2 ! 1 2 ? 1 2 ? 2 3 ! 3 3
Hard
3
702
438
0
17
1,768
C
1768C
C. Elemental Decompress
1,300
constructive algorithms; greedy; implementation; sortings
You are given an array \(a\) of \(n\) integers.Find two permutations\(^\dagger\) \(p\) and \(q\) of length \(n\) such that \(\max(p_i,q_i)=a_i\) for all \(1 \leq i \leq n\) or report that such \(p\) and \(q\) do not exist.\(^\dagger\) A permutation of length \(n\) is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array), and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” 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 2 \cdot 10^5\)).The second line of each test case contains \(n\) integers \(a_1,a_2,\ldots,a_n\) (\(1 \leq a_i \leq n\)) β€” the array \(a\).It is guaranteed that the total sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, if there do not exist \(p\) and \(q\) that satisfy the conditions, output ""NO"" (without quotes).Otherwise, output ""YES"" (without quotes) and then output \(2\) lines. The first line should contain \(n\) integers \(p_1,p_2,\ldots,p_n\) and the second line should contain \(n\) integers \(q_1,q_2,\ldots,q_n\).If there are multiple solutions, you may output any of them.You can output ""YES"" and ""NO"" in any case (for example, strings ""yEs"", ""yes"" and ""Yes"" will be recognized as a positive response).
In the first test case, \(p=q=[1]\). It is correct since \(a_1 = max(p_1,q_1) = 1\).In the second test case, \(p=[1,3,4,2,5]\) and \(q=[5,2,3,1,4]\). It is correct since: \(a_1 = \max(p_1, q_1) = \max(1, 5) = 5\), \(a_2 = \max(p_2, q_2) = \max(3, 2) = 3\), \(a_3 = \max(p_3, q_3) = \max(4, 3) = 4\), \(a_4 = \max(p_4, q_4) = \max(2, 1) = 2\), \(a_5 = \max(p_5, q_5) = \max(5, 4) = 5\). In the third test case, one can show that no such \(p\) and \(q\) exist.
Input: 31155 3 4 2 521 1 | Output: YES 1 1 YES 1 3 4 2 5 5 2 3 1 4 NO
Easy
4
559
453
531
17
1,344
E
1344E
E. Train Tracks
3,100
data structures; trees
That's right. I'm a Purdue student, and I shamelessly wrote a problem about trains.There are \(n\) stations and \(m\) trains. The stations are connected by \(n-1\) one-directional railroads that form a tree rooted at station \(1\). All railroads are pointed in the direction from the root station \(1\) to the leaves. A railroad connects a station \(u\) to a station \(v\), and has a distance \(d\), meaning it takes \(d\) time to travel from \(u\) to \(v\). Each station with at least one outgoing railroad has a switch that determines the child station an incoming train will be directed toward. For example, it might look like this: Here, stations \(1\) and \(3\) have switches directed toward stations \(2\) and \(4\), respectively. Initially, no trains are at any station. Train \(i\) will enter station \(1\) at time \(t_i\). Every unit of time, starting at time \(1\), the following two steps happen: You can switch at most one station to point to a different child station. A switch change takes effect before step \(2\). For every train that is on a station \(u\), it is directed toward the station \(v\) indicated by \(u\)'s switch. So, if the railroad from \(u\) to \(v\) has distance \(d\), the train will enter station \(v\) in \(d\) units of time from now. Every train has a destination station \(s_i\). When it enters \(s_i\), it will stop there permanently. If at some point the train is going in the wrong direction, so that it will never be able to reach \(s_i\) no matter where the switches point, it will immediately explode.Find the latest possible time of the first explosion if you change switches optimally, or determine that you can direct every train to its destination so that no explosion occurs. Also, find the minimum number of times you need to change a switch to achieve this.
The first line contains two integers \(n\) and \(m\) (\(1\le n,m\le 10^5\)) β€” the number of stations and trains, respectively.The next \(n-1\) lines describe the railroads. The \(i\)-th line contains three integers \(u,v,d\) (\(1\le u,v\le n\), \(1\le d\le 10^9\)), denoting a railroad from station \(u\) to station \(v\) with distance \(d\). It is guaranteed that the railroads form a tree rooted at station \(1\). The switch of a station \(u\) is initially directed towards the last outgoing railroad from \(u\) that appears in the input.The next \(m\) lines describe the trains. The \(i\)-th line contains two integers \(s_i,t_i\) (\(1\le s_i\le n\), \(1\le t_1<t_2<\cdots<t_m\le 10^9\)) β€” the destination station and the time the \(i\)-th train enters station \(1\), respectively.
Output two integers: the latest possible time of the first explosion (or \(-1\) if it is possible to never have an explosion) and the minimum number of switch changes to achieve it.
For the first test, here's an example timeline: At time \(1\), train \(1\) enters station \(1\). We switch station \(1\) to point to station \(2\). Train \(1\) is directed to station \(2\). At time \(2\), train \(2\) enters station \(1\), and train \(1\) enters station \(2\), where it stops permanently. We switch station \(1\) to point to station \(3\). Train \(2\) is directed to station \(3\). At time \(4\), train \(2\) enters station \(3\). We switch station \(3\) to point to station \(4\). Train \(2\) is directed to station \(4\). At time \(5\), train \(2\) enters station \(4\), where it stops permanently. At time \(6\), train \(3\) enters station \(1\). We switch station \(1\) to point to station \(2\). Train \(3\) is directed to station \(2\). At time \(7\), train \(3\) enters station \(2\), where it stops permanently. We switch station \(3\) to point to station \(5\). At time \(10\), train \(4\) enters station \(1\). We switch station \(1\) to point to station \(3\). Train \(4\) is directed to station \(3\). At time \(12\), train \(4\) enters station \(3\). Train \(4\) is directed to station \(5\). At time \(15\), train \(4\) enters station \(5\), where it stops permanently. For the second test, we switch nothing. At time \(4\), train \(2\) is directed to station \(5\) and train \(4\) is directed to station \(3\). They both explode. It is impossible to prevent an explosion by time \(4\).For the third test, denote a switch change by \((u\to v,t)\) if we make station \(u\) point to station \(v\) at time \(t\). One solution is to make these \(4\) switch changes: \((1\to 2,1)\),\((1\to 3,2)\),\((7\to 8,5)\),\((5\to 6,8)\). At time \(11\), trains \(4\),\(5\), and \(6\) explode. It is impossible to prevent an explosion by time \(11\).
Input: 5 4 1 2 1 1 3 2 3 4 1 3 5 3 2 1 4 2 2 6 5 10 | Output: -1 6
Master
2
1,808
784
181
13
1,907
F
1907F
F. Shift and Reverse
1,800
greedy; sortings
Given an array of integers \(a_1, a_2, \ldots, a_n\). You can make two types of operations with this array: Shift: move the last element of array to the first place, and shift all other elements to the right, so you get the array \(a_n, a_1, a_2, \ldots, a_{n-1}\). Reverse: reverse the whole array, so you get the array \(a_n, a_{n-1}, \ldots, a_1\). Your task is to sort the array in non-decreasing order using the minimal number of operations, or say that it is impossible.
The first line of input contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. Descriptions of test cases follow.The first line of each test case contains an integer \(n\) (\(1\le n \le 10^5\)) β€” size of the array. The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)) β€” elements of the array.It is guaranteed that sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case output the number \(k\), the minimal number of operations you need to sort the array. If it is impossible to sort the array using these operations, output \(-1\).
In the first test case of the example, to sort the array [\(3, 2, 1, 5, 4\)] you need to perform \(3\) operations: Shift to obtain the array [\(4, 3, 2, 1, 5\)]; Shift to obtain the array [\(5, 4, 3, 2, 1\)]; Reverse to obtain the array [\(1, 2, 3, 4, 5\)]. In the third test case of the example, it can be shown that it is impossible to sort the array using the given operations.In the seventh test case of the example, to sort the array [\(4, 1, 3, 4, 4\)] you need to perform \(3\) operations: Reverse to obtain the array [\(4, 4, 3, 1, 4\)]; Shift to obtain the array [\(4, 4, 4, 3, 1\)]; Reverse to obtain the array [\(1, 3, 4, 4, 4\)].
Input: 1153 2 1 5 451 1 2 1 143 7 10 551 2 3 4 525 133 4 154 1 3 4 435 1 142 5 5 452 2 1 1 225 5 | Output: 3 2 -1 0 1 1 3 1 2 2 0
Medium
2
476
464
181
19
2,057
H
2057H
H. Coffee Break
3,500
data structures; greedy; math
There are very long classes in the T-Generation. In one day, you need to have time to analyze the training and thematic contests, give a lecture with new material, and, if possible, also hold a mini-seminar. Therefore, there is a break where students can go to drink coffee and chat with each other.There are a total of \(n+2\) coffee machines located in sequentially arranged rooms along a long corridor. The coffee machines are numbered from \(0\) to \(n+1\), and immediately after the break starts, there are \(a_i\) students gathered around the \(i\)-th coffee machine.The students are talking too loudly among themselves, and the teachers need to make a very important announcement. Therefore, they want to gather the maximum number of students around some single coffee machine. The teachers are too lazy to run around the corridors and gather the students, so they came up with a more sophisticated way to manipulate them: At any moment, the teachers can choose room \(i\) (\(1 \le i \le n\)) and turn off the lights there; If there were \(x\) students in that room, then after turning off the lights, \(\lfloor \frac12 x \rfloor\) students will go to room \((i-1)\), and \(\lfloor \frac12 x \rfloor\) other students will go to room \((i+1)\). If \(x\) was odd, then one student remains in the same room. After that, the lights in room \(i\) are turned back on. The teachers have not yet decided where they will gather the students, so for each \(i\) from \(1\) to \(n\), you should determine what is the maximum number of students that can be gathered around the \(i\)-th coffee machine.The teachers can turn off the lights in any rooms at their discretion, in any order, possibly turning off the lights in the same room multiple times.Note that the values of \(a_0\) and \(a_{n+1}\) do not affect the answer to the problem, so their values will not be given to you.
The first line contains a single integer \(t\) (\(1 \le t \le 10\,000\)) β€” the number of test cases.In the first line of each test case, there is an integer \(n\) (\(1 \le n \le 10^6\)).In the second line of each test case, there are integers \(a_1, \ldots, a_n\) (\(0 \le a_i \le 10^9\)) β€” the number of students around coffee machines numbered \(1, 2, \ldots, n\).It is guaranteed that the sum of \(n\) across all test cases does not exceed \(10^6\).
For each test case, output \(n\) integers \(b_1, \ldots, b_n\), where \(b_i\) is the maximum number of students that can be around coffee machines number \(i\).
Let's analyze the first test case: To maximize the number of students at the \(1\)-st coffee machine, all that needs to be done is nothing. To maximize the number of students at the \(2\)-nd coffee machine, it is sufficient to turn off the lights in the \(1\)-st room once.
Input: 328 052 2 2 2 250 0 9 0 0 | Output: 8 4 4 5 4 5 4 4 6 9 6 4
Master
3
1,874
452
160
20
240
E
240E
E. Road Repairs
2,800
dfs and similar; graphs; greedy
A country named Berland has n cities. They are numbered with integers from 1 to n. City with index 1 is the capital of the country. Some pairs of cities have monodirectional roads built between them. However, not all of them are in good condition. For each road we know whether it needs repairing or not. If a road needs repairing, then it is forbidden to use it. However, the Berland government can repair the road so that it can be used.Right now Berland is being threatened by the war with the neighbouring state. So the capital officials decided to send a military squad to each city. The squads can move only along the existing roads, as there's no time or money to build new roads. However, some roads will probably have to be repaired in order to get to some cities.Of course the country needs much resources to defeat the enemy, so you want to be careful with what you're going to throw the forces on. That's why the Berland government wants to repair the minimum number of roads that is enough for the military troops to get to any city from the capital, driving along good or repaired roads. Your task is to help the Berland government and to find out, which roads need to be repaired.
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of cities and the number of roads in Berland.Next m lines contain three space-separated integers ai, bi, ci (1 ≀ ai, bi ≀ n, ai β‰  bi, 0 ≀ ci ≀ 1), describing the road from city ai to city bi. If ci equals 0, than the given road is in a good condition. If ci equals 1, then it needs to be repaired.It is guaranteed that there is not more than one road between the cities in each direction.
If even after all roads are repaired, it is still impossible to get to some city from the capital, print - 1. Otherwise, on the first line print the minimum number of roads that need to be repaired, and on the second line print the numbers of these roads, separated by single spaces.The roads are numbered starting from 1 in the order, in which they are given in the input.If there are multiple sets, consisting of the minimum number of roads to repair to make travelling to any city from the capital possible, print any of them.If it is possible to reach any city, driving along the roads that already are in a good condition, print 0 in the only output line.
Input: 3 21 3 03 2 1 | Output: 12
Master
3
1,195
479
660
2
757
G
757G
G. Can Bash Save the Day?
3,400
data structures; divide and conquer; graphs; trees
Whoa! You did a great job helping Team Rocket who managed to capture all the Pokemons sent by Bash. Meowth, part of Team Rocket, having already mastered the human language, now wants to become a master in programming as well. He agrees to free the Pokemons if Bash can answer his questions.Initially, Meowth gives Bash a weighted tree containing n nodes and a sequence a1, a2..., an which is a permutation of 1, 2, ..., n. Now, Mewoth makes q queries of one of the following forms: 1 l r v: meaning Bash should report , where dist(a, b) is the length of the shortest path from node a to node b in the given tree. 2 x: meaning Bash should swap ax and ax + 1 in the given sequence. This new sequence is used for later queries. Help Bash to answer the questions!
The first line contains two integers n and q (1 ≀ n ≀ 2Β·105, 1 ≀ q ≀ 2Β·105) β€” the number of nodes in the tree and the number of queries, respectively.The next line contains n space-separated integers β€” the sequence a1, a2, ..., an which is a permutation of 1, 2, ..., n.Each of the next n - 1 lines contain three space-separated integers u, v, and w denoting that there exists an undirected edge between node u and node v of weight w, (1 ≀ u, v ≀ n, u β‰  v, 1 ≀ w ≀ 106). It is guaranteed that the given graph is a tree.Each query consists of two lines. First line contains single integer t, indicating the type of the query. Next line contains the description of the query: t = 1: Second line contains three integers a, b and c (1 ≀ a, b, c < 230) using which l, r and v can be generated using the formula given below: , , . t = 2: Second line contains single integer a (1 ≀ a < 230) using which x can be generated using the formula given below: . The ansi is the answer for the i-th query, assume that ans0 = 0. If the i-th query is of type 2 then ansi = ansi - 1. It is guaranteed that: for each query of type 1: 1 ≀ l ≀ r ≀ n, 1 ≀ v ≀ n, for each query of type 2: 1 ≀ x ≀ n - 1. The operation means bitwise exclusive OR.
For each query of type 1, output a single integer in a separate line, denoting the answer to the query.
In the sample, the actual queries are the following: 1 1 5 4 1 1 3 3 2 3 2 2 1 1 3 3
Input: 5 54 5 1 3 24 2 41 3 94 1 44 5 211 5 4122 20 20238239136 38 38 | Output: 233728
Master
4
759
1,223
103
7
997
D
997D
D. Cycles in product
2,900
combinatorics; divide and conquer; trees
Consider a tree (that is, an undirected connected graph without loops) \(T_1\) and a tree \(T_2\). Let's define their cartesian product \(T_1 \times T_2\) in a following way.Let \(V\) be the set of vertices in \(T_1\) and \(U\) be the set of vertices in \(T_2\).Then the set of vertices of graph \(T_1 \times T_2\) is \(V \times U\), that is, a set of ordered pairs of vertices, where the first vertex in pair is from \(V\) and the second β€” from \(U\).Let's draw the following edges: Between \((v, u_1)\) and \((v, u_2)\) there is an undirected edge, if \(u_1\) and \(u_2\) are adjacent in \(U\). Similarly, between \((v_1, u)\) and \((v_2, u)\) there is an undirected edge, if \(v_1\) and \(v_2\) are adjacent in \(V\). Please see the notes section for the pictures of products of trees in the sample tests.Let's examine the graph \(T_1 \times T_2\). How much cycles (not necessarily simple) of length \(k\) it contains? Since this number can be very large, print it modulo \(998244353\).The sequence of vertices \(w_1\), \(w_2\), ..., \(w_k\), where \(w_i \in V \times U\) called cycle, if any neighboring vertices are adjacent and \(w_1\) is adjacent to \(w_k\). Cycles that differ only by the cyclic shift or direction of traversal are still considered different.
First line of input contains three integers β€” \(n_1\), \(n_2\) and \(k\) (\(2 \le n_1, n_2 \le 4000\), \(2 \le k \le 75\)) β€” number of vertices in the first tree, number of vertices in the second tree and the cycle length respectively.Then follow \(n_1 - 1\) lines describing the first tree. Each of this lines contains two integers β€” \(v_i, u_i\) (\(1 \le v_i, u_i \le n_1\)), which define edges of the first tree.Then follow \(n_2 - 1\) lines, which describe the second tree in the same format.It is guaranteed, that given graphs are trees.
Print one integer β€” number of cycles modulo \(998244353\).
The following three pictures illustrate graph, which are products of the trees from sample tests.In the first example, the list of cycles of length \(2\) is as follows: Β«ABΒ», Β«BAΒ» Β«BCΒ», Β«CBΒ» Β«ADΒ», Β«DAΒ» Β«CDΒ», Β«DCΒ»
Input: 2 2 21 21 2 | Output: 8
Master
3
1,267
542
58
9
1,718
E
1718E
E. Impressionism
3,500
constructive algorithms; graphs; implementation; math
Burenka has two pictures \(a\) and \(b\), which are tables of the same size \(n \times m\). Each cell of each painting has a color β€” a number from \(0\) to \(2 \cdot 10^5\), and there are no repeating colors in any row or column of each of the two paintings, except color \(0\).Burenka wants to get a picture \(b\) from the picture \(a\). To achieve her goal, Burenka can perform one of \(2\) operations: swap any two rows of \(a\) or any two of its columns. Tell Burenka if she can fulfill what she wants, and if so, tell her the sequence of actions.The rows are numbered from \(1\) to \(n\) from top to bottom, the columns are numbered from \(1\) to \(m\) from left to right.
The first line contains two integers \(n\) and \(m\) (\(1 \leq n \cdot m \leq 2 \cdot 10^5\)) β€” the sizes of the table.The \(i\)-th of the next \(n\) lines contains \(m\) integers \(a_{i, 1}, a_{i, 2}, \ldots, a_{i, m}\) (\(0 \leq a_{i,j} \leq 2 \cdot 10^5\)) β€” the colors of the \(i\)-th row of picture \(a\). It is guaranteed that there are no identical colors in the same row or column, except color \(0\).The \(i\)-th of the following \(n\) lines contains \(m\) integers \(b_{i, 1}, b_{i, 2}, \ldots, b_{i, m}\) (\(0 \leq b_{i,j} \leq 2 \cdot 10^5\)) β€” the colors of the \(i\)-th row of picture \(b\). It is guaranteed that there are no identical colors in the same row or column, except color \(0\).
In the first line print the number \(-1\) if it is impossible to achieve what Burenka wants, otherwise print the number of actions in your solution \(k\) (\(0 \le k \le 2 \cdot 10^5\)). It can be proved that if a solution exists, then there exists a solution where \(k \le 2 \cdot 10^5\).In the next \(k\) lines print the operations. First print the type of the operation (\(1\) β€” swap rows, \(2\) β€” columns), and then print the two indices of rows or columns to which the operation is applied.Note that you don't have to minimize the number of operations.
Input: 3 3 1 0 2 0 0 0 2 0 1 2 0 1 0 0 0 1 0 2 | Output: 1 1 1 3
Master
4
677
704
556
17
1,845
B
1845B
B. Come Together
900
geometry; implementation; math
Bob and Carol hanged out with Alice the whole day, but now it's time to go home. Alice, Bob and Carol live on an infinite 2D grid in cells \(A\), \(B\), and \(C\) respectively. Right now, all of them are in cell \(A\).If Bob (or Carol) is in some cell, he (she) can move to one of the neighboring cells. Two cells are called neighboring if they share a side. For example, the cell \((3, 5)\) has four neighboring cells: \((2, 5)\), \((4, 5)\), \((3, 6)\) and \((3, 4)\).Bob wants to return to the cell \(B\), Carol β€” to the cell \(C\). Both of them want to go along the shortest path, i. e. along the path that consists of the minimum possible number of cells. But they would like to walk together as well. What is the maximum possible number of cells that Bob and Carol can walk together if each of them walks home using one of the shortest paths?
The first line contains the single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first line of each test case contains two integers \(x_A\) and \(y_A\) (\(1 \le x_A, y_A \le 10^8\)) β€” the position of cell \(A\), where both Bob and Carol are right now.The second line contains two integers \(x_B\) and \(y_B\) (\(1 \le x_B, y_B \le 10^8\)) β€” the position of cell \(B\) (Bob's house).The third line contains two integers \(x_C\) and \(y_C\) (\(1 \le x_C, y_C \le 10^8\)) β€” the position of cell \(C\) (Carol's house).Additional constraint on the input: the cells \(A\), \(B\), and \(C\) are pairwise distinct in each test case.
For each test case, print the single integer β€” the maximum number of cells Bob and Carol can walk together if each of them goes home along one of the shortest paths.
In all pictures, red color denotes cells belonging only to Bob's path, light blue color β€” cells belonging only to Carol's path, and dark blue color β€” cells belonging to both paths.One of the optimal routes for the first test case is shown below: Bob's route contains \(5\) cells, Carol's route β€” \(7\) cells, and they will visit \(3\) cells together.The optimal answer for the second test case is shown below: Bob's route contains \(4\) cells, Carol's route β€” \(3\) cells, and they will visit only \(1\) cell together.One of the optimal answers for the third test case is shown below: Bob's route contains \(6\) cells, Carol's route β€” \(9\) cells, and they will visit \(6\) cells together.
Input: 33 11 36 45 22 27 21 14 35 5 | Output: 3 1 6
Beginner
3
848
646
165
18
1,970
A3
1970A3
A3. Balanced Unshuffle (Hard)
2,400
constructive algorithms; trees
The only difference with the medium version is the maximum length of the input.A parentheses sequence is a string consisting of characters ""("" and "")"", for example ""(()(("".A balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and operations into it, for example ""(()(()))"".The balance of a parentheses sequence is defined as the number of opening parentheses ""("" minus the number of closing parentheses "")"". For example, the balance of the sequence ""(()(("" is 3.A balanced parentheses sequence can also be defined as a parentheses sequence with balance 0 such that each of its prefixes has a non-negative balance.We define the balanced shuffle operation that takes a parentheses sequence and returns a parentheses sequence as follows: first, for every character of the input sequence, we compute the balance of the prefix of the sequence before that character and write those down in a table together with the positions of the characters in the input sequence, for example:Prefix balance01212321Position12345678Character(()(()))Then, we sort the columns of this table in increasing order of prefix balance, breaking ties in decreasing order of position. In the above example, we get:Prefix balance01112223Position18427536Character()(()())The last row of this table forms another parentheses sequence, in this case ""()(()())"". This sequence is called the result of applying the balanced shuffle operation to the input sequence, or in short just the balanced shuffle of the input sequence.Surprisingly, it turns out that the balanced shuffle of any balanced parentheses sequence is always another balanced parentheses sequence (we will omit the proof for brevity). Even more surprisingly, the balanced shuffles of two different balanced parentheses sequences are always different, therefore the balanced shuffle operation is a bijection on the set of balanced parentheses sequences of any given length (we will omit this proof, too).You are given a balanced parentheses sequence. Find its preimage: the balanced parentheses sequence the balanced shuffle of which is equal to the given sequence.
The only line of input contains a string \(s\) consisting only of characters ""("" and "")"". This string is guaranteed to be a non-empty balanced parentheses sequence with its length not exceeding \(500\,000\).
Print the balanced parentheses sequence \(t\) such that the balanced shuffle of \(t\) is equal to \(s\). It is guaranteed that the answer always exists and is unique.
Input: ()(()()) | Output: (()(()))
Expert
2
2,185
211
166
19
1,207
E
1207E
E. XOR Guessing
1,900
bitmasks; interactive; math
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury picked an integer \(x\) not less than \(0\) and not greater than \(2^{14} - 1\). You have to guess this integer.To do so, you may ask no more than \(2\) queries. Each query should consist of \(100\) integer numbers \(a_1\), \(a_2\), ..., \(a_{100}\) (each integer should be not less than \(0\) and not greater than \(2^{14} - 1\)). In response to your query, the jury will pick one integer \(i\) (\(1 \le i \le 100\)) and tell you the value of \(a_i \oplus x\) (the bitwise XOR of \(a_i\) and \(x\)). There is an additional constraint on the queries: all \(200\) integers you use in the queries should be distinct.It is guaranteed that the value of \(x\) is fixed beforehand in each test, but the choice of \(i\) in every query may depend on the integers you send.
To give the answer, your program should print one line \(!\) \(x\) with a line break in the end. After that, it should flush the output and terminate gracefully.
The example of interaction is not correct β€” you should sumbit exactly \(100\) integers in each query. Everything else is correct.Hacks are forbidden in this problem.
Input: 0 32 | Output: ? 3 5 6 ? 32 24 37 ! 5
Hard
3
1,185
0
161
12
1,847
E
1847E
E. Triangle Platinum?
2,900
brute force; combinatorics; implementation; interactive; math; probabilities
This is an interactive problem.Made in Heaven is a rather curious Stand. Of course, it is (arguably) the strongest Stand in existence, but it is also an ardent puzzle enjoyer. For example, it gave Qtaro the following problem recently:Made in Heaven has \(n\) hidden integers \(a_1, a_2, \dots, a_n\) (\(3 \le n \le 5000\), \(1 \le a_i \le 4\)). Qtaro must determine all the \(a_i\) by asking Made in Heaven some queries of the following form: In one query Qtaro is allowed to give Made in Heaven three distinct indexes \(i\), \(j\) and \(k\) (\(1 \leq i, j, k \leq n\)). If \(a_i, a_j, a_k\) form the sides of a non-degenerate triangle\(^\dagger\), Made in Heaven will respond with the area of this triangle. Otherwise, Made in Heaven will respond with \(0\). By asking at most \(5500\) such questions, Qtaro must either tell Made in Heaven all the values of the \(a_i\), or report that it is not possible to uniquely determine them.Unfortunately due to the universe reboot, Qtaro is not as smart as Jotaro. Please help Qtaro solve Made In Heaven's problem. β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” \(^\dagger\) Three positive integers \(a, b, c\) are said to form the sides of a non-degenerate triangle if and only if all of the following three inequalities hold: \(a+b > c\), \(b+c > a\), \(c+a > b\).
In the first example, the interaction process happens as follows: StdinStdoutExplanation3Read \(n = 3\). There are \(3\) hidden integers? 1 2 3Ask for the area formed by \(a_1\), \(a_2\) and \(a_3\)63Received \(16\Delta^2 = 63\). So the area \(\Delta = \sqrt{\frac{63}{16}} \approx 1.984313\)! -1Answer that there is no unique array satisfying the queries. From the area received, we can deduce that the numbers that forms the triangle are either (\(4\), \(4\), \(1\)) or (\(3\), \(2\), \(2\)) (in some order). As there are multiple arrays of numbers that satisfy the queries, a unique answer cannot be found.In the second example, the interaction process happens as follows: StepStdinStdoutExplanation16Read \(n = 6\). There are \(6\) hidden integers2? 1 2 3Ask for the area formed by \(a_1\), \(a_2\) and \(a_3\)30Does not form a non-degenerate triangle4? 2 3 4Ask for the area formed by \(a_2\), \(a_3\) and \(a_4\)50Does not form a non-degenerate triangle6? 4 5 6Ask for the area formed by \(a_4\), \(a_5\) and \(a_6\)70Does not form a non-degenerate triangle8? 1 5 6Ask for the area formed by \(a_1\), \(a_5\) and \(a_6\)963Received \(16\Delta^2 = 63\). So the area \(\Delta = \sqrt{\frac{63}{16}} \approx 1.984313\)10? 3 5 6Ask for the area formed by \(a_3\), \(a_5\) and \(a_6\)1115Received \(16\Delta^2 = 15\). So the area \(\Delta = \sqrt{\frac{15}{16}} \approx 0.968245\)12? 1 2 4Ask for the area formed by \(a_3\), \(a_5\) and \(a_6\)13135Received \(16\Delta^2 = 135\). So the area \(\Delta = \sqrt{\frac{135}{16}} \approx 2.904738\)14! 3 2 1 4 2 2A unique answer is found, which is \(a = [3, 2, 1, 4, 2, 2]\). From steps \(10\) and \(11\), we can deduce that the the multiset \(\left\{a_3, a_5, a_6\right\}\) must be \(\left\{2, 2, 1\right\}\).From steps \(8\) and \(9\), the multiset \(\left\{a_1, a_5, a_6\right\}\) must be either \(\left\{4, 4, 1\right\}\) or \(\left\{3, 2, 2\right\}\).As \(\left\{a_3, a_5, a_6\right\}\) and \(\left\{a_1, a_5, a_6\right\}\) share \(a_5\) and \(a_6\), we conclude that \(a_5 = a_6 = 2\), as well as \(a_1 = 3\), \(a_3 = 1\).From steps \(6\) and \(7\), we know that \(a_5 = a_6 = 2\), and \(a_4\), \(a_5\) and \(a_6\) cannot form a non-degenerate triangle, hence \(a_4 = 4\).With all the known information, only \(a_2 = 2\) satisfies the queries made in steps \(2\), \(3\), \(4\), \(5\), \(12\) and \(13\).In the third example, one array that satisfies the queries is \([1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\).
Input: 3 63 | Output: ? 1 2 3 ! -1
Master
6
1,285
0
0
18
536
E
536E
E. Tavas on the Path
3,100
data structures; divide and conquer; trees
Tavas lives in Tavaspolis. Tavaspolis has n cities numbered from 1 to n connected by n - 1 bidirectional roads. There exists a path between any two cities. Also each road has a length. Tavas' favorite strings are binary strings (they contain only 0 and 1). For any binary string like s = s1s2... sk, T(s) is its Goodness. T(s) can be calculated as follows:Consider there are exactly m blocks of 1s in this string (a block of 1s in s is a maximal consecutive substring of s that only contains 1) with lengths x1, x2, ..., xm.Define where f is a given sequence (if m = 0, then T(s) = 0).Tavas loves queries. He asks you to answer q queries. In each query he gives you numbers v, u, l and you should print following number:Consider the roads on the path from city v to city u: e1, e2, ..., ex.Build the binary string b of length x such that: bi = 1 if and only if l ≀ w(ei) where w(e) is the length of road e.You should print T(b) for this query.
The first line of input contains integers n and q (2 ≀ n ≀ 105 and 1 ≀ q ≀ 105).The next line contains n - 1 space separated integers f1, f2, ..., fn - 1 (|fi| ≀ 1000).The next n - 1 lines contain the details of the roads. Each line contains integers v, u and w and it means that there's a road between cities v and u of length w (1 ≀ v, u ≀ n and 1 ≀ w ≀ 109).The next q lines contain the details of the queries. Each line contains integers v, u, l (1 ≀ v, u ≀ n, v β‰  u and 1 ≀ l ≀ 109).
Print the answer of each query in a single line.
Input: 2 3101 2 31 2 21 2 31 2 4 | Output: 10100
Master
3
943
488
48
5
1,109
C
1109C
C. Sasha and a Patient Friend
2,800
binary search; data structures; implementation
Fedya and Sasha are friends, that's why Sasha knows everything about Fedya.Fedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let \(v\) be the number of liters of Fedya's patience, and, as soon as \(v\) becomes equal to \(0\), the bowl will burst immediately. There is one tap in the bowl which pumps \(s\) liters of patience per second. Notice that \(s\) can be negative, in that case, the tap pumps out the patience. Sasha can do different things, so he is able to change the tap's speed. All actions that Sasha does can be represented as \(q\) queries. There are three types of queries: ""1 t s"" β€” add a new event, means that starting from the \(t\)-th second the tap's speed will be equal to \(s\). ""2 t"" β€” delete the event which happens at the \(t\)-th second. It is guaranteed that such event exists. ""3 l r v"" β€” Sasha wonders: if you take all the events for which \(l \le t \le r\) and simulate changes of Fedya's patience from the very beginning of the \(l\)-th second till the very beginning of the \(r\)-th second inclusive (the initial volume of patience, at the beginning of the \(l\)-th second, equals to \(v\) liters) then when will be the moment when the bowl will burst. If that does not happen, then the answer will be \(-1\). Since Sasha does not want to check what will happen when Fedya's patience ends, and he has already come up with the queries, he is asking you to help him and find the answer for each query of the \(3\)-rd type.It is guaranteed that at any moment of time, there won't be two events which happen at the same second.
The first line contans one integer \(q\) (\(1 \le q \le 10^5\)) β€” the number of queries.Each of the next \(q\) lines have one of the following formats: 1 t s (\(1 \le t \le 10^9\), \(-10^9 \le s \le 10^9\)), means that a new event is added, which means that starting from the \(t\)-th second the tap's speed will be equal to \(s\). 2 t (\(1 \le t \le 10^9\)), means that the event which happens at the \(t\)-th second must be deleted. Guaranteed that such exists. 3 l r v (\(1 \le l \le r \le 10^9\), \(0 \le v \le 10^9\)), means that you should simulate the process from the very beginning of the \(l\)-th second till the very beginning of the \(r\)-th second inclusive, and to say when will the bowl burst. It is guaranteed that \(t\), \(s\), \(l\), \(r\), \(v\) in all the queries are integers.Also, it is guaranteed that there is at least one query of the \(3\)-rd type, and there won't be a query of the \(1\)-st type with such \(t\), that there already exists an event which happens at that second \(t\).
For each query of the \(3\)-rd type, print in a new line the moment when the bowl will burst or print \(-1\) if it won't happen.Your answer will be considered correct if it's absolute or relative error does not exceed \(10^{-6}\).Formally, let your answer be \(a\), and the jury's answer be \(b\). Your answer is accepted if and only if \(\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}\).
In the first example all the queries of the \(3\)-rd type cover all the events, it's simulation is following:
Input: 6 1 2 1 1 4 -3 3 1 6 1 3 1 6 3 3 1 6 4 3 1 6 5 | Output: 5 5.666667 6 -1
Master
3
1,632
1,010
384
11
348
D
348D
D. Turtles
2,500
dp; matrices
You've got a table of size n Γ— m. We'll consider the table rows numbered from top to bottom 1 through n, and the columns numbered from left to right 1 through m. Then we'll denote the cell in row x and column y as (x, y).Initially cell (1, 1) contains two similar turtles. Both turtles want to get to cell (n, m). Some cells of the table have obstacles but it is guaranteed that there aren't any obstacles in the upper left and lower right corner. A turtle (one or the other) can go from cell (x, y) to one of two cells (x + 1, y) and (x, y + 1), as long as the required cell doesn't contain an obstacle. The turtles have had an argument so they don't want to have any chance of meeting each other along the way. Help them find the number of ways in which they can go from cell (1, 1) to cell (n, m).More formally, find the number of pairs of non-intersecting ways from cell (1, 1) to cell (n, m) modulo 1000000007 (109 + 7). Two ways are called non-intersecting if they have exactly two common points β€” the starting point and the final point.
The first line contains two integers n, m (2 ≀ n, m ≀ 3000). Each of the following n lines contains m characters describing the table. The empty cells are marked by characters ""."", the cells with obstacles are marked by ""#"".It is guaranteed that the upper left and the lower right cells are empty.
In a single line print a single integer β€” the number of pairs of non-intersecting paths from cell (1, 1) to cell (n, m) modulo 1000000007 (109 + 7).
Input: 4 5......###..###...... | Output: 1
Expert
2
1,043
301
148
3
1,909
G
1909G
G. Pumping Lemma
3,000
hashing; strings
Tanchiky & Siromaru - Crystal Gravityβ €You are given two strings \(s\), \(t\) of length \(n\), \(m\), respectively. Both strings consist of lowercase letters of the English alphabet.Count the triples \((x, y, z)\) of strings such that the following conditions are true: \(s = x+y+z\) (the symbol \(+\) represents the concatenation); \(t = x+\underbrace{ y+\dots+y }_{k \text{ times}} + z\) for some integer \(k\).
The first line contains two integers \(n\) and \(m\) (\(1 \leq n < m \leq 10^7\)) β€” the length of the strings \(s\) and \(t\), respectively.The second line contains the string \(s\) of length \(n\), consisting of lowercase letters of the English alphabet.The third line contains the string \(t\) of length \(m\), consisting of lowercase letters of the English alphabet.
Output a single integer: the number of valid triples \((x, y, z)\).
In the first test case, the only valid triple is \((x, y, z) = (\texttt{""a""}, \texttt{""bc""}, \texttt{""d""})\). In fact, \(\texttt{""abcd""} = \texttt{""a""} + \texttt{""bc""} + \texttt{""d""}\); \(\texttt{""abcbcbcd""} = \texttt{""a""} + \texttt{""bc""} + \texttt{""bc""} + \texttt{""bc""} + \texttt{""d""}\). In the second test case, there are \(5\) valid triples: \((x, y, z) = (\texttt{""""}, \texttt{""a""}, \texttt{""aa""})\); \((x, y, z) = (\texttt{""""}, \texttt{""aa""}, \texttt{""a""})\); \((x, y, z) = (\texttt{""a""}, \texttt{""a""}, \texttt{""a""})\); \((x, y, z) = (\texttt{""a""}, \texttt{""aa""}, \texttt{""""})\); \((x, y, z) = (\texttt{""aa""}, \texttt{""a""}, \texttt{""""})\). In the third test case, there are \(8\) valid triples: \((x, y, z) = (\texttt{""ab""}, \texttt{""ba""}, \texttt{""babacaab""})\); \((x, y, z) = (\texttt{""abb""}, \texttt{""ab""}, \texttt{""abacaab""})\); \((x, y, z) = (\texttt{""abba""}, \texttt{""ba""}, \texttt{""bacaab""})\); \((x, y, z) = (\texttt{""ab""}, \texttt{""baba""}, \texttt{""bacaab""})\); \((x, y, z) = (\texttt{""abbab""}, \texttt{""ab""}, \texttt{""acaab""})\); \((x, y, z) = (\texttt{""abb""}, \texttt{""abab""}, \texttt{""acaab""})\); \((x, y, z) = (\texttt{""abbaba""}, \texttt{""ba""}, \texttt{""caab""})\); \((x, y, z) = (\texttt{""abba""}, \texttt{""baba""}, \texttt{""caab""})\).
Input: 4 8abcdabcbcbcd | Output: 1
Master
2
412
369
67
19
427
B
427B
B. Prison Transfer
1,100
data structures; implementation
The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are, The chosen c prisoners has to form a contiguous segment of prisoners. Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.
The first line of input will contain three space separated integers n (1 ≀ n ≀ 2Β·105), t (0 ≀ t ≀ 109) and c (1 ≀ c ≀ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.
Print a single integer β€” the number of ways you can choose the c prisoners.
Input: 4 3 32 3 1 1 | Output: 2
Easy
2
875
306
75
4
717
H
717H
H. Pokermon League challenge
2,400
math; probabilities
Welcome to the world of Pokermon, yellow little mouse-like creatures, who absolutely love playing poker! Yeah, right… In the ensuing Pokermon League, there are n registered Pokermon trainers, and t existing trainer teams each of which belongs to one of two conferences. Since there is a lot of jealousy between trainers, there are e pairs of trainers who hate each other. Their hate is mutual, there are no identical pairs among these, and no trainer hates himself (the world of Pokermon is a joyful place!). Each trainer has a wish-list of length li of teams he’d like to join.Your task is to divide players into teams and the teams into two conferences, so that: each trainer belongs to exactly one team; no team is in both conferences; total hate between conferences is at least e / 2; every trainer is in a team from his wish-list. Total hate between conferences is calculated as the number of pairs of trainers from teams from different conferences who hate each other.
The first line of the input contains two integer n (4 ≀ n ≀ 50 000) and e (2 ≀ e ≀ 100 000) β€” the total number of Pokermon trainers and the number of pairs of trainers who hate each other.Pokermon trainers are numbered from 1 to n. Next e lines contain two integers a and b (1 ≀ a, b ≀ n) indicating that Pokermon trainers a and b hate each other. Next 2n lines are in a following format. Starting with Pokermon trainer 1, for each trainer in consecutive order: first number li (16 ≀ li ≀ 20) β€” a size of Pokermon trainers wish list, then li positive integers ti, j (1 ≀ ti, j ≀ T), providing the teams the i-th trainer would like to be on.Each trainers wish list will contain each team no more than once. Teams on the wish lists are numbered in such a way that the set of all teams that appear on at least 1 wish list is set of consecutive positive integers {1, 2, 3, …, T}. Here T might be up to 1 000 000.
Print two lines. The first line should contain n numbers, specifying for each trainer the team he is in.The second line should contain T numbers, specifying the conference for each team (1 or 2).
Input: 4 31 22 34 1161 2 3 4 5 6 7 8 9 10 11 12 13 14 16 15162 3 4 5 6 7 8 9 10 11 12 13 14 15 17 18162 3 4 5 6 7 8 9 10 11 12 13 14 15 18 19161 2 3 4 5 6 7 8 9 10 11 12 13 14 16 19 | Output: 16 15 19 14 2 2 2 1 1 1 2 1 1 2 1 1 1 2 2 1 1 1 1
Expert
2
974
908
195
7
66
C
66C
C. Petya and File System
1,800
data structures; implementation
Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested folders, and so on) and what folder contains most files (including the files in the subfolders).More formally, the subfolders of the folder are all its directly nested folders and the subfolders of these nested folders. The given folder is not considered the subfolder of itself. A file is regarded as lying in a folder, if and only if it either lies directly in this folder, or lies in some subfolder of the folder.For a better understanding of how to count subfolders and files for calculating the answer, see notes and answers to the samples.You are given a few files that Petya has managed to create. The path to each file looks as follows:diskName:\folder1\folder2\...\ foldern\fileName diskName is single capital letter from the set {C,D,E,F,G}. folder1, ..., foldern are folder names. Each folder name is nonempty sequence of lowercase Latin letters and digits from 0 to 9. (n β‰₯ 1) fileName is a file name in the form of name.extension, where the name and the extension are nonempty sequences of lowercase Latin letters and digits from 0 to 9. It is also known that there is no file whose path looks like diskName:\fileName. That is, each file is stored in some folder, but there are no files directly in the root. Also let us assume that the disk root is not a folder.Help Petya to find the largest number of subfolders, which can be in some folder, and the largest number of files that can be in some folder, counting all its subfolders.
Each line of input data contains the description of one file path. The length of each line does not exceed 100, and overall there are no more than 100 lines. It is guaranteed, that all the paths are correct and meet the above rules. It is also guaranteed, that there are no two completely equal lines. That is, each file is described exactly once.There is at least one line in the input data.
Print two space-separated numbers. The first one is the maximal number of possible subfolders in a folder (including nested folders, nested folders of nested folders, and so on). The second one is the maximal number of files in a folder (including nested files in subfolders). Note that the disks are not regarded as folders.
In the first sample we have one folder on the ""C"" disk. It has no subfolders, which is why the first number in the answer is 0. But this folder contains one file, so the second number of the answer is 1.In the second sample we have several different folders. Consider the ""folder1"" folder on the ""C"" disk. This folder directly contains one folder, ""folder2"". The ""folder2"" folder contains two more folders β€” ""folder3"" and ""folder4"". Thus, the ""folder1"" folder on the ""C"" drive has exactly 3 subfolders. Also this folder contains two files, even though they do not lie directly in the folder, but they are located in subfolders of ""folder1"".In the third example we see that the names of some folders and some subfolders are identical. Consider the ""file"" folder, which lies directly on the ""C"" disk. That folder contains another ""file"" folder, which in turn contains another ""file"" folder, which contains two more folders, ""file"" and ""file2"". Thus, the ""file"" folder, which lies directly on the ""C"" disk, contains 4 subfolders.
Input: C:\folder1\file1.txt | Output: 0 1
Medium
2
1,764
392
325
0
954
F
954F
F. Runner's Problem
2,100
dp; matrices; sortings
You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column.You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to: (i - 1, j + 1) β€” only if i > 1, (i, j + 1), or (i + 1, j + 1) β€” only if i < 3. However, there are n obstacles blocking your path. k-th obstacle is denoted by three integers ak, lk and rk, and it forbids entering any cell (ak, j) such that lk ≀ j ≀ rk.You have to calculate the number of different paths from (2, 1) to (2, m), and print it modulo 109 + 7.
The first line contains two integers n and m (1 ≀ n ≀ 104, 3 ≀ m ≀ 1018) β€” the number of obstacles and the number of columns in the matrix, respectively.Then n lines follow, each containing three integers ak, lk and rk (1 ≀ ak ≀ 3, 2 ≀ lk ≀ rk ≀ m - 1) denoting an obstacle blocking every cell (ak, j) such that lk ≀ j ≀ rk. Some cells may be blocked by multiple obstacles.
Print the number of different paths from (2, 1) to (2, m), taken modulo 109 + 7. If it is impossible to get from (2, 1) to (2, m), then the number of paths is 0.
Input: 2 51 3 42 2 3 | Output: 2
Hard
3
626
373
161
9
2,070
E
2070E
E. Game with Binary String
2,200
constructive algorithms; data structures; divide and conquer; games; greedy; math
Consider the following game. Two players have a binary string (a string consisting of characters 0 and/or 1). The players take turns, the first player makes the first turn. During a player's turn, he or she has to choose exactly two adjacent elements of the string and remove them (the first element and the last element are also considered adjacent). Furthermore, there are additional constraints depending on who makes the move: if it's the first player's move, both chosen characters should be 0; if it's the second player's move, at least one of the chosen characters should be 1. The player who can't make a valid move loses the game. This also means that if the string currently has less than \(2\) characters, the current player loses the game.You are given a binary string \(s\) of length \(n\). You have to calculate the number of its substrings such that, if the game is played on that substring and both players make optimal decisions, the first player wins. In other words, calculate the number of pairs \((l, r)\) such that \(1 \le l \le r \le n\) and the first player has a winning strategy on the string \(s_l s_{l+1} \dots s_r\).
The first line contains one integer \(n\) (\(1 \le n \le 3 \cdot 10^5\)).The second line contains the string \(s\), consisting of exactly \(n\) characters. Each character of the string is either 0 or 1.
Print one integer β€” the number of substrings such that, if the game is played on that substring, the first player wins.
In the first example, the following substrings are winning for the first player (\(s[l:r]\) denotes \(s_l s_{l+1} \dots s_r\)): \(s[1:2]\); \(s[1:3]\); \(s[1:7]\); \(s[2:4]\); \(s[2:8]\); \(s[3:5]\); \(s[4:5]\); \(s[4:6]\); \(s[5:7]\); \(s[6:8]\); \(s[7:8]\); \(s[7:9]\).
Input: 100010010011 | Output: 12
Hard
6
1,145
202
119
20
285
E
285E
E. Positions in Permutations
2,600
combinatorics; dp; math
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.We'll call position i (1 ≀ i ≀ n) in permutation p1, p2, ..., pn good, if |p[i] - i| = 1. Count the number of permutations of size n with exactly k good positions. Print the answer modulo 1000000007 (109 + 7).
The single line contains two space-separated integers n and k (1 ≀ n ≀ 1000, 0 ≀ k ≀ n).
Print the number of permutations of length n with exactly k good positions modulo 1000000007 (109 + 7).
The only permutation of size 1 has 0 good positions.Permutation (1, 2) has 0 good positions, and permutation (2, 1) has 2 positions.Permutations of size 3: (1, 2, 3) β€” 0 positions β€” 2 positions β€” 2 positions β€” 2 positions β€” 2 positions (3, 2, 1) β€” 0 positions
Input: 1 0 | Output: 1
Expert
3
473
88
103
2
569
A
569A
A. Music
1,500
implementation; math
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.Tell Lesha, for how many times he will start the song, including the very first start.
The single line contains three integers T, S, q (2 ≀ q ≀ 104, 1 ≀ S < T ≀ 105).
Print a single integer β€” the number of times the song will be restarted.
In the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.In the second test, the song is almost downloaded, and Lesha will start it only once.In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case.
Input: 5 2 2 | Output: 2
Medium
2
911
79
72
5
225
D
225D
D. Snake
2,200
bitmasks; dfs and similar; graphs; implementation
Let us remind you the rules of a very popular game called ""Snake"" (or sometimes ""Boa"", ""Python"" or ""Worm"").The game field is represented by an n Γ— m rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable.You control a snake, the snake consists of segments. Each segment takes up exactly one passable square of the field, but any passable square contains at most one segment. All segments are indexed by integers from 1 to k, where k is the snake's length. The 1-th segment is the head and the k-th segment is the tail. For any i (1 ≀ i < k), segments with indexes i and i + 1 are located in the adjacent squares of the field, that is, these squares share a common side.One of the passable field squares contains an apple. The snake's aim is to reach the apple and eat it (that is, to position its head in the square with the apple).The snake moves throughout the game. During one move the snake can move its head to an adjacent field square. All other segments follow the head. That is, each segment number i (1 < i ≀ k) moves to the square that has just had segment number i - 1. Consider that all segments including the head move simultaneously (see the second test sample). If the snake's head moves to an unpassable square or to the square, occupied by its other segment, the snake dies. That's why we will consider such moves unvalid.Your task is to determine the minimum number of valid moves that the snake needs to reach the apple.
The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 15) β€” the number of rows and columns of the game field.Next n lines describe the game field. Each of these lines contains m characters. Character ""#"" represents a wall, ""."" is a passable square, ""@"" is an apple. The snake's first segment is represented by character ""1"", the second one segment β€” by character ""2"" and so on.The game field description doesn't contain any characters besides ""#', ""."", ""@"" and digits (except 0). It is guaranteed that the described field is correct. It is guaranteed that the described field contains exactly one apple and exactly one snake, the snake's length is at least 3 and at most 9.
Print a single integer to the output β€” the minimum number of moves needed to reach the apple. If the snake can't reach the apple, print -1.
Input: 4 5##.....1#@432#....#. | Output: 4
Hard
4
1,517
707
139
2
117
C
117C
C. Cycle
2,000
dfs and similar; graphs
A tournament is a directed graph without self-loops in which every pair of vertexes is connected by exactly one directed edge. That is, for any two vertexes u and v (u β‰  v) exists either an edge going from u to v, or an edge from v to u.You are given a tournament consisting of n vertexes. Your task is to find there a cycle of length three.
The first line contains an integer n (1 ≀ n ≀ 5000). Next n lines contain the adjacency matrix A of the graph (without spaces). Ai, j = 1 if the graph has an edge going from vertex i to vertex j, otherwise Ai, j = 0. Ai, j stands for the j-th character in the i-th line.It is guaranteed that the given graph is a tournament, that is, Ai, i = 0, Ai, j β‰  Aj, i (1 ≀ i, j ≀ n, i β‰  j).
Print three distinct vertexes of the graph a1, a2, a3 (1 ≀ ai ≀ n), such that Aa1, a2 = Aa2, a3 = Aa3, a1 = 1, or ""-1"", if a cycle whose length equals three does not exist. If there are several solutions, print any of them.
Input: 50010010000010011110111000 | Output: 1 3 2
Hard
2
341
381
225
1
161
C
161C
C. Abracadabra
2,400
divide and conquer
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm: On the first step the string consists of a single character ""a"". On the k-th step Polycarpus concatenates two copies of the string obtained on the (k - 1)-th step, while inserting the k-th character of the alphabet between them. Polycarpus uses the alphabet that consists of lowercase Latin letters and digits (a total of 36 characters). The alphabet characters are numbered like this: the 1-st character is ""a"", the 2-nd β€” ""b"", ..., the 26-th β€” ""z"", the 27-th β€” ""0"", the 28-th β€” ""1"", ..., the 36-th β€” ""9"". Let's have a closer look at the algorithm. On the second step Polycarpus will concatenate two strings ""a"" and insert the character ""b"" between them, resulting in ""aba"" string. The third step will transform it into ""abacaba"", and the fourth one - into ""abacabadabacaba"". Thus, the string constructed on the k-th step will consist of 2k - 1 characters. Polycarpus wrote down the string he got after 30 steps of the given algorithm and chose two non-empty substrings of it. Your task is to find the length of the longest common substring of the two substrings selected by Polycarpus.A substring s[i... j] (1 ≀ i ≀ j ≀ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = ""abacaba"" equals ""bac"". The string is its own substring.The longest common substring of two strings s and t is the longest string that is a substring of both s and t. For example, the longest common substring of ""contest"" and ""systemtesting"" is string ""test"". There can be several common substrings of maximum length.
The input consists of a single line containing four integers l1, r1, l2, r2 (1 ≀ li ≀ ri ≀ 109, i = 1, 2). The numbers are separated by single spaces. li and ri give the indices of the first and the last characters of the i-th chosen substring, correspondingly (i = 1, 2). The characters of string abracadabra are numbered starting from 1.
Print a single number β€” the length of the longest common substring of the given strings. If there are no common substrings, print 0.
In the first sample the first substring is ""acab"", the second one is ""abac"". These two substrings have two longest common substrings ""ac"" and ""ab"", but we are only interested in their length β€” 2.In the second sample the first substring is ""a"", the second one is ""c"". These two substrings don't have any common characters, so the length of their longest common substring is 0.
Input: 3 6 1 4 | Output: 2
Expert
1
1,686
339
132
1
2,104
A
2104A
A. Three Decks
800
math
Monocarp placed three decks of cards in a row on the table. The first deck consists of \(a\) cards, the second deck consists of \(b\) cards, and the third deck consists of \(c\) cards, with the condition \(a < b < c\).Monocarp wants to take some number of cards (at least one, but no more than \(c\)) from the third deck and distribute them between the first two decks so that each of the taken cards ends up in either the first or the second deck. It is possible that all the cards taken from the third deck will go into the same deck.Your task is to determine whether Monocarp can make the number of cards in all three decks equal using the described operation.
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 three integers \(a, b\), and \(c\) (\(1 \le a, b, c \le 10^8\)) β€” the number of cards in the first, second, and third decks, respectively.Additional constraint on the input: \(a < b < c\).
For each test case, output ""YES"" (without quotes) if Monocarp can make the number of cards in all three decks equal using the described operation. Otherwise, output ""NO"" (without quotes).
In the first test case, Monocarp has to take \(4\) cards from the third deck, put \(3\) cards in the first deck, and \(1\) card in the second deck. Thus, there will be \(6\) cards in all three decks.In the second test case, it is impossible to make the number of cards in all three decks equal.In the third test case, Monocarp has to take \(2\) cards from the third deck and put both in the first deck. Thus, there will be \(5\) cards in all three decks.In the fourth test case, it is also impossible to make the number of cards in all three decks equal.
Input: 43 5 1012 20 303 5 71 5 6 | Output: YES NO YES NO
Beginner
1
663
326
191
21
1,731
D
1731D
D. Valiant's New Map
1,700
binary search; brute force; data structures; dp; two pointers
Game studio ""DbZ Games"" wants to introduce another map in their popular game ""Valiant"". This time, the map named ""Panvel"" will be based on the city of Mumbai.Mumbai can be represented as \(n \times m\) cellular grid. Each cell \((i, j)\) (\(1 \le i \le n\); \(1 \le j \le m\)) of the grid is occupied by a cuboid building of height \(a_{i,j}\).This time, DbZ Games want to make a map that has perfect vertical gameplay. That's why they want to choose an \(l \times l\) square inside Mumbai, such that each building inside the square has a height of at least \(l\).Can you help DbZ Games find such a square of the maximum possible size \(l\)?
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 1000\)). Description of the test cases follows.The first line of each test case contains two positive integers \(n\) and \(m\) (\(1 \le n \le m\); \(1 \leq n \cdot m \leq 10^6\)).The \(i\)-th of next \(n\) lines contains \(m\) integers \(a_{i,1}, a_{i,2}, \dots, a_{i,m}\) (\(1 \leq a_{i,j} \leq 10^6\)) β€” heights of buildings on the \(i\)-th row.It's guaranteed that the sum of \(n \cdot m\) over all test cases doesn't exceed \(10^6\).
For each test case, print the maximum side length \(l\) of the square DbZ Games can choose.
In the first test case, we can choose the square of side \(l = 2\) (i. e. the whole grid) since the heights of all buildings are greater than or equal to \(2\).In the second test case, we can only choose the side as \(1\), so the answer is \(1\).In the third test case, there are no squares of size \(2\) that have all buildings of height at least \(2\), so the answer is \(1\).
Input: 42 22 34 51 31 2 32 34 4 32 1 45 61 9 4 6 5 810 9 5 8 11 624 42 32 8 11 123 1 9 69 13 313 22 60 12 14 17 | Output: 2 1 1 3
Medium
5
647
549
91
17
901
B
901B
B. GCD of Polynomials
2,200
constructive algorithms; math
Suppose you have two polynomials and . Then polynomial can be uniquely represented in the following way:This can be done using long division. Here, denotes the degree of polynomial P(x). is called the remainder of division of polynomial by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair to pair .
You are given a single integer n (1 ≀ n ≀ 150) β€” the number of steps of the algorithm you need to reach.
Print two polynomials in the following format.In the first line print a single integer m (0 ≀ m ≀ n) β€” the degree of the polynomial. In the second line print m + 1 integers between - 1 and 1 β€” the coefficients of the polynomial, from constant to leading. The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials.If there is no answer for the given n, print -1.If there are multiple answer, print any of them.
In the second example you can print polynomials x2 - 1 and x. The sequence of transitions is(x2 - 1, x) β†’ (x, - 1) β†’ ( - 1, 0).There are two steps in it.
Input: 1 | Output: 10 101
Hard
2
1,274
104
579
9
1,658
D2
1658D2
D2. 388535 (Hard Version)
2,300
bitmasks; brute force; data structures; math
This is the hard version of the problem. The difference in the constraints between both versions are 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 perform the following steps: First, Gojou chooses \(2\) integers \(l\) and \(r\) such that \(l \leq r\). Then, Gojou will make 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{\le} \boldsymbol{l}} \le r < 2^{17}\)).The second line contains \(r - l + 1\) space-seperated integers of \(a_1,a_2,\ldots,a_{r-l+1}\) (\(0 \le a_i < 2^{17}\)). It is guaranteed that array \(a\) is valid.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 \([7, 6, 5, 4]\). In the second test case, the original array is \([4, 7, 6, 5]\).In the third test case, the original array is \([3, 1, 2]\).
Input: 34 73 2 1 04 74 7 6 51 30 2 1 | Output: 4 0 3
Expert
4
933
513
84
16
549
G
549G
G. Happy Line
2,200
constructive algorithms; greedy; sortings
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of n Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person a stands just behind person b, then person a can pay person b 1 dollar, then a and b get swapped. Of course, if person a has zero dollars, he can not swap places with person b.Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them.Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.
The first line contains integer n (1 ≀ n ≀ 200 000) β€” the number of residents who stand in the line.The second line contains n space-separated integers ai (0 ≀ ai ≀ 109), where ai is the number of Berland dollars of a man standing on the i-th position in the line. The positions are numbered starting from the end of the line.
If it is impossible to make all the residents happy, print "":("" without the quotes. Otherwise, print in the single line n space-separated integers, the i-th of them must be equal to the number of money of the person on position i in the new line. If there are multiple answers, print any of them.
In the first sample two residents should swap places, after that the first resident has 10 dollars and he is at the head of the line and the second resident will have 9 coins and he will be at the end of the line. In the second sample it is impossible to achieve the desired result.In the third sample the first person can swap with the second one, then they will have the following numbers of dollars: 4 11 3, then the second person (in the new line) swaps with the third one, and the resulting numbers of dollars will equal to: 4 4 10. In this line everybody will be happy.
Input: 211 8 | Output: 9 10
Hard
3
1,121
326
298
5
761
A
761A
A. Dasha and Stairs
1,000
brute force; constructive algorithms; implementation; math
On her way to programming school tiger Dasha faced her first test β€” a huge staircase! The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values β€” the number of steps with even and odd numbers. You need to check whether there is an interval of steps from the l-th to the r-th (1 ≀ l ≀ r), for which values that Dasha has found are correct.
In the only line you are given two integers a, b (0 ≀ a, b ≀ 100) β€” the number of even and odd steps, accordingly.
In the only line print ""YES"", if the interval of steps described above exists, and ""NO"" otherwise.
In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps β€” 2 and 4, and three odd: 1, 3 and 5.
Input: 2 3 | Output: YES
Beginner
4
500
114
102
7
913
A
913A
A. Modular Exponentiation
900
implementation; math
The following problem is well-known: given integers n and m, calculate , where 2n = 2Β·2Β·...Β·2 (n factors), and denotes the remainder of division of x by y.You are asked to solve the ""reverse"" problem. Given integers n and m, calculate .
The first line contains a single integer n (1 ≀ n ≀ 108).The second line contains a single integer m (1 ≀ m ≀ 108).
Output a single integer β€” the value of .
In the first example, the remainder of division of 42 by 24 = 16 is equal to 10.In the second example, 58 is divisible by 21 = 2 without remainder, and the answer is 0.
Input: 442 | Output: 10
Beginner
2
238
115
40
9
1,016
B
1016B
B. Segment Occurrences
1,300
brute force; implementation
You are given two strings \(s\) and \(t\), both consisting only of lowercase Latin letters.The substring \(s[l..r]\) is the string which is obtained by taking characters \(s_l, s_{l + 1}, \dots, s_r\) without changing the order.Each of the occurrences of string \(a\) in a string \(b\) is a position \(i\) (\(1 \le i \le |b| - |a| + 1\)) such that \(b[i..i + |a| - 1] = a\) (\(|a|\) is the length of string \(a\)).You are asked \(q\) queries: for the \(i\)-th query you are required to calculate the number of occurrences of string \(t\) in a substring \(s[l_i..r_i]\).
The first line contains three integer numbers \(n\), \(m\) and \(q\) (\(1 \le n, m \le 10^3\), \(1 \le q \le 10^5\)) β€” the length of string \(s\), the length of string \(t\) and the number of queries, respectively.The second line is a string \(s\) (\(|s| = n\)), consisting only of lowercase Latin letters.The third line is a string \(t\) (\(|t| = m\)), consisting only of lowercase Latin letters.Each of the next \(q\) lines contains two integer numbers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le n\)) β€” the arguments for the \(i\)-th query.
Print \(q\) lines β€” the \(i\)-th line should contain the answer to the \(i\)-th query, that is the number of occurrences of string \(t\) in a substring \(s[l_i..r_i]\).
In the first example the queries are substrings: ""cod"", ""deforces"", ""fo"" and ""for"", respectively.
Input: 10 3 4codeforcesfor1 33 105 65 7 | Output: 0101
Easy
2
569
544
168
10
542
C
542C
C. Idempotent functions
2,000
constructive algorithms; graphs; math
Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function , that for any the formula g(g(x)) = g(x) holds.Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x)) for each k > 1.You are given some function . Your task is to find minimum positive integer k such that function f(k)(x) is idempotent.
In the first line of the input there is a single integer n (1 ≀ n ≀ 200) β€” the size of function f domain.In the second line follow f(1), f(2), ..., f(n) (1 ≀ f(i) ≀ n for each 1 ≀ i ≀ n), the values of a function.
Output minimum k such that function f(k)(x) is idempotent.
In the first sample test function f(x) = f(1)(x) is already idempotent since f(f(1)) = f(1) = 1, f(f(2)) = f(2) = 2, f(f(3)) = f(3) = 2, f(f(4)) = f(4) = 4.In the second sample test: function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2; function f(x) = f(2)(x) is idempotent since for any x it is true that f(2)(x) = 3, so it is also true that f(2)(f(2)(x)) = 3. In the third sample test: function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2; function f(f(x)) = f(2)(x) isn't idempotent because f(2)(f(2)(1)) = 2 but f(2)(1) = 3; function f(f(f(x))) = f(3)(x) is idempotent since it is identity function: f(3)(x) = x for any meaning that the formula f(3)(f(3)(x)) = f(3)(x) also holds.
Input: 41 2 2 4 | Output: 1
Hard
3
438
213
58
5
223
E
223E
E. Planar Graph
3,000
flows; geometry; graphs
A graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes.An articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph.A bridge is such an edge of an undirected graph, that when removed increases the number of connected components of the graph.You've got a connected undirected planar graph consisting of n vertexes, numbered from 1 to n, drawn on the plane. The graph has no bridges, articulation points, loops and multiple edges. You are also given q queries. Each query is a cycle in the graph. The query response is the number of graph vertexes, which (if you draw a graph and the cycle on the plane) are located either inside the cycle, or on it. Write a program that, given the graph and the queries, will answer each query.
The first line contains two space-separated integers n and m (3 ≀ n, m ≀ 105) β€” the number of vertexes and edges of the graph. Next m lines contain the edges of the graph: the i-th line contains two space-separated integers ui and vi (1 ≀ ui, vi ≀ n) β€” the numbers of vertexes, connecting the i-th edge. The next n lines contain the positions of the planar graph vertexes on the plane: the i-th line contains a pair of space-separated integers xi and yi (|xi|, |yi| ≀ 109) β€” the coordinates of the i-th vertex of the graph on the plane. The next line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. Then follow q lines that describe the queries: the i-th line contains the sequence of space-separated integers ki, a1, a2, ..., aki (1 ≀ aj ≀ n; ki > 2), where ki is the cycle length in the i-th query, aj are numbers of the vertexes that form a cycle. The numbers of vertexes in the cycle are given in the clockwise or counterclockwise order. The given cycles are simple, that is they cannot go through a graph vertex more than once. The total length of all cycles in all queries does not exceed 105.It is guaranteed that the given graph contains no bridges, articulation points, loops and multiple edges. It is guaranteed that the edge segments can have common points only at the graph's vertexes.
For each query print a single integer β€” the number of vertexes inside the cycle or on it. Print the answers in the order, in which the queries follow in the input. Separate the numbers by spaces.
Input: 3 31 22 33 10 01 00 113 1 2 3 | Output: 3
Master
3
857
1,307
195
2
713
D
713D
D. Animals and Puzzle
2,700
binary search; data structures
Owl Sonya gave a huge lake puzzle of size n Γ— m to hedgehog Filya as a birthday present. Friends immediately started to assemble the puzzle, but some parts of it turned out to be empty β€” there was no picture on them. Parts with picture on it are denoted by 1, while empty parts are denoted by 0. Rows of the puzzle are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m.Animals decided to complete the picture and play with it, as it might be even more fun! Owl and hedgehog ask each other some queries. Each query is provided by four integers x1, y1, x2, y2 which define the rectangle, where (x1, y1) stands for the coordinates of the up left cell of the rectangle, while (x2, y2) stands for the coordinates of the bottom right cell. The answer to the query is the size of the maximum square consisting of picture parts only (only parts denoted by 1) and located fully inside the query rectangle.Help Sonya and Filya answer t queries.
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 1000) β€” sizes of the puzzle.Each of the following n lines contains m integers aij. Each of them is equal to 1 if the corresponding cell contains a picture and 0 if it's empty.Next line contains an integer t (1 ≀ t ≀ 1 000 000) β€” the number of queries.Then follow t lines with queries' descriptions. Each of them contains four integers x1, y1, x2, y2 (1 ≀ x1 ≀ x2 ≀ n, 1 ≀ y1 ≀ y2 ≀ m) β€” coordinates of the up left and bottom right cells of the query rectangle.
Print t lines. The i-th of them should contain the maximum size of the square consisting of 1-s and lying fully inside the query rectangle.
Input: 3 41 1 0 10 1 1 00 1 1 051 1 2 32 1 3 23 2 3 41 1 3 41 2 3 4 | Output: 11122
Master
2
1,011
530
139
7
1,675
A
1675A
A. Food for Animals
800
greedy; math
In the pet store on sale there are: \(a\) packs of dog food; \(b\) packs of cat food; \(c\) packs of universal food (such food is suitable for both dogs and cats). Polycarp has \(x\) dogs and \(y\) cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.
The first line of input contains an integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases in the input.Then \(t\) lines are given, each containing a description of one test case. Each description consists of five integers \(a, b, c, x\) and \(y\) (\(0 \le a,b,c,x,y \le 10^8\)).
For each test case in a separate line, output: YES, if suitable food can be bought for each of \(x\) dogs and for each of \(y\) cats; NO else. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
Input: 71 1 4 2 30 0 0 0 05 5 0 4 61 1 1 1 150000000 50000000 100000000 100000000 1000000000 0 0 100000000 1000000001 3 2 2 5 | Output: YES YES NO YES YES NO NO
Beginner
2
372
288
268
16
1,779
D
1779D
D. Boris and His Amazing Haircut
1,700
constructive algorithms; data structures; dp; dsu; greedy; sortings
Boris thinks that chess is a tedious game. So he left his tournament early and went to a barber shop as his hair was a bit messy.His current hair can be described by an array \(a_1,a_2,\ldots, a_n\), where \(a_i\) is the height of the hair standing at position \(i\). His desired haircut can be described by an array \(b_1,b_2,\ldots, b_n\) in a similar fashion.The barber has \(m\) razors. Each has its own size and can be used at most once. In one operation, he chooses a razor and cuts a segment of Boris's hair. More formally, an operation is: Choose any razor which hasn't been used before, let its size be \(x\); Choose a segment \([l,r]\) (\(1\leq l \leq r \leq n\)); Set \(a_i := \min (a_i,x)\) for each \(l\leq i \leq r\); Notice that some razors might have equal sizes β€” the barber can choose some size \(x\) only as many times as the number of razors with size \(x\). He may perform as many operations as he wants, as long as any razor is used at most once and \(a_i = b_i\) for each \(1 \leq i \leq n\) at the end. He does not have to use all razors.Can you determine whether the barber can give Boris his desired haircut?
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 20\,000\)). The description of the test cases follows.The first line of each test case contains a positive integer \(n\) (\(3\leq n\leq 2\cdot 10^5\)) β€” the length of arrays \(a\) and \(b\).The second line of each test case contains \(n\) positive integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)) β€” Boris's current hair.The third line of each test case contains \(n\) positive integers \(b_1, b_2, \ldots, b_n\) (\(1 \leq b_i \leq 10^9\)) β€” Boris's desired hair.The fourth line of each test case contains a positive integer \(m\) (\(1 \leq m \leq 2\cdot 10^5\)) β€” the number of razors.The fifth line of each test case contains \(m\) positive integers \(x_1,x_2, \ldots, x_m\) (\(1 \leq x_i \leq 10^9\)) β€” the sizes of the razors.It is guaranteed that the sum of \(n\) and the sum of \(m\) over all test cases do not exceed \(2\cdot 10^5\).
For each test case, print ""YES"" if the barber can cut Boris's hair as desired. Otherwise, print ""NO"".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, Boris's hair is initially \([3,3,3]\). Let us describe a sequence of \(2\) operations the barber can perform: The barber uses the razor with size \(1\) on the segment \([2,2]\); hence Boris's hair becomes \([3,1,3]\). The barber uses the razor with size \(2\) on the segment \([1,3]\); hence Boris's hair becomes \([2,1,2]\) which is the desired haircut. In the third test case, no operation has to be done since Boris's hair is already as desired.In the fourth test case, no cuts will be able to increase the third element in \([1,1,1]\) in a way that the array becomes \([1,1,2]\).
Input: 733 3 32 1 221 263 4 4 6 3 43 1 2 3 2 333 2 3101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 10101 2 3 4 5 6 7 8 9 1031 1 11 1 2124 2 4 3 1 5 6 3 5 6 2 1137 9 4 5 3 3 3 6 8 10 3 2 55 3 1 5 3 2 2 5 8 5 1 1 581 5 3 5 4 2 3 1137 9 4 5 3 3 3 6 8 10 3 2 55 3 1 5 3 2 2 5 8 5 1 1 571 5 3 4 2 3 1319747843 2736467 9385783972039844 2039844 203984412039844 | Output: YES NO YES NO YES NO YES
Medium
6
1,134
964
266
17