problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
F2. Marek and Matching (hard version)time limit per test15 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version, n \le 7.Marek is working hard on creating strong test cases to his new algorithmic problem. Do you want to know what it is? Nah, we're not telling you. However, we can tell you how he generates test cases.Marek chooses an integer n and n^2 integers p_{ij} (1 \le i \le n, 1 \le j \le n). He then generates a random bipartite graph with 2n vertices. There are n vertices on the left side: \ell_1, \ell_2, \dots, \ell_n, and n vertices on the right side: r_1, r_2, \dots, r_n. For each i and j, he puts an edge between vertices \ell_i and r_j with probability p_{ij} percent.It turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur?It can be shown that this value can be represented as \frac{P}{Q} where P and Q are coprime integers and Q \not\equiv 0 \pmod{10^9+7}. Let Q^{-1} be an integer for which Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} modulo 10^9+7.InputThe first line of the input contains a single integer n (\mathbf{1 \le n \le 7}). The following n lines describe the probabilities of each edge appearing in the graph. The i-th of the lines contains n integers p_{i1}, p_{i2}, \dots, p_{in} (0 \le p_{ij} \le 100); p_{ij} denotes the probability, in percent, of an edge appearing between \ell_i and r_j.OutputPrint a single integer — the probability that the perfect matching exists in the bipartite graph, written as P \cdot Q^{-1} \pmod{10^9+7} for P, Q defined above.ExamplesInput
2
50 50
50 50
Output
937500007
Input
3
3 1 4
1 5 9
2 6 5
Output
351284554
NoteIn the first sample test, each of the 16 graphs below is equally probable. Out of these, 7 have a perfect matching: Therefore, the probability is equal to \frac{7}{16}. As 16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}, the answer to the testcase is 7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007. | 2
50 50
50 50
| 937500007 | 15 seconds | 256 megabytes | ['brute force', 'probabilities', '*3200'] |
F1. Marek and Matching (easy version)time limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version, n \le 6.Marek is working hard on creating strong testcases to his new algorithmic problem. You want to know what it is? Nah, we're not telling you. However, we can tell you how he generates the testcases.Marek chooses an integer n and n^2 integers p_{ij} (1 \le i \le n, 1 \le j \le n). He then generates a random bipartite graph with 2n vertices. There are n vertices on the left side: \ell_1, \ell_2, \dots, \ell_n, and n vertices on the right side: r_1, r_2, \dots, r_n. For each i and j, he puts an edge between vertices \ell_i and r_j with probability p_{ij} percent.It turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur?It can be shown that this value can be represented as \frac{P}{Q} where P and Q are coprime integers and Q \not\equiv 0 \pmod{10^9+7}. Let Q^{-1} be an integer for which Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} modulo 10^9+7.InputThe first line of the input contains a single integer n (\mathbf{1 \le n \le 6}). The following n lines describe the probabilities of each edge appearing in the graph. The i-th of the lines contains n integers p_{i1}, p_{i2}, \dots, p_{in} (0 \le p_{ij} \le 100); p_{ij} denotes the probability, in percent, of an edge appearing between \ell_i and r_j.OutputPrint a single integer — the probability that the perfect matching exists in the bipartite graph, written as P \cdot Q^{-1} \pmod{10^9+7} for P, Q defined above.ExamplesInput
2
50 50
50 50
Output
937500007
Input
3
3 1 4
1 5 9
2 6 5
Output
351284554
NoteIn the first sample test, each of the 16 graphs below is equally probable. Out of these, 7 have a perfect matching: Therefore, the probability is equal to \frac{7}{16}. As 16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}, the answer to the testcase is 7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007. | 2
50 50
50 50
| 937500007 | 7 seconds | 256 megabytes | ['brute force', 'probabilities', '*3100'] |
E. Wojtek and Card Trickstime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWojtek has just won a maths competition in Byteland! The prize is admirable — a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!'The first chapter of the book is 'How to Shuffle k Cards in Any Order You Want.' It's basically a list of n intricate methods of shuffling the deck of k cards in a deterministic way. Specifically, the i-th recipe can be described as a permutation (P_{i,1}, P_{i,2}, \dots, P_{i,k}) of integers from 1 to k. If we enumerate the cards in the deck from 1 to k from top to bottom, then P_{i,j} indicates the number of the j-th card from the top of the deck after the shuffle.The day is short and Wojtek wants to learn only some of the tricks today. He will pick two integers l, r (1 \le l \le r \le n), and he will memorize each trick from the l-th to the r-th, inclusive. He will then take a sorted deck of k cards and repeatedly apply random memorized tricks until he gets bored. He still likes maths, so he started wondering: how many different decks can he have after he stops shuffling it?Wojtek still didn't choose the integers l and r, but he is still curious. Therefore, he defined f(l, r) as the number of different decks he can get if he memorizes all the tricks between the l-th and the r-th, inclusive. What is the value of\sum_{l=1}^n \sum_{r=l}^n f(l, r)?InputThe first line contains two integers n, k (1 \le n \le 200\,000, 1 \le k \le 5) — the number of tricks and the number of cards in Wojtek's deck.Each of the following n lines describes a single trick and is described by k distinct integers P_{i,1}, P_{i,2}, \dots, P_{i, k} (1 \le P_{i, j} \le k).OutputOutput the value of the sum described in the statement.ExamplesInput
3 3
2 1 3
3 1 2
1 3 2
Output
25
Input
2 4
4 1 3 2
4 3 1 2
Output
31
NoteConsider the first sample: The first trick swaps two top cards. The second trick takes a card from the bottom and puts it on the top of the deck. The third trick swaps two bottom cards. The first or the third trick allow Wojtek to generate only two distinct decks (either the two cards are swapped or not). Therefore, f(1, 1) = f(3, 3) = 2.The second trick allows him to shuffle the deck in a cyclic order. Therefore, f(2,2)=3.It turns that two first tricks or two last tricks are enough to shuffle the deck in any way desired by Wojtek. Therefore, f(1,2) = f(2,3) = f(1,3) = 3! = 6. | 3 3
2 1 3
3 1 2
1 3 2
| 25 | 3.5 seconds | 256 megabytes | ['math', '*2700'] |
D. Konrad and Company Evaluationtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKonrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.There are n people working for VoltModder, numbered from 1 to n. Each employee earns a different amount of money in the company — initially, the i-th person earns i rubles per day.On each of q following days, the salaries will be revised. At the end of the i-th day, employee v_i will start earning n+i rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again.Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people a and b dislike each other and a earns more money than b, employee a will brag about this to b. A dangerous triple is a triple of three employees a, b and c, such that a brags to b, who in turn brags to c. If a dislikes b, then b dislikes a.At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?InputThe first line contains two integers n and m (1 \le n \le 100\,000, 0 \le m \le 100\,000) — the number of employees in the company and the number of pairs of people who don't like each other. Each of the following m lines contains two integers a_i, b_i (1 \le a_i, b_i \le n, a_i \neq b_i) denoting that employees a_i and b_i hate each other (that is, a_i dislikes b_i and b_i dislikes a_i). Each such relationship will be mentioned exactly once.The next line contains an integer q (0 \le q \le 100\,000) — the number of salary revisions. The i-th of the following q lines contains a single integer v_i (1 \le v_i \le n) denoting that at the end of the i-th day, employee v_i will earn the most.OutputOutput q + 1 integers. The i-th of them should contain the number of dangerous triples in the company at the beginning of the i-th day.ExamplesInput
4 5
1 2
2 4
1 3
3 4
2 3
2
2
3
Output
4
3
2
Input
3 3
1 2
2 3
1 3
5
1
2
2
1
3
Output
1
1
1
1
1
1
NoteConsider the first sample test. The i-th row in the following image shows the structure of the company at the beginning of the i-th day. A directed edge from a to b denotes that employee a brags to employee b. The dangerous triples are marked by highlighted edges. | 4 5
1 2
2 4
1 3
3 4
2 3
2
2
3
| 4 3 2 | 4 seconds | 256 megabytes | ['graphs', '*2400'] |
C. Kamil and Making a Streamtime limit per test4 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputKamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?You're given a tree — a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.Each vertex v is assigned its beauty x_v — a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, \dots, t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.Your task is to find the sum \sum_{u\text{ is an ancestor of }v} f(u, v). As the result might be too large, please output it modulo 10^9 + 7.Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.InputThe first line contains a single integer n (2 \le n \le 100\,000) — the number of vertices in the tree.The following line contains n integers x_1, x_2, \dots, x_n (0 \le x_i \le 10^{12}). The value x_v denotes the beauty of vertex v.The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 \le a, b \le n, a \neq b) — the vertices connected by a single edge.OutputOutput the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.ExamplesInput
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
NoteThe following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42: | 5
4 5 6 0 8
1 2
1 3
1 4
4 5
| 42 | 4 seconds | 768 megabytes | ['math', 'number theory', 'trees', '*2000'] |
B. Marcin and Training Camptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i and b_i; b_i is equal to the skill level of the i-th student (the higher, the better). Also, there are 60 known algorithms, which are numbered with integers from 0 to 59. If the i-th student knows the j-th algorithm, then the j-th bit (2^j) is set in the binary representation of a_i. Otherwise, this bit is not set.Student x thinks that he is better than student y if and only if x knows some algorithm which y doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?InputThe first line contains one integer n (1 \leq n \leq 7000) — the number of students interested in the camp.The second line contains n integers. The i-th of them is a_i (0 \leq a_i < 2^{60}).The third line contains n integers. The i-th of them is b_i (1 \leq b_i \leq 10^9).OutputOutput one integer which denotes the maximum sum of b_i over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.ExamplesInput
4
3 2 3 6
2 8 5 10
Output
15
Input
3
1 2 3
1 2 3
Output
0
Input
1
0
1
Output
0
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of b_i.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset. | 4
3 2 3 6
2 8 5 10
| 15 | 3 seconds | 256 megabytes | ['brute force', 'greedy', '*1700'] |
A. Anadi and Dominotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 \leq a \leq b \leq 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.How many dominoes at most can Anadi place on the edges of his graph?InputThe first line contains two integers n and m (1 \leq n \leq 7, 0 \leq m \leq \frac{n\cdot(n-1)}{2}) — the number of vertices and the number of edges in the graph.The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 \leq a, b \leq n, a \neq b) and denote that there is an edge which connects vertices a_i and b_i.The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.OutputOutput one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.ExamplesInput
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
NoteHere is an illustration of Anadi's graph from the first sample test: And here is one of the ways to place a domino on each of its edges: Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots. | 4 4
1 2
2 3
3 4
4 1
| 4 | 2 seconds | 256 megabytes | ['brute force', 'graphs', '*1700'] |
H. Moving Walkwaystime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAirports often use moving walkways to help you walking big distances faster. Each such walkway has some speed that effectively increases your speed. You can stand on such a walkway and let it move you, or you could also walk and then your effective speed is your walking speed plus walkway's speed.Limak wants to get from point 0 to point L on a straight line. There are n disjoint walkways in between. The i-th walkway is described by two integers x_i and y_i and a real value s_i. The i-th walkway starts at x_i, ends at y_i and has speed s_i. Every walkway is located inside the segment [0, L] and no two walkways have positive intersection. However, they can touch by endpoints.Limak needs to decide how to distribute his energy. For example, it might make more sense to stand somewhere (or to walk slowly) to then have a lot of energy to walk faster.Limak's initial energy is 0 and it must never drop below that value. At any moment, he can walk with any speed v in the interval [0, 2] and it will cost him v energy per second, but he continuously recovers energy with speed of 1 energy per second. So, when he walks with speed v, his energy increases by (1-v). Note that negative value would mean losing energy.In particular, he can walk with speed 1 and this won't change his energy at all, while walking with speed 0.77 effectively gives him 0.23 energy per second.Limak can choose his speed arbitrarily (any real value in interval [0, 2]) at every moment of time (including the moments when he is located on non-integer positions). Everything is continuous (non-discrete).What is the fastest time Limak can get from 0 to L?InputThe first line contains integers n and L (1 \le n \le 200\,000, 1 \le L \le 10^9), the number of walkways and the distance to walk.Each of the next n lines contains integers x_i, y_i and real value s_i (0 \le x_i < y_i \le L, 0.1 \le s_i \le 10.0). The value s_i is given with at most 9 digits after decimal point.It's guaranteed, that no two walkways have a positive intersection. The walkways are listed from left to right. That is, y_i \le x_{i + 1} for 1 \le i \le n - 1.OutputPrint one real value, the fastest possible time to reach L. Your answer will be considered correct if its absolute or relative error won't exceed 10^{-9}.ExamplesInput
1 5
0 2 2.0
Output
3.000000000000
Input
1 5
2 4 0.91
Output
3.808900523560
Input
3 1000
0 990 1.777777
995 996 1.123456789
996 1000 2.0
Output
361.568848429553
NoteThe drawings show the first two examples. In the first one, there is a walkway from 0 to 2 with speed 2.0 and Limak wants to get to point 5. The second example has a walkway from 2 to 4 with speed 0.91. In the first example, one of optimal strategies is as follows. Get from 0 to 2 by standing still on the walkway. It moves you with speed 2 so it takes 1 second and you save up 1 energy. Get from 2 to 4 by walking with max speed 2 for next 1 second. It takes 1 second again and the energy drops to 0. Get from 4 to 5 by walking with speed 1. It takes 1 second and the energy stays constant at the value 0. The total time is 1 + 1 + 1 = 3. | 1 5
0 2 2.0
| 3.000000000000 | 2.5 seconds | 256 megabytes | ['data structures', 'greedy', 'math', '*3300'] |
G2. Into Blocks (hard version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version q \le 200\,000.A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal.Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value x to value y, you must also change all other elements of value x into y as well. For example, for [3, 3, 1, 3, 2, 1, 2] it isn't allowed to change first 1 to 3 and second 1 to 2. You need to leave 1's untouched or change them to the same value.You are given a sequence of integers a_1, a_2, \ldots, a_n and q updates.Each update is of form "i x" — change a_i to x. Updates are not independent (the change stays for the future).Print the difficulty of the initial sequence and of the sequence after every update.InputThe first line contains integers n and q (1 \le n \le 200\,000, 0 \le q \le 200\,000), the length of the sequence and the number of the updates.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 200\,000), the initial sequence.Each of the following q lines contains integers i_t and x_t (1 \le i_t \le n, 1 \le x_t \le 200\,000), the position and the new value for this position.OutputPrint q+1 integers, the answer for the initial sequence and the answer after every update.ExampleInput
5 6
1 2 1 2 1
2 1
4 1
5 3
2 3
4 2
2 1
Output
2
1
0
0
2
3
0
| 5 6
1 2 1 2 1
2 1
4 1
5 3
2 3
4 2
2 1
| 2 1 0 0 2 3 0 | 5 seconds | 256 megabytes | ['data structures', '*3200'] |
G1. Into Blocks (easy version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easier version of the next problem. In this version, q = 0.A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal.Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value x to value y, you must also change all other elements of value x into y as well. For example, for [3, 3, 1, 3, 2, 1, 2] it isn't allowed to change first 1 to 3 and second 1 to 2. You need to leave 1's untouched or change them to the same value.You are given a sequence of integers a_1, a_2, \ldots, a_n and q updates.Each update is of form "i x" — change a_i to x. Updates are not independent (the change stays for the future).Print the difficulty of the initial sequence and of the sequence after every update.InputThe first line contains integers n and q (1 \le n \le 200\,000, q = 0), the length of the sequence and the number of the updates.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 200\,000), the initial sequence.Each of the following q lines contains integers i_t and x_t (1 \le i_t \le n, 1 \le x_t \le 200\,000), the position and the new value for this position.OutputPrint q+1 integers, the answer for the initial sequence and the answer after every update.ExamplesInput
5 0
3 7 3 7 3
Output
2
Input
10 0
1 2 1 2 3 1 1 1 50 1
Output
4
Input
6 0
6 6 3 3 4 4
Output
0
Input
7 0
3 3 1 3 2 1 2
Output
4
| 5 0
3 7 3 7 3
| 2 | 5 seconds | 256 megabytes | ['data structures', 'dsu', 'greedy', 'implementation', 'two pointers', '*2000'] |
F. Koala and Notebooktime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKoala Land consists of m bidirectional roads connecting n cities. The roads are numbered from 1 to m by order in input. It is guaranteed, that one can reach any city from every other city.Koala starts traveling from city 1. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?Since these numbers may be quite large, print their remainders modulo 10^9+7. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.InputThe first line contains two integers n and m (2 \le n \le 10^5, n - 1 \le m \le 10^5), the number of cities and the number of roads, respectively.The i-th of the following m lines contains integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i), representing a bidirectional road between cities x_i and y_i.It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city. OutputPrint n - 1 integers, the answer for every city except for the first city.The i-th integer should be equal to the smallest number he could have written for destination i+1. Since this number may be large, output its remainder modulo 10^9+7.ExamplesInput
11 10
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
Output
1
12
123
1234
12345
123456
1234567
12345678
123456789
345678826
Input
12 19
1 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
3 11
11 12
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
Output
1
12
13
14
15
16
17
18
19
1210
121011
Input
12 14
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
1 3
1 4
1 10
Output
1
12
13
134
1345
13456
1498
149
14
1410
141011
| 11 10
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
| 1 12 123 1234 12345 123456 1234567 12345678 123456789 345678826 | 2 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'graphs', 'shortest paths', 'strings', 'trees', '*2600'] |
E2. Rotate Columns (hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. The difference is only in constraints.You are given a rectangular n \times m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for i-th row it is equal r_i. What is the maximal possible value of r_1+r_2+\ldots+r_n?InputThe first line contains an integer t (1 \le t \le 40), the number of test cases in the input.The first line of each test case contains integers n and m (1 \le n \le 12, 1 \le m \le 2000) — the number of rows and the number of columns in the given matrix a. Each of the following n lines contains m integers, the elements of a (1 \le a_{i, j} \le 10^5).OutputPrint t integers: answers for all test cases in the order they are given in the input.ExampleInput
3
2 3
2 5 7
4 2 4
3 6
4 1 5 2 10 4
8 6 6 4 9 10
5 4 9 5 8 7
3 3
9 9 9
1 1 1
1 1 1
Output
12
29
27
NoteIn the first test case you can shift the third column down by one, this way there will be r_1 = 5 and r_2 = 7.In the second case you can don't rotate anything at all, this way there will be r_1 = r_2 = 10 and r_3 = 9. | 3
2 3
2 5 7
4 2 4
3 6
4 1 5 2 10 4
8 6 6 4 9 10
5 4 9 5 8 7
3 3
9 9 9
1 1 1
1 1 1
| 12 29 27 | 3 seconds | 256 megabytes | ['bitmasks', 'dp', 'greedy', 'sortings', '*2500'] |
E1. Rotate Columns (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easier version of the next problem. The difference is only in constraints.You are given a rectangular n \times m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for i-th row it is equal r_i. What is the maximal possible value of r_1+r_2+\ldots+r_n?InputThe first line contains an integer t (1 \le t \le 40), the number of test cases in the input.The first line of each test case contains integers n and m (1 \le n \le 4, 1 \le m \le 100) — the number of rows and the number of columns in the given matrix a. Each of the following n lines contains m integers, the elements of a (1 \le a_{i, j} \le 10^5).OutputPrint t integers: answers for all test cases in the order they are given in the input.ExampleInput
2
2 3
2 5 7
4 2 4
3 6
4 1 5 2 10 4
8 6 6 4 9 10
5 4 9 5 8 7
Output
12
29
NoteIn the first test case, you can shift the third column down by one, this way there will be r_1 = 5 and r_2 = 7.In the second case you can don't rotate anything at all, this way there will be r_1 = r_2 = 10 and r_3 = 9. | 2
2 3
2 5 7
4 2 4
3 6
4 1 5 2 10 4
8 6 6 4 9 10
5 4 9 5 8 7
| 12 29 | 3 seconds | 256 megabytes | ['bitmasks', 'brute force', 'dp', 'greedy', 'sortings', '*2000'] |
D. Cow and Snackstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!There are n snacks flavors, numbered with integers 1, 2, \ldots, n. Bessie has n snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad. Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.InputThe first line contains integers n and k (2 \le n \le 10^5, 1 \le k \le 10^5), the number of snacks and the number of guests. The i-th of the following k lines contains two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i), favorite snack flavors of the i-th guest.OutputOutput one integer, the smallest possible number of sad guests.ExamplesInput
5 4
1 2
4 3
1 4
3 4
Output
1
Input
6 5
2 3
2 1
3 4
6 5
4 5
Output
0
NoteIn the first example, Bessie can order the guests like this: 3, 1, 2, 4. Guest 3 goes first and eats snacks 1 and 4. Then the guest 1 goes and eats the snack 2 only, because the snack 1 has already been eaten. Similarly, the guest 2 goes up and eats the snack 3 only. All the snacks are gone, so the guest 4 will be sad. In the second example, one optimal ordering is 2, 1, 3, 5, 4. All the guests will be satisfied. | 5 4
1 2
4 3
1 4
3 4
| 1 | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*1700'] |
C. Paint the Digitstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of n digits d_1d_2 \dots d_{n}. You need to paint all the digits in two colors so that: each digit is painted either in the color 1 or in the color 2; if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color 2, then the resulting sequence of n digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence d=914 the only valid coloring is 211 (paint in the color 1 two last digits, paint in the color 2 the first digit). But 122 is not a valid coloring (9 concatenated with 14 is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.InputThe first line contains a single integer t (1 \le t \le 10000) — the number of test cases in the input.The first line of each test case contains an integer n (1 \le n \le 2\cdot10^5) — the length of a given sequence of digits.The next line contains a sequence of n digits d_1d_2 \dots d_{n} (0 \le d_i \le 9). The digits are written in a row without spaces or any other separators. The sequence can start with 0.It is guaranteed that the sum of the values of n for all test cases in the input does not exceed 2\cdot10^5.OutputPrint t lines — the answers to each of the test cases in the input.If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of n digits t_1t_2 \dots t_n (1 \le t_i \le 2), where t_i is the color the i-th digit is painted in. If there are several feasible solutions, print any of them.If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign).ExampleInput
5
12
040425524644
1
0
9
123456789
2
98
3
987
Output
121212211211
1
222222222
21
-
NoteIn the first test case, d=040425524644. The output t=121212211211 is correct because 0022444 (painted in 1) concatenated with 44556 (painted in 2) is 002244444556 which is a sorted sequence of n given digits. | 5
12
040425524644
1
0
9
123456789
2
98
3
987
| 121212211211 1 222222222 21 - | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*1500'] |
B. Koala and Lightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is a holiday season, and Koala is decorating his house with cool lights! He owns n lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters a_i and b_i. Light with parameters a_i and b_i will toggle (on to off, or off to on) every a_i seconds starting from the b_i-th second. In other words, it will toggle at the moments b_i, b_i + a_i, b_i + 2 \cdot a_i and so on.You know for each light whether it's initially on or off and its corresponding parameters a_i and b_i. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out. Here is a graphic for the first example. InputThe first line contains a single integer n (1 \le n \le 100), the number of lights.The next line contains a string s of n characters. The i-th character is "1", if the i-th lamp is initially on. Otherwise, i-th character is "0".The i-th of the following n lines contains two integers a_i and b_i (1 \le a_i, b_i \le 5) — the parameters of the i-th light.OutputPrint a single integer — the maximum number of lights that will ever be on at the same time.ExamplesInput
3
101
3 3
3 2
3 1
Output
2
Input
4
1111
3 4
5 2
3 1
3 2
Output
4
Input
6
011100
5 3
5 5
2 4
3 5
4 2
1 5
Output
6
NoteFor first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is 2 (e.g. at the moment 2).In the second example, all lights are initially on. So the answer is 4. | 3
101
3 3
3 2
3 1
| 2 | 1 second | 256 megabytes | ['implementation', 'math', 'number theory', '*1300'] |
A. Paint the Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of integers a_1, a_2, \dots, a_n. You need to paint elements in colors, so that: If we consider any color, all elements of this color must be divisible by the minimal element of this color. The number of used colors must be minimized. For example, it's fine to paint elements [40, 10, 60] in a single color, because they are all divisible by 10. You can use any color an arbitrary amount of times (in particular, it is allowed to use a color only once). The elements painted in one color do not need to be consecutive.For example, if a=[6, 2, 3, 4, 12] then two colors are required: let's paint 6, 3 and 12 in the first color (6, 3 and 12 are divisible by 3) and paint 2 and 4 in the second color (2 and 4 are divisible by 2). For example, if a=[10, 7, 15] then 3 colors are required (we can simply paint each element in an unique color).InputThe first line contains an integer n (1 \le n \le 100), where n is the length of the given sequence.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100). These numbers can contain duplicates.OutputPrint the minimal number of colors to paint all the given numbers in a valid way.ExamplesInput
6
10 2 3 5 4 2
Output
3
Input
4
100 100 100 100
Output
1
Input
8
7 6 5 4 3 2 2 3
Output
4
NoteIn the first example, one possible way to paint the elements in 3 colors is: paint in the first color the elements: a_1=10 and a_4=5, paint in the second color the element a_3=3, paint in the third color the elements: a_2=2, a_5=4 and a_6=2. In the second example, you can use one color to paint all the elements.In the third example, one possible way to paint the elements in 4 colors is: paint in the first color the elements: a_4=4, a_6=2 and a_7=2, paint in the second color the elements: a_2=6, a_5=3 and a_8=3, paint in the third color the element a_3=5, paint in the fourth color the element a_1=7. | 6
10 2 3 5 4 2
| 3 | 1 second | 256 megabytes | ['greedy', 'implementation', 'math', '*800'] |
H. Red Blue Treetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree of n nodes. The tree is rooted at node 1, which is not considered as a leaf regardless of its degree.Each leaf of the tree has one of the two colors: red or blue. Leaf node v initially has color s_{v}.The color of each of the internal nodes (including the root) is determined as follows. Let b be the number of blue immediate children, and r be the number of red immediate children of a given vertex. Then the color of this vertex is blue if and only if b - r \ge k, otherwise red. Integer k is a parameter that is same for all the nodes.You need to handle the following types of queries: 1 v: print the color of node v; 2 v c: change the color of leaf v to c (c = 0 means red, c = 1 means blue); 3 h: update the current value of k to h. InputThe first line of the input consists of two integers n and k (2 \le n \le 10^{5}, -n \le k \le n) — the number of nodes and the initial parameter k.Each of the next n - 1 lines contains two integers u and v (1 \le u,v \le n), denoting that there is an edge between vertices u and v.The next line consists of n space separated integers — the initial array s (-1 \le s_i \le 1). s_{i} = 0 means that the color of node i is red. s_{i} = 1 means that the color of node i is blue. s_{i} = -1 means that the node i is not a leaf.The next line contains an integer q (1 \le q \le 10^5), the number of queries.q lines follow, each containing a query in one of the following queries: 1 v (1 \le v \le n): print the color of node v; 2 v c (1 \le v \le n, c = 0 or c = 1): change the color of leaf v to c (c = 0 means red, c = 1 means blue). It is guaranteed that v is a leaf; 3 h (-n \le h \le n): update the current value of k to h. OutputFor each query of the first type, print 0 if the color of vertex v is red, and 1 otherwise.ExampleInput
5 2
1 2
1 3
2 4
2 5
-1 -1 0 1 0
9
1 1
1 2
3 -2
1 1
1 2
3 1
2 5 1
1 1
1 2
Output
0
0
1
1
0
1
Note Figures:(i) The initial tree (ii) The tree after the 3rd query (iii) The tree after the 7th query | 5 2
1 2
1 3
2 4
2 5
-1 -1 0 1 0
9
1 1
1 2
3 -2
1 1
1 2
3 1
2 5 1
1 1
1 2
| 0 0 1 1 0 1 | 5 seconds | 256 megabytes | ['data structures', 'implementation', 'trees', '*3500'] |
G. Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and k.You need to construct k regular polygons having same circumcircle, with distinct number of sides l between 3 and n. Illustration for the first example. You can rotate them to minimize the total number of distinct points on the circle. Find the minimum number of such points.InputThe only line of input contains two integers n and k (3 \le n \le 10^{6}, 1 \le k \le n-2), the maximum number of sides of a polygon and the number of polygons to construct, respectively.OutputPrint a single integer — the minimum number of points required for k polygons.ExamplesInput
6 2
Output
6
Input
200 50
Output
708
NoteIn the first example, we have n = 6 and k = 2. So, we have 4 polygons with number of sides 3, 4, 5 and 6 to choose from and if we choose the triangle and the hexagon, then we can arrange them as shown in the picture in the statement.Hence, the minimum number of points required on the circle is 6, which is also the minimum overall possible sets. | 6 2
| 6 | 1 second | 256 megabytes | ['greedy', 'math', 'number theory', '*2800'] |
F. Bits And Piecestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers.You need to find the maximum value of a_{i} | ( a_{j} \& a_{k} ) over all triplets (i,j,k) such that i < j < k.Here \& denotes the bitwise AND operation, and | denotes the bitwise OR operation.InputThe first line of input contains the integer n (3 \le n \le 10^{6}), the size of the array a.Next line contains n space separated integers a_1, a_2, ..., a_n (0 \le a_{i} \le 2 \cdot 10^{6}), representing the elements of the array a.OutputOutput a single integer, the maximum value of the expression given in the statement. ExamplesInput
3
2 4 6
Output
6
Input
4
2 8 4 7
Output
12
NoteIn the first example, the only possible triplet is (1, 2, 3). Hence, the answer is 2 | (4 \& 6) = 6.In the second example, there are 4 possible triplets: (1, 2, 3), value of which is 2|(8\&4) = 2. (1, 2, 4), value of which is 2|(8\&7) = 2. (1, 3, 4), value of which is 2|(4\&7) = 6. (2, 3, 4), value of which is 8|(4\&7) = 12. The maximum value hence is 12. | 3
2 4 6
| 6 | 2 seconds | 256 megabytes | ['bitmasks', 'dfs and similar', 'dp', 'greedy', '*2600'] |
E. Let Them Slidetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n arrays that can have different sizes. You also have a table with w columns and n rows. The i-th array is placed horizontally in the i-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.You need to find the maximum sum of the integers in the j-th column for each j from 1 to w independently. Optimal placements for columns 1, 2 and 3 are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.InputThe first line contains two integers n (1 \le n \le 10^{6}) and w (1 \le w \le 10^{6}) — the number of arrays and the width of the table.Each of the next n lines consists of an integer l_{i} (1 \le l_{i} \le w), the length of the i-th array, followed by l_{i} integers a_{i1}, a_{i2}, \ldots, a_{il_i} (-10^{9} \le a_{ij} \le 10^{9}) — the elements of the array.The total length of the arrays does no exceed 10^{6}.OutputPrint w integers, the i-th of them should be the maximum sum for column i.ExamplesInput
3 3
3 2 4 8
2 2 5
2 6 3
Output
10 15 16
Input
2 2
2 7 8
1 -8
Output
7 8
NoteIllustration for the first example is in the statement. | 3 3
3 2 4 8
2 2 5
2 6 3
| 10 15 16 | 4 seconds | 256 megabytes | ['data structures', 'implementation', '*2200'] |
D. Restore Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p_{1},p_{2}, \ldots,p_{n} is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4].There is a hidden permutation of length n.For each index i, you are given s_{i}, which equals to the sum of all p_{j} such that j < i and p_{j} < p_{i}. In other words, s_i is the sum of elements before the i-th element that are smaller than the i-th element.Your task is to restore the permutation.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^{5}) — the size of the permutation.The second line contains n integers s_{1}, s_{2}, \ldots, s_{n} (0 \le s_{i} \le \frac{n(n-1)}{2}).It is guaranteed that the array s corresponds to a valid permutation of length n.OutputPrint n integers p_{1}, p_{2}, \ldots, p_{n} — the elements of the restored permutation. We can show that the answer is always unique.ExamplesInput
3
0 0 0
Output
3 2 1
Input
2
0 1
Output
1 2
Input
5
0 1 1 1 10
Output
1 4 3 2 5
NoteIn the first example for each i there is no index j satisfying both conditions, hence s_i are always 0.In the second example for i = 2 it happens that j = 1 satisfies the conditions, so s_2 = p_1.In the third example for i = 2, 3, 4 only j = 1 satisfies the conditions, so s_2 = s_3 = s_4 = 1. For i = 5 all j = 1, 2, 3, 4 are possible, so s_5 = p_1 + p_2 + p_3 + p_4 = 10. | 3
0 0 0
| 3 2 1 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', 'implementation', '*1900'] |
C. Magic Gridtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us define a magic grid to be a square matrix of integers of size n \times n, satisfying the following conditions. All integers from 0 to (n^2 - 1) inclusive appear in the matrix exactly once. Bitwise XOR of all elements in a row or a column must be the same for each row and column. You are given an integer n which is a multiple of 4. Construct a magic grid of size n \times n.InputThe only line of input contains an integer n (4 \leq n \leq 1000). It is guaranteed that n is a multiple of 4.OutputPrint a magic grid, i.e. n lines, the i-th of which contains n space-separated integers, representing the i-th row of the grid.If there are multiple answers, print any. We can show that an answer always exists.ExamplesInput
4
Output
8 9 1 13
3 12 7 5
0 2 4 11
6 10 15 14Input
8
Output
19 55 11 39 32 36 4 52
51 7 35 31 12 48 28 20
43 23 59 15 0 8 16 44
3 47 27 63 24 40 60 56
34 38 6 54 17 53 9 37
14 50 30 22 49 5 33 29
2 10 18 46 41 21 57 13
26 42 62 58 1 45 25 61NoteIn the first example, XOR of each row and each column is 13.In the second example, XOR of each row and each column is 60. | 4
| 8 9 1 13 3 12 7 5 0 2 4 11 6 10 15 14 | 1 second | 256 megabytes | ['constructive algorithms', '*1800'] |
B. Uniquenesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_{1}, a_{2}, \ldots, a_{n}. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.In other words, at most one time you can choose two integers l and r (1 \leq l \leq r \leq n) and delete integers a_l, a_{l+1}, \ldots, a_r from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.InputThe first line of the input contains a single integer n (1 \le n \le 2000) — the number of elements in the given array.The next line contains n spaced integers a_{1}, a_{2}, \ldots, a_{n} (1 \le a_{i} \le 10^{9}) — the elements of the array. OutputPrint a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print 0.ExamplesInput
3
1 2 3
Output
0
Input
4
1 1 2 2
Output
2
Input
5
1 4 1 4 9
Output
2
NoteIn the first example all the elements are already distinct, therefore no subsegment needs to be removed.In the second example you can remove the subsegment from index 2 to 3.In the third example you can remove the subsegments from index 1 to 2, or from index 2 to 3, or from index 3 to 4. | 3
1 2 3
| 0 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'implementation', 'two pointers', '*1500'] |
A. XORinaccitime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: f(0) = a; f(1) = b; f(n) = f(n-1) \oplus f(n-2) when n > 1, where \oplus denotes the bitwise XOR operation. You are given three integers a, b, and n, calculate f(n).You have to answer for T independent test cases.InputThe input contains one or more independent test cases.The first line of input contains a single integer T (1 \le T \le 10^3), the number of test cases.Each of the T following lines contains three space-separated integers a, b, and n (0 \le a, b, n \le 10^9) respectively.OutputFor each test case, output f(n).ExampleInput
3
3 4 2
4 5 0
325 265 1231232
Output
7
4
76
NoteIn the first example, f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7. | 3
3 4 2
4 5 0
325 265 1231232
| 7 4 76 | 1 second | 256 megabytes | ['math', '*900'] |
G. Indie Albumtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMishka's favourite experimental indie band has recently dropped a new album! Songs of that album share one gimmick. Each name s_i is one of the following types: 1~c — a single lowercase Latin letter; 2~j~c — name s_j (1 \le j < i) with a single lowercase Latin letter appended to its end. Songs are numbered from 1 to n. It's guaranteed that the first song is always of type 1.Vova is rather interested in the new album but he really doesn't have the time to listen to it entirely. Thus he asks Mishka some questions about it to determine if some song is worth listening to. Questions have the following format: i~t — count the number of occurrences of string t in s_i (the name of the i-th song of the album) as a continuous substring, t consists only of lowercase Latin letters. Mishka doesn't question the purpose of that information, yet he struggles to provide it. Can you please help Mishka answer all Vova's questions?InputThe first line contains a single integer n (1 \le n \le 4 \cdot 10^5) — the number of songs in the album.Each of the next n lines contains the desciption of the i-th song of the album in the following format: 1~c — s_i is a single lowercase Latin letter; 2~j~c — s_i is the name s_j (1 \le j < i) with a single lowercase Latin letter appended to its end. The next line contains a single integer m (1 \le m \le 4 \cdot 10^5) — the number of Vova's questions.Each of the next m lines contains the desciption of the j-th Vova's question in the following format: i~t (1 \le i \le n, 1 \le |t| \le 4 \cdot 10^5) — count the number of occurrences of string t in s_i (the name of the i-th song of the album) as a continuous substring, t consists only of lowercase Latin letters. It's guaranteed that the total length of question strings t doesn't exceed 4 \cdot 10^5.OutputFor each question print a single integer — the number of occurrences of the question string t in the name of the i-th song of the album as a continuous substring.ExampleInput
20
1 d
2 1 a
2 2 d
2 3 a
2 4 d
2 5 a
2 6 d
2 7 a
1 d
2 9 o
2 10 k
2 11 i
2 12 d
2 13 o
2 14 k
2 15 i
2 1 o
2 17 k
2 18 i
2 15 i
12
8 da
8 dada
8 ada
6 dada
3 dada
19 doki
19 ok
16 doki
15 doki
9 d
1 a
20 doki
Output
4
3
3
2
0
1
1
2
1
1
0
2
NoteSong names of the first example: d da dad dada dadad dadada dadadad dadadada d do dok doki dokid dokido dokidok dokidoki do dok doki dokidoki Thus the occurrences for each question string are: string "da" starts in positions [1, 3, 5, 7] in the name "dadadada"; string "dada" starts in positions [1, 3, 5] in the name "dadadada"; string "ada" starts in positions [2, 4, 6] in the name "dadadada"; string "dada" starts in positions [1, 3] in the name "dadada"; no occurrences of string "dada" in the name "dad"; string "doki" starts in position [1] in the name "doki"; string "ok" starts in position [2] in the name "doki"; string "doki" starts in positions [1, 5] in the name "dokidoki"; string "doki" starts in position [1] in the name "dokidok"; string "d" starts in position [1] in the name "d"; no occurrences of string "a" in the name "d"; string "doki" starts in positions [1, 5] in the name "dokidoki". | 20
1 d
2 1 a
2 2 d
2 3 a
2 4 d
2 5 a
2 6 d
2 7 a
1 d
2 9 o
2 10 k
2 11 i
2 12 d
2 13 o
2 14 k
2 15 i
2 1 o
2 17 k
2 18 i
2 15 i
12
8 da
8 dada
8 ada
6 dada
3 dada
19 doki
19 ok
16 doki
15 doki
9 d
1 a
20 doki
| 4 3 3 2 0 1 1 2 1 1 0 2 | 3 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'hashing', 'string suffix structures', 'strings', 'trees', '*2700'] |
F. Remainder Problemtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of 500000 integers (numbered from 1 to 500000). Initially all elements of a are zero.You have to process two types of queries to this array: 1 x y — increase a_x by y; 2 x y — compute \sum\limits_{i \in R(x, y)} a_i, where R(x, y) is the set of all integers from 1 to 500000 which have remainder y modulo x. Can you process all the queries?InputThe first line contains one integer q (1 \le q \le 500000) — the number of queries.Then q lines follow, each describing a query. The i-th line contains three integers t_i, x_i and y_i (1 \le t_i \le 2). If t_i = 1, then it is a query of the first type, 1 \le x_i \le 500000, and -1000 \le y_i \le 1000. If t_i = 2, then it it a query of the second type, 1 \le x_i \le 500000, and 0 \le y_i < x_i.It is guaranteed that there will be at least one query of type 2.OutputFor each query of type 2 print one integer — the answer to it.ExampleInput
5
1 3 4
2 3 0
2 4 3
1 4 -4
2 1 0
Output
4
4
0
| 5
1 3 4
2 3 0
2 4 3
1 4 -4
2 1 0
| 4 4 0 | 4 seconds | 512 megabytes | ['brute force', 'data structures', 'implementation', '*2100'] |
E. XOR Guessingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis 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.OutputTo 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.InteractionBefore giving the answer, you may submit no more than 2 queries. To ask a query, print one line in the following format: ? a_1 a_2 ... a_{100}, where every a_j should be an integer from the range [0, 2^{14} - 1]. The line should be ended with a line break character. After submitting a query, flush the output and read the answer to your query — the value of a_i \oplus x for some i \in [1, 100]. No integer can be used in queries more than once.If you submit an incorrect query (or ask more than 2 queries), the answer to it will be one integer -1. After receiving such an answer, your program should terminate immediately — otherwise you may receive verdict "Runtime error", "Time limit exceeded" or some other verdict instead of "Wrong answer".ExampleInput
0
32Output
? 3 5 6
? 32 24 37
! 5NoteThe 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. | 0
32 | ? 3 5 6 ? 32 24 37 ! 5 | 1 second | 256 megabytes | ['bitmasks', 'interactive', 'math', '*1900'] |
D. Number Of Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of n pairs of integers: (a_1, b_1), (a_2, b_2), \dots , (a_n, b_n). This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences: s = [(1, 2), (3, 2), (3, 1)] is bad because the sequence of first elements is sorted: [1, 3, 3]; s = [(1, 2), (3, 2), (1, 2)] is bad because the sequence of second elements is sorted: [2, 2, 2]; s = [(1, 1), (2, 2), (3, 3)] is bad because both sequences (the sequence of first elements and the sequence of second elements) are sorted; s = [(1, 3), (3, 3), (2, 2)] is good because neither the sequence of first elements ([1, 3, 2]) nor the sequence of second elements ([3, 3, 2]) is sorted. Calculate the number of permutations of size n such that after applying this permutation to the sequence s it turns into a good sequence. A permutation p of size n is a sequence p_1, p_2, \dots , p_n consisting of n distinct integers from 1 to n (1 \le p_i \le n). If you apply permutation p_1, p_2, \dots , p_n to the sequence s_1, s_2, \dots , s_n you get the sequence s_{p_1}, s_{p_2}, \dots , s_{p_n}. For example, if s = [(1, 2), (1, 3), (2, 3)] and p = [2, 3, 1] then s turns into [(1, 3), (2, 3), (1, 2)].InputThe first line contains one integer n (1 \le n \le 3 \cdot 10^5).The next n lines contains description of sequence s. The i-th line contains two integers a_i and b_i (1 \le a_i, b_i \le n) — the first and second elements of i-th pair in the sequence.The sequence s may contain equal elements.OutputPrint the number of permutations of size n such that after applying this permutation to the sequence s it turns into a good sequence. Print the answer modulo 998244353 (a prime number).ExamplesInput
3
1 1
2 2
3 1
Output
3
Input
4
2 3
2 2
2 1
2 4
Output
0
Input
3
1 1
1 1
2 3
Output
4
NoteIn first test case there are six permutations of size 3: if p = [1, 2, 3], then s = [(1, 1), (2, 2), (3, 1)] — bad sequence (sorted by first elements); if p = [1, 3, 2], then s = [(1, 1), (3, 1), (2, 2)] — bad sequence (sorted by second elements); if p = [2, 1, 3], then s = [(2, 2), (1, 1), (3, 1)] — good sequence; if p = [2, 3, 1], then s = [(2, 2), (3, 1), (1, 1)] — good sequence; if p = [3, 1, 2], then s = [(3, 1), (1, 1), (2, 2)] — bad sequence (sorted by second elements); if p = [3, 2, 1], then s = [(3, 1), (2, 2), (1, 1)] — good sequence. | 3
1 1
2 2
3 1
| 3 | 2 seconds | 256 megabytes | ['combinatorics', '*1800'] |
C. Gas Pipelinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units. Each unit of gas pipeline costs us a bourles, and each unit of pillar — b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.InputThe fist line contains one integer T (1 \le T \le 100) — the number of queries. Next 2 \cdot T lines contain independent queries — one query per two lines.The first line contains three integers n, a, b (2 \le n \le 2 \cdot 10^5, 1 \le a \le 10^8, 1 \le b \le 10^8) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.The second line contains binary string s (|s| = n, s_i \in \{0, 1\}, s_1 = s_n = 0) — the description of the road.It's guaranteed that the total length of all strings s doesn't exceed 2 \cdot 10^5.OutputPrint T integers — one per query. For each query print the minimum possible cost of the constructed pipeline.ExampleInput
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | 4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
| 94 25 2900000000 13 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*1500'] |
B. Square Fillingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two matrices A and B. Each matrix contains exactly n rows and m columns. Each element of A is either 0 or 1; each element of B is initially 0.You may perform some operations with matrix B. During each operation, you choose any submatrix of B having size 2 \times 2, and replace every element in the chosen submatrix with 1. In other words, you choose two integers x and y such that 1 \le x < n and 1 \le y < m, and then set B_{x, y}, B_{x, y + 1}, B_{x + 1, y} and B_{x + 1, y + 1} to 1.Your goal is to make matrix B equal to matrix A. Two matrices A and B are equal if and only if every element of matrix A is equal to the corresponding element of matrix B.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes B equal to A. Note that you don't have to minimize the number of operations.InputThe first line contains two integers n and m (2 \le n, m \le 50).Then n lines follow, each containing m integers. The j-th integer in the i-th line is A_{i, j}. Each integer is either 0 or 1.OutputIf it is impossible to make B equal to A, print one integer -1.Otherwise, print any sequence of operations that transforms B into A in the following format: the first line should contain one integer k — the number of operations, and then k lines should follow, each line containing two integers x and y for the corresponding operation (set B_{x, y}, B_{x, y + 1}, B_{x + 1, y} and B_{x + 1, y + 1} to 1). The condition 0 \le k \le 2500 should hold.ExamplesInput
3 3
1 1 1
1 1 1
0 1 1
Output
3
1 1
1 2
2 2
Input
3 3
1 0 1
1 0 1
0 0 0
Output
-1
Input
3 2
0 0
0 0
0 0
Output
0
NoteThe sequence of operations in the first example: \begin{matrix} 0 & 0 & 0 & & 1 & 1 & 0 & & 1 & 1 & 1 & & 1 & 1 & 1 \\ 0 & 0 & 0 & \rightarrow & 1 & 1 & 0 & \rightarrow & 1 & 1 & 1 & \rightarrow & 1 & 1 & 1 \\ 0 & 0 & 0 & & 0 & 0 & 0 & & 0 & 0 & 0 & & 0 & 1 & 1 \end{matrix} | 3 3
1 1 1
1 1 1
0 1 1
| 3 1 1 1 2 2 2 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*1200'] |
A. There Are Two Types Of Burgerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for h dollars and one chicken burger for c dollars. Calculate the maximum profit you can achieve.You have to answer t independent queries.InputThe first line contains one integer t (1 \le t \le 100) – the number of queries.The first line of each query contains three integers b, p and f (1 \le b, ~p, ~f \le 100) — the number of buns, beef patties and chicken cutlets in your restaurant.The second line of each query contains two integers h and c (1 \le h, ~c \le 100) — the hamburger and chicken burger prices in your restaurant.OutputFor each query print one integer — the maximum profit you can achieve.ExampleInput
3
15 2 3
5 10
7 5 2
10 12
1 100 100
100 100
Output
40
34
0
NoteIn first query you have to sell two hamburgers and three chicken burgers. Your income is 2 \cdot 5 + 3 \cdot 10 = 40.In second query you have to ell one hamburgers and two chicken burgers. Your income is 1 \cdot 10 + 2 \cdot 12 = 34.In third query you can not create any type of burgers because because you have only one bun. So your income is zero. | 3
15 2 3
5 10
7 5 2
10 12
1 100 100
100 100
| 40 34 0 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*800'] |
B. Make Product Equal Onetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n numbers a_1, a_2, \dots, a_n. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract 1 from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to 1, in other words, we want a_1 \cdot a_2 \dots \cdot a_n = 1. For example, for n = 3 and numbers [1, -3, 0] we can make product equal to 1 in 3 coins: add 1 to second element, add 1 to second element again, subtract 1 from third element, so that array becomes [1, -1, -1]. And 1\cdot (-1) \cdot (-1) = 1.What is the minimum cost we will have to pay to do that?InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of numbers.The second line contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9) — the numbers.OutputOutput a single number — the minimal number of coins you need to pay to make the product equal to 1.ExamplesInput
2
-1 1
Output
2Input
4
0 0 0 0
Output
4Input
5
-5 -3 5 3 0
Output
13NoteIn the first example, you can change 1 to -1 or -1 to 1 in 2 coins.In the second example, you have to apply at least 4 operations for the product not to be 0.In the third example, you can change -5 to -1 in 4 coins, -3 to -1 in 2 coins, 5 to 1 in 4 coins, 3 to 1 in 2 coins, 0 to 1 in 1 coin. | 2
-1 1
| 2 | 1 second | 256 megabytes | ['dp', 'implementation', '*900'] |
A. Choose Two Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array A, consisting of n positive integers a_1, a_2, \dots, a_n, and an array B, consisting of m positive integers b_1, b_2, \dots, b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can choose 1 from A and 4 from B, as number 5 = 1 + 4 doesn't belong to A and doesn't belong to B. However, we can't choose 2 from A and 1 from B, as 3 = 2 + 1 belongs to B.It can be shown that such a pair exists. If there are multiple answers, print any.Choose and print any such two numbers.InputThe first line contains one integer n (1\le n \le 100) — the number of elements of A.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 200) — the elements of A.The third line contains one integer m (1\le m \le 100) — the number of elements of B.The fourth line contains m different integers b_1, b_2, \dots, b_m (1 \le b_i \le 200) — the elements of B.It can be shown that the answer always exists.OutputOutput two numbers a and b such that a belongs to A, b belongs to B, but a+b doesn't belong to nor A neither B.If there are multiple answers, print any.ExamplesInput
1
20
2
10 20
Output
20 20Input
3
3 2 2
5
1 5 7 7 9
Output
3 1
Input
4
1 3 5 7
4
7 5 3 1
Output
1 1
NoteIn the first example, we can choose 20 from array [20] and 20 from array [10, 20]. Number 40 = 20 + 20 doesn't belong to any of those arrays. However, it is possible to choose 10 from the second array too.In the second example, we can choose 3 from array [3, 2, 2] and 1 from array [1, 5, 7, 7, 9]. Number 4 = 3 + 1 doesn't belong to any of those arrays.In the third example, we can choose 1 from array [1, 3, 5, 7] and 1 from array [7, 5, 3, 1]. Number 2 = 1 + 1 doesn't belong to any of those arrays. | 1
20
2
10 20
| 20 20 | 1 second | 256 megabytes | ['math', 'sortings', '*800'] |
F. Beauty of a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDefine the beauty of a permutation of numbers from 1 to n (p_1, p_2, \dots, p_n) as number of pairs (L, R) such that 1 \le L \le R \le n and numbers p_L, p_{L+1}, \dots, p_R are consecutive R-L+1 numbers in some order. For example, the beauty of the permutation (1, 2, 5, 3, 4) equals 9, and segments, corresponding to pairs, are [1], [2], [5], [4], [3], [1, 2], [3, 4], [5, 3, 4], [1, 2, 5, 3, 4].Answer q independent queries. In each query, you will be given integers n and k. Determine if there exists a permutation of numbers from 1 to n with beauty equal to k, and if there exists, output one of them.InputThe first line contains a single integer q (1\le q \le 10\,000) — the number of queries.Follow q lines. Each line contains two integers n, k (1 \le n \le 100, 1 \le k \le \frac{n(n+1)}{2}) — the length of permutation and needed beauty respectively.OutputFor a query output "NO", if such a permutation doesn't exist. Otherwise, output "YES", and in the next line output n numbers — elements of permutation in the right order.ExamplesInput
4
1 1
5 6
5 8
5 10
Output
YES
1
YES
2 4 1 5 3
NO
YES
2 3 1 4 5
Input
2
4 10
100 1
Output
YES
1 2 3 4
NO
NoteLet's look at the first example.The first query: in (1) there is only one segment consisting of consecutive numbers — the entire permutation.The second query: in (2, 4, 1, 5, 3) there are 6 such segments: [2], [4], [1], [5], [3], [2, 4, 1, 5, 3].There is no such permutation for the second query.The fourth query: in (2, 3, 1, 4, 5) there are 10 such segments: [2], [3], [1], [4], [5], [2, 3], [2, 3, 1], [2, 3, 1, 4], [4, 5], [2, 3, 1, 4, 5]. | 4
1 1
5 6
5 8
5 10
| YES 1 YES 2 4 1 5 3 NO YES 2 3 1 4 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*3400'] |
E. Expected Value Againtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given integers n, k. Let's consider the alphabet consisting of k different elements.Let beauty f(s) of the string s be the number of indexes i, 1\le i<|s|, for which prefix of s of length i equals to suffix of s of length i. For example, beauty of the string abacaba equals 2, as for i = 1, 3 prefix and suffix of length i are equal.Consider all words of length n in the given alphabet. Find the expected value of f(s)^2 of a uniformly chosen at random word. We can show that it can be expressed as \frac{P}{Q}, where P and Q are coprime and Q isn't divided by 10^9 + 7. Output P\cdot Q^{-1} \bmod 10^9 + 7.InputThe first and the only line contains two integers n, k (1\le n \le 10^5, 1\le k\le 10^9) — the length of a string and the size of alphabet respectively.OutputOutput a single integer — P\times Q^{-1} \bmod 10^9 + 7.ExamplesInput
2 3
Output
333333336
Input
1 5
Output
0
Input
100 1
Output
9801
Input
10 10
Output
412377396
NoteIn the first example, there are 9 words of length 2 in alphabet of size 3 — aa, ab, ac, ba, bb, bc, ca, cb, cc. 3 of them have beauty 1 and 6 of them have beauty 0, so the average value is \frac{1}{3}.In the third example, there is only one such word, and it has beauty 99, so the average value is 99^2. | 2 3
| 333333336 | 4 seconds | 256 megabytes | ['combinatorics', 'strings', '*3100'] |
D. Almost Alltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied:For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from 1 to \lfloor \frac{2n^2}{9} \rfloor has to be written on the blackboard at least once. It is guaranteed that such an arrangement exists.InputThe first line contains a single integer n (1 \le n \le 1000) — the number of nodes.Each of the next n-1 lines contains two integers u and v (1 \le u, v \le n, u \neq v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.OutputOutput n-1 lines, each of form u v x (0 \le x \le 10^6), which will mean that you wrote number x on the edge between u, v. Set of edges (u, v) has to coincide with the set of edges of the input graph, but you can output edges in any order. You can also output ends of edges in an order different from the order in input.ExamplesInput
3
2 3
2 1
Output
3 2 1
1 2 2
Input
4
2 4
2 3
2 1
Output
4 2 1
3 2 2
1 2 3
Input
5
1 2
1 3
1 4
2 5
Output
2 1 1
5 2 1
3 1 3
4 1 6
NoteIn the first example, distance between nodes 1 and 2 is equal to 2, between nodes 2 and 3 to 1, between 1 and 3 to 3.In the third example, numbers from 1 to 9 (inclusive) will be written on the blackboard, while we need just from 1 to 5 to pass the test. | 3
2 3
2 1
| 3 2 1 1 2 2 | 1 second | 256 megabytes | ['constructive algorithms', 'trees', '*2700'] |
C. Palindromic Pathstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problemYou are given a grid n\times n, where n is odd. Rows are enumerated from 1 to n from up to down, columns are enumerated from 1 to n from left to right. Cell, standing on the intersection of row x and column y, is denoted by (x, y).Every cell contains 0 or 1. It is known that the top-left cell contains 1, and the bottom-right cell contains 0.We want to know numbers in all cells of the grid. To do so we can ask the following questions: "? x_1 y_1 x_2 y_2", where 1 \le x_1 \le x_2 \le n, 1 \le y_1 \le y_2 \le n, and x_1 + y_1 + 2 \le x_2 + y_2. In other words, we output two different cells (x_1, y_1), (x_2, y_2) of the grid such that we can get from the first to the second by moving only to the right and down, and they aren't adjacent.As a response to such question you will be told if there exists a path between (x_1, y_1) and (x_2, y_2), going only to the right or down, numbers in cells of which form a palindrome.For example, paths, shown in green, are palindromic, so answer for "? 1 1 2 3" and "? 1 2 3 3" would be that there exists such path. However, there is no palindromic path between (1, 1) and (3, 1). Determine all cells of the grid by asking not more than n^2 questions. It can be shown that the answer always exists.InputThe first line contains odd integer (3 \le n < 50) — the side of the grid.InteractionYou begin the interaction by reading n.To ask a question about cells (x_1, y_1), (x_2, y_2), in a separate line output "? x_1 y_1 x_2 y_2".Numbers in the query have to satisfy 1 \le x_1 \le x_2 \le n, 1 \le y_1 \le y_2 \le n, and x_1 + y_1 + 2 \le x_2 + y_2. Don't forget to 'flush', to get the answer.In response, you will receive 1, if there exists a path going from (x_1, y_1) to (x_2, y_2) only to the right or down, numbers in cells of which form a palindrome, and 0 otherwise.In case your query is invalid or you asked more than n^2 queries, program will print -1 and will finish interaction. You will receive Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine numbers in all cells, output "!".Then output n lines, the i-th of which is a string of length n, corresponding to numbers in the i-th row of the grid.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack FormatTo hack, use the following format.The first line should contain a single odd integer n (side of your grid).The i-th of n following lines should contain a string of length n corresponding to the i-th row of the grid. Top left element of the grid has to be equal to 1, bottom right has to be equal to 0.ExampleInput
3
0
1
0
1
1
1
1Output
? 1 1 1 3
? 1 1 2 3
? 2 1 2 3
? 3 1 3 3
? 2 2 3 3
? 1 2 3 2
? 1 2 3 3
!
100
001
000 | 3
0
1
0
1
1
1
1 | ? 1 1 1 3 ? 1 1 2 3 ? 2 1 2 3 ? 3 1 3 3 ? 2 2 3 3 ? 1 2 3 2 ? 1 2 3 3 ! 100 001 000 | 1 second | 256 megabytes | ['implementation', 'interactive', '*2400'] |
B. Shortest Cycletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integer numbers a_1, a_2, \dots, a_n. Consider graph on n nodes, in which nodes i, j (i\neq j) are connected if and only if, a_i AND a_j\neq 0, where AND denotes the bitwise AND operation.Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.InputThe first line contains one integer n (1 \le n \le 10^5) — number of numbers.The second line contains n integer numbers a_1, a_2, \dots, a_n (0 \le a_i \le 10^{18}).OutputIf the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.ExamplesInput
4
3 6 28 9
Output
4Input
5
5 12 9 16 48
Output
3Input
4
1 2 4 8
Output
-1NoteIn the first example, the shortest cycle is (9, 3, 6, 28).In the second example, the shortest cycle is (5, 12, 9).The graph has no cycles in the third example. | 4
3 6 28 9
| 4 | 1 second | 256 megabytes | ['bitmasks', 'brute force', 'graphs', 'shortest paths', '*1900'] |
A. Almost Equaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied:For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more than by 1.For example, choose n = 3. On the left you can see an example of a valid arrangement: 1 + 4 + 5 = 10, 4 + 5 + 2 = 11, 5 + 2 + 3 = 10, 2 + 3 + 6 = 11, 3 + 6 + 1 = 10, 6 + 1 + 4 = 11, any two numbers differ by at most 1. On the right you can see an invalid arrangement: for example, 5 + 1 + 6 = 12, and 3 + 2 + 4 = 9, 9 and 12 differ more than by 1. InputThe first and the only line contain one integer n (1 \le n \le 10^5).OutputIf there is no solution, output "NO" in the first line. If there is a solution, output "YES" in the first line. In the second line output 2n numbers — numbers from 1 to 2n in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.ExamplesInput
3
Output
YES
1 4 5 2 3 6 Input
4
Output
NONoteExample from the statement is shown for the first example. It can be proved that there is no solution in the second example. | 3
| YES 1 4 5 2 3 6 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1200'] |
E. Natasha, Sasha and the Prefix Sumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNatasha's favourite numbers are n and 1, and Sasha's favourite numbers are m and -1. One day Natasha and Sasha met and wrote down every possible array of length n+m such that some n of its elements are equal to 1 and another m elements are equal to -1. For each such array they counted its maximal prefix sum, probably an empty one which is equal to 0 (in another words, if every nonempty prefix sum is less to zero, then it is considered equal to zero). Formally, denote as f(a) the maximal prefix sum of an array a_{1, \ldots ,l} of length l \geq 0. Then: f(a) = \max (0, \smash{\displaystyle\max_{1 \leq i \leq l}} \sum_{j=1}^{i} a_j )Now they want to count the sum of maximal prefix sums for each such an array and they are asking you to help. As this sum can be very large, output it modulo 998\: 244\: 853.InputThe only line contains two integers n and m (0 \le n,m \le 2\,000).OutputOutput the answer to the problem modulo 998\: 244\: 853.ExamplesInput0 2Output0Input2 0Output2Input2 2Output5Input2000 2000Output674532367NoteIn the first example the only possible array is [-1,-1], its maximal prefix sum is equal to 0. In the second example the only possible array is [1,1], its maximal prefix sum is equal to 2. There are 6 possible arrays in the third example:[1,1,-1,-1], f([1,1,-1,-1]) = 2[1,-1,1,-1], f([1,-1,1,-1]) = 1[1,-1,-1,1], f([1,-1,-1,1]) = 1[-1,1,1,-1], f([-1,1,1,-1]) = 1[-1,1,-1,1], f([-1,1,-1,1]) = 0[-1,-1,1,1], f([-1,-1,1,1]) = 0So the answer for the third example is 2+1+1+1+0+0 = 5. | Input0 2 | Output0 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', 'number theory', '*2300'] |
D2. Kirk and a Binary String (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions: For any l and r (1 \leq l \leq r \leq n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} \ldots s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} \ldots t_{r}; The number of zeroes in t is the maximum possible.A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, \ldots, i_k such that i_1 < i_2 < \ldots < i_k and p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}. The length of the subsequence is k.If there are multiple substrings which satisfy the conditions, output any.InputThe first line contains a binary string of length not more than 10^5.OutputOutput a binary string which satisfied the above conditions. If there are many such strings, output any of them.ExamplesInput
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
NoteIn the first example: For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1; For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01; For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00; For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1; The second example is similar to the first one. | 110
| 010 | 1 second | 256 megabytes | ['data structures', 'greedy', 'math', 'strings', '*2100'] |
D1. Kirk and a Binary String (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions: For any l and r (1 \leq l \leq r \leq n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} \ldots s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} \ldots t_{r}; The number of zeroes in t is the maximum possible.A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, \ldots, i_k such that i_1 < i_2 < \ldots < i_k and p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}. The length of the subsequence is k.If there are multiple substrings which satisfy the conditions, output any.InputThe first line contains a binary string of length not more than 2\: 000.OutputOutput a binary string which satisfied the above conditions. If there are many such strings, output any of them.ExamplesInput
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
NoteIn the first example: For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1; For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01; For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00; For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1; The second example is similar to the first one. | 110
| 010 | 1 second | 256 megabytes | ['brute force', 'greedy', 'strings', '*2000'] |
C. Anna, Svyatoslav and Mapstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe main characters have been omitted to be short.You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, \ldots, p_m of m vertexes; for each 1 \leq i < m there is an arc from p_i to p_{i+1}.Define the sequence v_1, v_2, \ldots, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, \ldots, v_k in that order.A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them. InputThe first line contains a single integer n (2 \le n \le 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops.The next line contains a single integer m (2 \le m \le 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, \ldots, p_m (1 \le p_i \le n) — the sequence of vertexes in the path. It is guaranteed that for any 1 \leq i < m there is an arc from p_i to p_{i+1}.OutputIn the first line output a single integer k (2 \leq k \leq m) — the length of the shortest good subsequence. In the second line output k integers v_1, \ldots, v_k (1 \leq v_i \leq n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.ExamplesInput
4
0110
0010
0001
1000
4
1 2 3 4
Output
3
1 2 4 Input
4
0110
0010
1001
1000
20
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
Output
11
1 2 4 2 4 2 4 2 4 2 4 Input
3
011
101
110
7
1 2 3 1 3 2 1
Output
7
1 2 3 1 3 2 1 Input
4
0110
0001
0001
1000
3
1 2 4
Output
2
1 4 NoteBelow you can see the graph from the first example:The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4. | 4
0110
0010
0001
1000
4
1 2 3 4
| 3 1 2 4 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'greedy', 'shortest paths', '*1700'] |
B. Mislove Has Lost an Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMislove had an array a_1, a_2, \cdots, a_n of n positive integers, but he has lost it. He only remembers the following facts about it: The number of different numbers in the array is not less than l and is not greater than r; For each array's element a_i either a_i = 1 or a_i is even and there is a number \dfrac{a_i}{2} in the array.For example, if n=5, l=2, r=3 then an array could be [1,2,2,4,4] or [1,1,1,1,2]; but it couldn't be [1,2,2,4,8] because this array contains 4 different numbers; it couldn't be [1,2,2,3,3] because 3 is odd and isn't equal to 1; and it couldn't be [1,1,2,2,16] because there is a number 16 in the array but there isn't a number \frac{16}{2} = 8.According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array. InputThe only input line contains three integers n, l and r (1 \leq n \leq 1\,000, 1 \leq l \leq r \leq \min(n, 20)) — an array's size, the minimal number and the maximal number of distinct elements in an array.OutputOutput two numbers — the minimal and the maximal possible sums of all elements in an array.ExamplesInput
4 2 2
Output
5 7
Input
5 1 5
Output
5 31
NoteIn the first example, an array could be the one of the following: [1,1,1,2], [1,1,2,2] or [1,2,2,2]. In the first case the minimal sum is reached and in the last case the maximal sum is reached.In the second example, the minimal sum is reached at the array [1,1,1,1,1], and the maximal one is reached at the array [1,2,4,8,16]. | 4 2 2
| 5 7 | 1 second | 256 megabytes | ['greedy', 'math', '*900'] |
A. BowWow and the Timetabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k \geq 0. Team BowWow has arrived at the station at the time s and it is trying to count how many trains have they missed; in other words, the number of trains that have departed strictly before time s. For example if s = 20, then they missed trains which have departed at 1, 4 and 16. As you are the only one who knows the time, help them!Note that the number s will be given you in a binary representation without leading zeroes.InputThe first line contains a single binary number s (0 \leq s < 2^{100}) without leading zeroes.OutputOutput a single number — the number of trains which have departed strictly before the time s.ExamplesInput
100000000
Output
4
Input
101
Output
2
Input
10100
Output
3
NoteIn the first example 100000000_2 = 256_{10}, missed trains have departed at 1, 4, 16 and 64.In the second example 101_2 = 5_{10}, trains have departed at 1 and 4.The third example is explained in the statements. | 100000000
| 4 | 1 second | 256 megabytes | ['math', '*1000'] |
F2. Complete the Projects (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.Polycarp is a very famous freelancer. His current rating is r units.Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer.Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether.To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.Your task is to calculate the maximum possible size of such subset of projects.InputThe first line of the input contains two integers n and r (1 \le n \le 100, 1 \le r \le 30000) — the number of projects and the initial rating of Polycarp, respectively.The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 \le a_i \le 30000, -300 \le b_i \le 300) — the rating required to complete the i-th project and the rating change after the project completion.OutputPrint one integer — the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose.ExamplesInput
3 4
4 6
10 -2
8 -1
Output
3
Input
5 20
45 -6
34 -15
10 34
1 27
40 -45
Output
5
Input
3 2
300 -300
1 299
1 123
Output
3
| 3 4
4 6
10 -2
8 -1
| 3 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*2300'] |
F1. Complete the Projects (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.Polycarp is a very famous freelancer. His current rating is r units.Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer.Is it possible to complete all the projects? Formally, write a program to check if such an order of the projects exists, that Polycarp has enough rating before starting each project, and he has non-negative rating after completing each project.In other words, you have to check that there exists such an order of projects in which Polycarp will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.InputThe first line of the input contains two integers n and r (1 \le n \le 100, 1 \le r \le 30000) — the number of projects and the initial rating of Polycarp, respectively.The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 \le a_i \le 30000, -300 \le b_i \le 300) — the rating required to complete the i-th project and the rating change after the project completion.OutputPrint "YES" or "NO".ExamplesInput
3 4
4 6
10 -2
8 -1
Output
YES
Input
3 5
4 -5
4 -2
1 3
Output
YES
Input
4 4
5 2
5 -3
2 1
4 -2
Output
YES
Input
3 10
10 0
10 -10
30 0
Output
NO
NoteIn the first example, the possible order is: 1, 2, 3.In the second example, the possible order is: 2, 3, 1.In the third example, the possible order is: 3, 1, 4, 2. | 3 4
4 6
10 -2
8 -1
| YES | 2 seconds | 256 megabytes | ['greedy', '*2100'] |
E. Boxerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).Write a program that for given current values a_i will find the maximum possible number of boxers in a team.It is possible that after some change the weight of some boxer is 150001 (but no more).InputThe first line contains an integer n (1 \le n \le 150000) — the number of boxers. The next line contains n integers a_1, a_2, \dots, a_n, where a_i (1 \le a_i \le 150000) is the weight of the i-th boxer.OutputPrint a single integer — the maximum possible number of people in a team.ExamplesInput43 2 4 1Output4Input61 1 1 4 4 4Output5NoteIn the first example, boxers should not change their weights — you can just make a team out of all of them.In the second example, one boxer with a weight of 1 can be increased by one (get the weight of 2), one boxer with a weight of 4 can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of 3 and 5, respectively). Thus, you can get a team consisting of boxers with weights of 5, 4, 3, 2, 1. | Input43 2 4 1 | Output4 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1500'] |
D2. Remove the Substring (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the length of the string.You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s.If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|} (where |s| is the length of s).Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s.InputThe first line of the input contains one string s consisting of at least 1 and at most 2 \cdot 10^5 lowercase Latin letters.The second line of the input contains one string t consisting of at least 1 and at most 2 \cdot 10^5 lowercase Latin letters.It is guaranteed that t is a subsequence of s.OutputPrint one integer — the maximum possible length of the substring you can remove so that t is still a subsequence of s.ExamplesInput
bbaba
bb
Output
3
Input
baaba
ab
Output
2
Input
abcde
abcde
Output
0
Input
asdfasdf
fasd
Output
3
| bbaba
bb
| 3 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'implementation', 'two pointers', '*1700'] |
D1. Remove the Substring (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the length of the string.You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s.If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|} (where |s| is the length of s).Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s.InputThe first line of the input contains one string s consisting of at least 1 and at most 200 lowercase Latin letters.The second line of the input contains one string t consisting of at least 1 and at most 200 lowercase Latin letters.It is guaranteed that t is a subsequence of s.OutputPrint one integer — the maximum possible length of the substring you can remove so that t is still a subsequence of s.ExamplesInput
bbaba
bb
Output
3
Input
baaba
ab
Output
2
Input
abcde
abcde
Output
0
Input
asdfasdf
fasd
Output
3
| bbaba
bb
| 3 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1600'] |
C. Common Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 divide each number from the array (so the answer for this test is 2).InputThe first line of the input contains one integer n (1 \le n \le 4 \cdot 10^5) — the number of elements in a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{12}), where a_i is the i-th element of a.OutputPrint one integer — the number of such positive integers x such that x divides each number from the given array (in other words, the answer is the number of common divisors of all elements in the array).ExamplesInput
5
1 2 3 4 5
Output
1
Input
6
6 90 12 18 30 18
Output
4
| 5
1 2 3 4 5
| 1 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1300'] |
B. Equal Rectanglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given 4n sticks, the length of the i-th stick is a_i.You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides a and b is a \cdot b.Your task is to say if it is possible to create exactly n rectangles of equal area or not.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 500) — the number of queries. Then q queries follow.The first line of the query contains one integer n (1 \le n \le 100) — the number of rectangles.The second line of the query contains 4n integers a_1, a_2, \dots, a_{4n} (1 \le a_i \le 10^4), where a_i is the length of the i-th stick.OutputFor each query print the answer to it. If it is impossible to create exactly n rectangles of equal area using given sticks, print "NO". Otherwise print "YES".ExampleInput
5
1
1 1 10 10
2
10 5 2 10 1 1 2 5
2
10 5 1 10 5 1 1 1
2
1 1 1 1 1 1 1 1
1
10000 10000 10000 10000
Output
YES
YES
NO
YES
YES
| 5
1
1 1 10 10
2
10 5 2 10 1 1 2 5
2
10 5 1 10 5 1 1 1
2
1 1 1 1 1 1 1 1
1
10000 10000 10000 10000
| YES YES NO YES YES | 2 seconds | 256 megabytes | ['greedy', 'math', '*1200'] |
A. Circle of Studentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation).Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after the student 1 in clockwise order (there are no students between them), the student 3 comes right after the student 2 in clockwise order, and so on, and the student n comes right after the student n - 1 in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student i should be right after the student i - 1 in counterclockwise order (this condition should be met for every i from 2 to n). For example, if the indices of students listed in clockwise order are [2, 3, 4, 5, 1], then they can start a clockwise round dance. If the students have indices [3, 2, 1, 4] in clockwise order, then they can start a counterclockwise round dance.Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 200) — the number of queries. Then q queries follow.The first line of the query contains one integer n (1 \le n \le 200) — the number of students.The second line of the query contains a permutation of indices p_1, p_2, \dots, p_n (1 \le p_i \le n), where p_i is the index of the i-th student (in clockwise order). It is guaranteed that all p_i are distinct integers from 1 to n (i. e. they form a permutation).OutputFor each query, print the answer on it. If a round dance can be started with the given order of students, print "YES". Otherwise print "NO".ExampleInput
5
4
1 2 3 4
3
1 3 2
5
1 2 3 5 4
1
1
5
3 2 1 5 4
Output
YES
YES
NO
YES
YES
| 5
4
1 2 3 4
3
1 3 2
5
1 2 3 5 4
1
1
5
3 2 1 5 4
| YES YES NO YES YES | 2 seconds | 256 megabytes | ['implementation', '*1000'] |
F. You Are Given Some Letters...time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a uppercase Latin letters 'A' and b letters 'B'.The period of the string is the smallest such positive integer k that s_i = s_{i~mod~k} (0-indexed) for each i. Note that this implies that k won't always divide a+b = |s|.For example, the period of string "ABAABAA" is 3, the period of "AAAA" is 1, and the period of "AABBB" is 5.Find the number of different periods over all possible strings with a letters 'A' and b letters 'B'.InputThe first line contains two integers a and b (1 \le a, b \le 10^9) — the number of letters 'A' and 'B', respectively.OutputPrint the number of different periods over all possible strings with a letters 'A' and b letters 'B'.ExamplesInput
2 4
Output
4
Input
5 3
Output
5
NoteAll the possible periods for the first example: 3 "BBABBA" 4 "BBAABB" 5 "BBBAAB" 6 "AABBBB" All the possible periods for the second example: 3 "BAABAABA" 5 "BAABABAA" 6 "BABAAABA" 7 "BAABAAAB" 8 "AAAAABBB" Note that these are not the only possible strings for the given periods. | 2 4
| 4 | 1 second | 256 megabytes | ['binary search', 'implementation', 'math', '*2700'] |
E. You Are Given Some Strings...time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string t and n strings s_1, s_2, \dots, s_n. All strings consist of lowercase Latin letters.Let f(t, s) be the number of occurences of string s in string t. For example, f('\text{aaabacaa}', '\text{aa}') = 3, and f('\text{ababa}', '\text{aba}') = 2.Calculate the value of \sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j), where s + t is the concatenation of strings s and t. Note that if there are two pairs i_1, j_1 and i_2, j_2 such that s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}, you should include both f(t, s_{i_1} + s_{j_1}) and f(t, s_{i_2} + s_{j_2}) in answer.InputThe first line contains string t (1 \le |t| \le 2 \cdot 10^5).The second line contains integer n (1 \le n \le 2 \cdot 10^5).Each of next n lines contains string s_i (1 \le |s_i| \le 2 \cdot 10^5).It is guaranteed that \sum\limits_{i=1}^{n} |s_i| \le 2 \cdot 10^5. All strings consist of lowercase English letters.OutputPrint one integer — the value of \sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j).ExamplesInput
aaabacaa
2
a
aa
Output
5
Input
aaabacaa
4
a
a
a
b
Output
33
| aaabacaa
2
a
aa
| 5 | 3 seconds | 256 megabytes | ['brute force', 'string suffix structures', 'strings', '*2400'] |
D. Print a 1337-string...time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given an integer n. You have to find a sequence s consisting of digits \{1, 3, 7\} such that it has exactly n subsequences equal to 1337.For example, sequence 337133377 has 6 subsequences equal to 1337: 337\underline{1}3\underline{3}\underline{3}7\underline{7} (you can remove the second and fifth characters); 337\underline{1}\underline{3}3\underline{3}7\underline{7} (you can remove the third and fifth characters); 337\underline{1}\underline{3}\underline{3}37\underline{7} (you can remove the fourth and fifth characters); 337\underline{1}3\underline{3}\underline{3}\underline{7}7 (you can remove the second and sixth characters); 337\underline{1}\underline{3}3\underline{3}\underline{7}7 (you can remove the third and sixth characters); 337\underline{1}\underline{3}\underline{3}3\underline{7}7 (you can remove the fourth and sixth characters). Note that the length of the sequence s must not exceed 10^5.You have to answer t independent queries.InputThe first line contains one integer t (1 \le t \le 10) — the number of queries. Next t lines contains a description of queries: the i-th line contains one integer n_i (1 \le n_i \le 10^9).OutputFor the i-th query print one string s_i (1 \le |s_i| \le 10^5) consisting of digits \{1, 3, 7\}. String s_i must have exactly n_i subsequences 1337. If there are multiple such strings, print any of them.ExampleInput
2
6
1
Output
113337
1337 | 2
6
1
| 113337 1337 | 1 second | 256 megabytes | ['combinatorics', 'constructive algorithms', 'math', 'strings', '*1900'] |
C. You Are Given a WASD-string...time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' — move one cell up; 'S' — move one cell down; 'A' — move one cell left; 'D' — move one cell right. Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = \text{DSAWWAW} then Grid(s) is the 4 \times 3 grid: you can place the robot in the cell (3, 2); the robot performs the command 'D' and moves to (3, 3); the robot performs the command 'S' and moves to (4, 3); the robot performs the command 'A' and moves to (4, 2); the robot performs the command 'W' and moves to (3, 2); the robot performs the command 'W' and moves to (2, 2); the robot performs the command 'A' and moves to (2, 1); the robot performs the command 'W' and moves to (1, 1). You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).What is the minimum area of Grid(s) you can achieve?InputThe first line contains one integer T (1 \le T \le 1000) — the number of queries.Next T lines contain queries: one per line. This line contains single string s (1 \le |s| \le 2 \cdot 10^5, s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}) — the sequence of commands.It's guaranteed that the total length of s over all queries doesn't exceed 2 \cdot 10^5.OutputPrint T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.ExampleInput
3
DSAWWAW
D
WA
Output
8
2
4
NoteIn the first query you have to get string \text{DSAWW}\underline{D}\text{AW}.In second and third queries you can not decrease the area of Grid(s). | 3
DSAWWAW
D
WA
| 8 2 4 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'dp', 'greedy', 'implementation', 'math', 'strings', '*2100'] |
B. You Are Given a Decimal String...time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you have a special x-y-counter. This counter can store some value as a decimal number; at first, the counter has value 0. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either x or y to its value. So all sequences this counter generates are starting from 0. For example, a 4-2-counter can act as follows: it prints 0, and adds 4 to its value, so the current value is 4, and the output is 0; it prints 4, and adds 4 to its value, so the current value is 8, and the output is 04; it prints 8, and adds 4 to its value, so the current value is 12, and the output is 048; it prints 2, and adds 2 to its value, so the current value is 14, and the output is 0482; it prints 4, and adds 4 to its value, so the current value is 18, and the output is 04824. This is only one of the possible outputs; for example, the same counter could generate 0246802468024 as the output, if we chose to add 2 during each step.You wrote down a printed sequence from one of such x-y-counters. But the sequence was corrupted and several elements from the sequence could be erased.Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string s — the remaining data of the sequence. For all 0 \le x, y < 10, calculate the minimum number of digits you have to insert in the string s to make it a possible output of the x-y-counter. Note that you can't change the order of digits in string s or erase any of them; only insertions are allowed.InputThe first line contains a single string s (1 \le |s| \le 2 \cdot 10^6, s_i \in \{\text{0} - \text{9}\}) — the remaining data you have. It's guaranteed that s_1 = 0.OutputPrint a 10 \times 10 matrix, where the j-th integer (0-indexed) on the i-th line (0-indexed too) is equal to the minimum number of digits you have to insert in the string s to make it a possible output of the i-j-counter, or -1 if there is no way to do so.ExampleInput
0840
Output
-1 17 7 7 7 -1 2 17 2 7
17 17 7 5 5 5 2 7 2 7
7 7 7 4 3 7 1 7 2 5
7 5 4 7 3 3 2 5 2 3
7 5 3 3 7 7 1 7 2 7
-1 5 7 3 7 -1 2 9 2 7
2 2 1 2 1 2 2 2 0 1
17 7 7 5 7 9 2 17 2 3
2 2 2 2 2 2 0 2 2 2
7 7 5 3 7 7 1 3 2 7
NoteLet's take, for example, 4-3-counter. One of the possible outcomes the counter could print is 0(4)8(1)4(7)0 (lost elements are in the brackets).One of the possible outcomes a 2-3-counter could print is 0(35)8(1)4(7)0.The 6-8-counter could print exactly the string 0840. | 0840
| -1 17 7 7 7 -1 2 17 2 7 17 17 7 5 5 5 2 7 2 7 7 7 7 4 3 7 1 7 2 5 7 5 4 7 3 3 2 5 2 3 7 5 3 3 7 7 1 7 2 7 -1 5 7 3 7 -1 2 9 2 7 2 2 1 2 1 2 2 2 0 1 17 7 7 5 7 9 2 17 2 3 2 2 2 2 2 2 0 2 2 2 7 7 5 3 7 7 1 3 2 7 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'shortest paths', '*1700'] |
A. You Are Given Two Binary Strings...time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k \ge 0, calculate the expression s_k = f(x) + f(y) \cdot 2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For example, let x = 1010 and y = 11; you've chosen k = 1 and, since 2^1 = 10_2, so s_k = 1010_2 + 11_2 \cdot 10_2 = 10000_2 and rev_k = 00001.For given x and y, you need to choose such k that rev_k is lexicographically minimal (read notes if you don't know what does "lexicographically" means).It's guaranteed that, with given constraints, k exists and is finite.InputThe first line contains a single integer T (1 \le T \le 100) — the number of queries.Next 2T lines contain a description of queries: two lines per query. The first line contains one binary string x, consisting of no more than 10^5 characters. Each character is either 0 or 1.The second line contains one binary string y, consisting of no more than 10^5 characters. Each character is either 0 or 1.It's guaranteed, that 1 \le f(y) \le f(x) (where f(x) is the integer represented by x, and f(y) is the integer represented by y), both representations don't have any leading zeroes, the total length of x over all queries doesn't exceed 10^5, and the total length of y over all queries doesn't exceed 10^5.OutputPrint T integers (one per query). For each query print such k that rev_k is lexicographically minimal.ExampleInput
4
1010
11
10001
110
1
1
1010101010101
11110000
Output
1
3
0
0
NoteThe first query was described in the legend.In the second query, it's optimal to choose k = 3. The 2^3 = 1000_2 so s_3 = 10001_2 + 110_2 \cdot 1000_2 = 10001 + 110000 = 1000001 and rev_3 = 1000001. For example, if k = 0, then s_0 = 10111 and rev_0 = 11101, but rev_3 = 1000001 is lexicographically smaller than rev_0 = 11101.In the third query s_0 = 10 and rev_0 = 01. For example, s_2 = 101 and rev_2 = 101. And 01 is lexicographically smaller than 101.The quote from Wikipedia: "To determine which of two strings of characters comes when arranging in lexicographical order, their first letters are compared. If they differ, then the string whose first letter comes earlier in the alphabet comes before the other string. If the first letters are the same, then the second letters are compared, and so on. If a position is reached where one string has no more letters to compare while the other does, then the first (shorter) string is deemed to come first in alphabetical order." | 4
1010
11
10001
110
1
1
1010101010101
11110000
| 1 3 0 0 | 2 seconds | 256 megabytes | ['bitmasks', 'greedy', '*1100'] |
E2. Knightmare (hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Alice and Bob are playing a game on the chessboard of size n \times m where n and m are even. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are two knights on the chessboard. A white one initially is on the position (x_1, y_1), while the black one is on the position (x_2, y_2). Alice will choose one of the knights to play with, and Bob will use the other one.The Alice and Bob will play in turns and whoever controls the white knight starts the game. During a turn, the player must move their knight adhering the chess rules. That is, if the knight is currently on the position (x, y), it can be moved to any of those positions (as long as they are inside the chessboard): (x+1, y+2), (x+1, y-2), (x-1, y+2), (x-1, y-2),(x+2, y+1), (x+2, y-1), (x-2, y+1), (x-2, y-1). We all know that knights are strongest in the middle of the board. Both knight have a single position they want to reach: the owner of the white knight wins if it captures the black knight or if the white knight is at (n/2, m/2) and this position is not under attack of the black knight at this moment; The owner of the black knight wins if it captures the white knight or if the black knight is at (n/2+1, m/2) and this position is not under attack of the white knight at this moment. Formally, the player who captures the other knight wins. The player who is at its target square ((n/2, m/2) for white, (n/2+1, m/2) for black) and this position is not under opponent's attack, also wins.A position is under attack of a knight if it can move into this position. Capturing a knight means that a player moves their knight to the cell where the opponent's knight is.If Alice made 350 moves and nobody won, the game is a draw.Alice is unsure in her chess skills, so she asks you for a help. Choose a knight and win the game for her. It can be shown, that Alice always has a winning strategy.InteractionThe interaction starts with two integers n and m (6 \le n,m \le 1000, n and m are even) — the dimensions of the chessboard.The second line contains four integers x_1, y_1, x_2, y_2 (1 \le x_1, x_2 \le n, 1 \le y_1, y_2 \le m) — the positions of the white and the black knight. It is guaranteed that the two knights have different starting positions. It is also guaranteed that none of the knights are in their own target square in the beginning of the game (however, they can be on the opponent's target position).Your program should reply with either "WHITE" or "BLACK", depending on the knight you want to play with. In case you select the white knight, you start the game.During every your turn, you need to print two integers: x and y, the position to move the knight. If you won the game by this turn, you must terminate your program immediately.After every turn of the opponent, you will receive two integers: x and y, the position where Bob moved his knight.If your last move was illegal or you lost the game after jury's turn, or you made 350 moves, and haven't won, you will receive "-1 -1". In such cases, you should terminate your program and then you will get a Wrong Answer verdict.After printing anything, do not forget to output the end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hacks are disabled for this problem.Jury's program is adaptive: the moves of jury may depend on the moves made by your program.ExamplesInput
8 8
2 3 1 8
Output
WHITE
4 4
Input
6 6
4 4 2 2
6 3Output
BLACK
4 3
NoteIn the first example, the white knight can reach it's target square in one move.In the second example black knight wins, no matter what white knight moves. | 8 8
2 3 1 8
| WHITE 4 4 | 3 seconds | 256 megabytes | ['graphs', 'interactive', 'shortest paths', '*3000'] |
E1. Knightmare (easy)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem only differs from the next problem in constraints.This is an interactive problem.Alice and Bob are playing a game on the chessboard of size n \times m where n and m are even. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are two knights on the chessboard. A white one initially is on the position (x_1, y_1), while the black one is on the position (x_2, y_2). Alice will choose one of the knights to play with, and Bob will use the other one.The Alice and Bob will play in turns and whoever controls the white knight starts the game. During a turn, the player must move their knight adhering the chess rules. That is, if the knight is currently on the position (x, y), it can be moved to any of those positions (as long as they are inside the chessboard): (x+1, y+2), (x+1, y-2), (x-1, y+2), (x-1, y-2),(x+2, y+1), (x+2, y-1), (x-2, y+1), (x-2, y-1). We all know that knights are strongest in the middle of the board. Both knight have a single position they want to reach: the owner of the white knight wins if it captures the black knight or if the white knight is at (n/2, m/2) and this position is not under attack of the black knight at this moment; The owner of the black knight wins if it captures the white knight or if the black knight is at (n/2+1, m/2) and this position is not under attack of the white knight at this moment. Formally, the player who captures the other knight wins. The player who is at its target square ((n/2, m/2) for white, (n/2+1, m/2) for black) and this position is not under opponent's attack, also wins.A position is under attack of a knight if it can move into this position. Capturing a knight means that a player moves their knight to the cell where the opponent's knight is.If Alice made 350 moves and nobody won, the game is a draw.Alice is unsure in her chess skills, so she asks you for a help. Choose a knight and win the game for her. It can be shown, that Alice always has a winning strategy.InteractionThe interaction starts with two integers n and m (6 \le n,m \le 40, n and m are even) — the dimensions of the chessboard.The second line contains four integers x_1, y_1, x_2, y_2 (1 \le x_1, x_2 \le n, 1 \le y_1, y_2 \le m) — the positions of the white and the black knight. It is guaranteed that the two knights have different starting positions. It is also guaranteed that none of the knights are in their own target square in the beginning of the game (however, they can be on the opponent's target position).Your program should reply with either "WHITE" or "BLACK", depending on the knight you want to play with. In case you select the white knight, you start the game.During every your turn, you need to print two integers: x and y, the position to move the knight. If you won the game by this turn, you must terminate your program immediately.After every turn of the opponent, you will receive two integers: x and y, the position where Bob moved his knight.If your last move was illegal or you lost the game after jury's turn, or you made 350 moves, and haven't won, you will receive "-1 -1". In such cases, you should terminate your program and then you will get a Wrong Answer verdict.After printing anything, do not forget to output the end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hacks are disabled for this problem.Jury's program is adaptive: the moves of jury may depend on the moves made by your program.ExamplesInput
8 8
2 3 1 8
Output
WHITE
4 4
Input
6 6
4 4 2 2
6 3Output
BLACK
4 3
NoteIn the first example, the white knight can reach it's target square in one move.In the second example black knight wins, no matter what white knight moves. | 8 8
2 3 1 8
| WHITE 4 4 | 3 seconds | 256 megabytes | ['graphs', 'interactive', 'shortest paths', '*2900'] |
D. Treasure Huntingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are on the island which can be represented as a n \times m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i).Initially you stand at the lower left corner of the island, at the position (1, 1). If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from (r, c) to (r+1, c)), left (from (r, c) to (r, c-1)), or right (from position (r, c) to (r, c+1)). Because of the traps, you can't move down.However, moving up is also risky. You can move up only if you are in a safe column. There are q safe columns: b_1, b_2, \ldots, b_q. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures.InputThe first line contains integers n, m, k and q (2 \le n, \, m, \, k, \, q \le 2 \cdot 10^5, q \le m) — the number of rows, the number of columns, the number of treasures in the island and the number of safe columns.Each of the next k lines contains two integers r_i, c_i, (1 \le r_i \le n, 1 \le c_i \le m) — the coordinates of the cell with a treasure. All treasures are located in distinct cells.The last line contains q distinct integers b_1, b_2, \ldots, b_q (1 \le b_i \le m) — the indices of safe columns.OutputPrint the minimum number of moves required to collect all the treasures.ExamplesInput
3 3 3 2
1 1
2 1
3 1
2 3
Output
6Input
3 5 3 2
1 2
2 3
3 1
1 5
Output
8Input
3 6 3 2
1 6
2 2
3 4
1 6
Output
15NoteIn the first example you should use the second column to go up, collecting in each row treasures from the first column. In the second example, it is optimal to use the first column to go up. In the third example, it is optimal to collect the treasure at cell (1;6), go up to row 2 at column 6, then collect the treasure at cell (2;2), go up to the top row at column 1 and collect the last treasure at cell (3;4). That's a total of 15 moves. | 3 3 3 2
1 1
2 1
3 1
2 3
| 6 | 3 seconds | 256 megabytes | ['binary search', 'dp', 'greedy', 'implementation', '*2100'] |
C. Maximum Mediantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers, where n is odd. You can make the following operation with it: Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1). You want to make the median of the array the largest possible using at most k operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.InputThe first line contains two integers n and k (1 \le n \le 2 \cdot 10^5, n is odd, 1 \le k \le 10^9) — the number of elements in the array and the largest number of operations you can make.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).OutputPrint a single integer — the maximum possible median after the operations.ExamplesInput
3 2
1 3 5
Output
5Input
5 5
1 2 1 1 1
Output
3Input
7 7
4 1 2 4 3 4 4
Output
5NoteIn the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5. | 3 2
1 3 5
| 5 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'math', 'sortings', '*1400'] |
B. Zero Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n.In one operation you can choose two elements a_i and a_j (i \ne j) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.InputThe first line contains a single integer n (2 \le n \le 10^5) — the size of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the elements of the array.OutputPrint "YES" if it is possible to make all elements zero, otherwise print "NO".ExamplesInput
4
1 1 2 2
Output
YESInput
6
1 2 3 4 5 6
Output
NONoteIn the first example, you can make all elements equal to zero in 3 operations: Decrease a_1 and a_2, Decrease a_3 and a_4, Decrease a_3 and a_4 In the second example, one can show that it is impossible to make all elements equal to zero. | 4
1 1 2 2
| YES | 1 second | 256 megabytes | ['greedy', 'math', '*1500'] |
A. Important Examtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA class of students wrote a multiple-choice test.There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class. InputThe first line contains integers n and m (1 \le n, m \le 1000) — the number of students in the class and the number of questions in the test.Each of the next n lines contains string s_i (|s_i| = m), describing an answer of the i-th student. The j-th character represents the student answer (A, B, C, D or E) on the j-th question.The last line contains m integers a_1, a_2, \ldots, a_m (1 \le a_i \le 1000) — the number of points for the correct answer for every question.OutputPrint a single integer — the maximum possible total score of the class.ExamplesInput
2 4
ABCD
ABCE
1 2 3 4
Output
16Input
3 3
ABC
BCD
CDE
5 4 12
Output
21NoteIn the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be 16.In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is 5 + 4 + 12 = 21. | 2 4
ABCD
ABCE
1 2 3 4
| 16 | 1 second | 256 megabytes | ['implementation', 'strings', '*900'] |
F. Graph Travelertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], \ldots, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself.A travel on this graph works as follows. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. The next vertex is e_i[x] where x is an integer 0 \le x \le m_i-1 satisfying x \equiv c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly.For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 \le x \le 1) where x \equiv c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on.Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times.InputThe first line of the input contains an integer n (1 \le n \le 1000), the number of vertices in the graph.The second line contains n integers. The i-th integer is k_i (-10^9 \le k_i \le 10^9), the integer written on the i-th vertex.Next 2 \cdot n lines describe the edges of each vertex. The (2 \cdot i + 1)-st line contains an integer m_i (1 \le m_i \le 10), the number of outgoing edges of the i-th vertex. The (2 \cdot i + 2)-nd line contains m_i integers e_i[0], e_i[1], \ldots, e_i[m_i-1], each having an integer value between 1 and n, inclusive.Next line contains an integer q (1 \le q \le 10^5), the number of queries Gildong wants to ask.Next q lines contains two integers x and y (1 \le x \le n, -10^9 \le y \le 10^9) each, which mean that the start vertex is x and the starting value of c is y.OutputFor each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y.ExamplesInput
4
0 0 0 0
2
2 3
1
2
3
2 4 1
4
3 1 2 1
6
1 0
2 0
3 -1
4 -2
1 1
1 5
Output
1
1
2
1
3
2
Input
4
4 -5 -3 -1
2
2 3
1
2
3
2 4 1
4
3 1 2 1
6
1 0
2 0
3 -1
4 -2
1 1
1 5
Output
1
1
1
3
1
1
NoteThe first example can be shown like the following image: Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex.The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". 1(0) \to 2(0) \to 2(0) \to \ldots 2(0) \to 2(0) \to \ldots 3(-1) \to 1(-1) \to 3(-1) \to \ldots 4(-2) \to 2(-2) \to 2(-2) \to \ldots 1(1) \to 3(1) \to 4(1) \to 1(1) \to \ldots 1(5) \to 3(5) \to 1(5) \to \ldots The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. The queries for the second example works as follows: 1(4) \to 2(-1) \to 2(-6) \to \ldots 2(-5) \to 2(-10) \to \ldots 3(-4) \to 1(0) \to 2(-5) \to 2(-10) \to \ldots 4(-3) \to 1(1) \to 3(-2) \to 4(-3) \to \ldots 1(5) \to 3(2) \to 1(6) \to 2(1) \to 2(-4) \to \ldots 1(9) \to 3(6) \to 2(1) \to 2(-4) \to \ldots | 4
0 0 0 0
2
2 3
1
2
3
2 4 1
4
3 1 2 1
6
1 0
2 0
3 -1
4 -2
1 1
1 5
| 1 1 2 1 3 2 | 2 seconds | 512 megabytes | ['brute force', 'data structures', 'dfs and similar', 'dp', 'graphs', 'implementation', 'math', 'number theory', '*2300'] |
E. Compress Wordstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmugae has a sentence consisting of n words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.InputThe first line contains an integer n (1 \le n \le 10^5), the number of the words in Amugae's sentence.The second line contains n words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed 10^6.OutputIn the only line output the compressed word after the merging process ends as described in the problem.ExamplesInput
5
I want to order pizza
Output
IwantorderpizzaInput
5
sample please ease in out
Output
sampleaseinout | 5
I want to order pizza
| Iwantorderpizza | 1 second | 256 megabytes | ['brute force', 'hashing', 'implementation', 'string suffix structures', 'strings', '*2000'] |
D. White Linestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint — black and white.There is a tool named eraser in cfpaint. The eraser has an integer size k (1 \le k \le n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 \le i, j \le n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i \le i' \le i + k - 1 and j \le j' \le j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.A white line is a row or a column without any black cells.Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.InputThe first line contains two integers n and k (1 \le k \le n \le 2000) — the number of rows and columns, and the size of the eraser.The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.OutputPrint one integer: the maximum number of white lines after using the eraser exactly once.ExamplesInput
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
NoteIn the first example, Gildong can click the cell (2, 2), then the working screen becomes: BWWWWWWWWWWWWWWBThen there are four white lines — the 2-nd and 3-rd row, and the 2-nd and 3-rd column.In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | 4 2
BWWW
WBBW
WBBW
WWWB
| 4 | 1.5 seconds | 256 megabytes | ['brute force', 'data structures', 'dp', 'implementation', 'two pointers', '*1900'] |
C. Round Corridortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by n sectors, and the outer area is equally divided by m sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position. The inner area's sectors are denoted as (1,1), (1,2), \dots, (1,n) in clockwise direction. The outer area's sectors are denoted as (2,1), (2,2), \dots, (2,m) in the same manner. For a clear understanding, see the example image above.Amugae wants to know if he can move from one sector to another sector. He has q questions.For each question, check if he can move between two given sectors.InputThe first line contains three integers n, m and q (1 \le n, m \le 10^{18}, 1 \le q \le 10^4) — the number of sectors in the inner area, the number of sectors in the outer area and the number of questions.Each of the next q lines contains four integers s_x, s_y, e_x, e_y (1 \le s_x, e_x \le 2; if s_x = 1, then 1 \le s_y \le n, otherwise 1 \le s_y \le m; constraints on e_y are similar). Amague wants to know if it is possible to move from sector (s_x, s_y) to sector (e_x, e_y).OutputFor each question, print "YES" if Amugae can move from (s_x, s_y) to (e_x, e_y), and "NO" otherwise.You can print each letter in any case (upper or lower).ExampleInput
4 6 3
1 1 2 3
2 6 1 2
2 6 2 4
Output
YES
NO
YES
NoteExample is shown on the picture in the statement. | 4 6 3
1 1 2 3
2 6 1 2
2 6 2 4
| YES NO YES | 1 second | 256 megabytes | ['math', 'number theory', '*1400'] |
B. Block Adventuretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong is playing a video game called Block Adventure. In Block Adventure, there are n columns of blocks in a row, and the columns are numbered from 1 to n. All blocks have equal heights. The height of the i-th column is represented as h_i, which is the number of blocks stacked in the i-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the 1-st column. The goal of the game is to move the character to the top of the n-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the i-th column, Gildong can take one of the following three actions as many times as he wants: if there is at least one block on the column, remove one block from the top of the i-th column and put it in the bag; if there is at least one block in the bag, take one block out of the bag and place it on the top of the i-th column; if i < n and |h_i - h_{i+1}| \le k, move the character to the top of the i+1-st column. k is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the i-th column, and the value h_i changes.The character initially has m blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.The first line of each test case contains three integers n, m, and k (1 \le n \le 100, 0 \le m \le 10^6, 0 \le k \le 10^6) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer k described in the statement.The second line of each test case contains n integers. The i-th integer is h_i (0 \le h_i \le 10^6), the initial height of the i-th column.OutputFor each test case, print "YES" if it is possible to win the game. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInput53 0 14 3 53 1 21 4 74 10 010 20 10 202 5 50 111 9 999OutputYESNOYESNOYESNoteIn the first case, Gildong can take one block from the 1-st column, move to the 2-nd column, put the block on the 2-nd column, then move to the 3-rd column.In the second case, Gildong has to put the block in his bag on the 1-st column to get to the 2-nd column. But it is impossible to get to the 3-rd column because |h_2 - h_3| = 3 > k and there is no way to decrease the gap.In the fifth case, the character is already on the n-th column from the start so the game is won instantly. | Input53 0 14 3 53 1 21 4 74 10 010 20 10 202 5 50 111 9 999 | OutputYESNOYESNOYES | 1 second | 256 megabytes | ['dp', 'greedy', '*1200'] |
A. Hoteliertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right.The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.InputThe first line consists of an integer n (1 \le n \le 10^5), the number of events in Amugae's memory.The second line consists of a string of length n describing the events in chronological order. Each character represents: 'L': A customer arrives from the left entrance. 'R': A customer arrives from the right entrance. '0', '1', ..., '9': The customer in room x (0, 1, ..., 9 respectively) leaves. It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room x when x (0, 1, ..., 9) is given. Also, all the rooms are initially empty.OutputIn the only line, output the hotel room's assignment status, from room 0 to room 9. Represent an empty room as '0', and an occupied room as '1', without spaces.ExamplesInput
8
LLRL1RL1
Output
1010000011Input
9
L0L0LLRR9
Output
1100000010NoteIn the first example, hotel room's assignment status after each action is as follows. First of all, all rooms are empty. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. L: one more customer from the left entrance. Assignment status is 1110000001. 1: the customer in room 1 leaves. Assignment status is 1010000001. R: one more customer from the right entrance. Assignment status is 1010000011. L: one more customer from the left entrance. Assignment status is 1110000011. 1: the customer in room 1 leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011.In the second example, hotel room's assignment status after each action is as follows. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. 0: the customer in room 0 leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again. 0: the customer in room 0 leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. R: one more customer from the right entrance. Assignment status is 1100000011. 9: the customer in room 9 leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010. | 8
LLRL1RL1
| 1010000011 | 1 second | 256 megabytes | ['brute force', 'data structures', 'implementation', '*800'] |
B. Water Lilytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surface. Suppose that the lily grows at some point A on the lake bottom, and its stem is always a straight segment with one endpoint at point A. Also suppose that initially the flower was exactly above the point A, i.e. its stem was vertical. Can you determine the depth of the lake at point A?InputThe only line contains two integers H and L (1 \le H < L \le 10^{6}).OutputPrint a single number — the depth of the lake at point A. The absolute or relative error should 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}.ExamplesInput
1 2
Output
1.5000000000000
Input
3 5
Output
2.6666666666667
| 1 2
| 1.5000000000000 | 1 second | 256 megabytes | ['geometry', 'math', '*1000'] |
A. City Daytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x \le j < d and d < j \le d + y. Citizens only watch the weather during summer, so we only consider such j that 1 \le j \le n.Help mayor find the earliest not-so-rainy day of summer.InputThe first line contains three integers n, x and y (1 \le n \le 100\,000, 0 \le x, y \le 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.The second line contains n distinct integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9), where a_i denotes the rain amount on the i-th day.OutputPrint a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.ExamplesInput
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
NoteIn the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer. | 10 2 2
10 9 6 7 8 3 2 1 4 5
| 3 | 1 second | 256 megabytes | ['implementation', '*1000'] |
F. GCD Groups 2time limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.Both groups have to be non-empty.InputThe first line contains a single integer n (2 \leq n \leq 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the elements of the array.OutputIn the first line print "YES" (without quotes), if it is possible to split the integers into two groups as required, and "NO" (without quotes) otherwise.If it is possible to split the integers, in the second line print n integers, where the i-th integer is equal to 1 if the integer a_i should be in the first group, and 2 otherwise.If there are multiple solutions, print any.ExamplesInput
4
2 3 6 7
Output
YES
2 2 1 1
Input
5
6 15 35 77 22
Output
YES
2 1 2 1 1
Input
5
6 10 15 1000 75
Output
NO
| 4
2 3 6 7
| YES 2 2 1 1 | 0.5 seconds | 256 megabytes | ['greedy', 'number theory', 'probabilities', '*2900'] |
E. Rectangle Painting 2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a square grid of size n \times n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs \min(h, w) to color a rectangle of size h \times w. You are to make all cells white for minimum total cost.The square is large, so we give it to you in a compressed way. The set of black cells is the union of m rectangles.InputThe first line contains two integers n and m (1 \le n \le 10^{9}, 0 \le m \le 50) — the size of the square grid and the number of black rectangles.Each of the next m lines contains 4 integers x_{i1} y_{i1} x_{i2} y_{i2} (1 \le x_{i1} \le x_{i2} \le n, 1 \le y_{i1} \le y_{i2} \le n) — the coordinates of the bottom-left and the top-right corner cells of the i-th black rectangle.The rectangles may intersect.OutputPrint a single integer — the minimum total cost of painting the whole square in white.ExamplesInput
10 2
4 1 5 10
1 4 10 5
Output
4
Input
7 6
2 1 2 1
4 2 4 3
2 5 2 5
2 3 5 3
1 2 1 2
3 2 5 3
Output
3
NoteThe examples and some of optimal solutions are shown on the pictures below. | 10 2
4 1 5 10
1 4 10 5
| 4 | 1 second | 256 megabytes | ['flows', 'graph matchings', 'graphs', '*2500'] |
D. Rectangle Painting 1time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a square grid of size n \times n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs \max(h, w) to color a rectangle of size h \times w. You are to make all cells white for minimum total cost.InputThe first line contains a single integer n (1 \leq n \leq 50) — the size of the square grid.Each of the next n lines contains a string of length n, consisting of characters '.' and '#'. The j-th character of the i-th line is '#' if the cell with coordinates (i, j) is black, otherwise it is white.OutputPrint a single integer — the minimum total cost to paint all cells in white.ExamplesInput
3
###
#.#
###
Output
3
Input
3
...
...
...
Output
0
Input
4
#...
....
....
#...
Output
2
Input
5
#...#
.#.#.
.....
.#...
#....
Output
5
NoteThe examples and some of optimal solutions are shown on the pictures below. | 3
###
#.#
###
| 3 | 1 second | 256 megabytes | ['dp', '*2300'] |
C. Matching vs Independent Settime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a graph with 3 \cdot n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices.A set of edges is called a matching if no two edges share an endpoint.A set of vertices is called an independent set if no two vertices are connected with an edge.InputThe first line contains a single integer T \ge 1 — the number of graphs you need to process. The description of T graphs follows.The first line of description of a single graph contains two integers n and m, where 3 \cdot n is the number of vertices, and m is the number of edges in the graph (1 \leq n \leq 10^{5}, 0 \leq m \leq 5 \cdot 10^{5}).Each of the next m lines contains two integers v_i and u_i (1 \leq v_i, u_i \leq 3 \cdot n), meaning that there is an edge between vertices v_i and u_i.It is guaranteed that there are no self-loops and no multiple edges in the graph.It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 \cdot 10^{5}.OutputPrint your answer for each of the T graphs. Output your answer for a single graph in the following format.If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order.If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set.If there is no matching and no independent set of the specified size, print "Impossible" (without quotes).You can print edges and vertices in any order.If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets.ExampleInput
4
1 2
1 3
1 2
1 2
1 3
1 2
2 5
1 2
3 1
1 4
5 1
1 6
2 15
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
Output
Matching
2
IndSet
1
IndSet
2 4
Matching
1 15
NoteThe first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n.The fourth graph does not have an independent set of size 2, but there is a matching of size 2. | 4
1 2
1 3
1 2
1 2
1 3
1 2
2 5
1 2
3 1
1 4
5 1
1 6
2 15
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
| Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 | 1 second | 256 megabytes | ['constructive algorithms', 'graphs', 'greedy', 'sortings', '*2000'] |
B. Welfare Statetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.Sometimes the government makes payouts to the poor: all citizens who have strictly less money than x are paid accordingly so that after the payout they have exactly x money. In this case the citizens don't send a receipt.You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^{5}) — the numer of citizens.The next line contains n integers a_1, a_2, ..., a_n (0 \le a_{i} \le 10^{9}) — the initial balances of citizens.The next line contains a single integer q (1 \le q \le 2 \cdot 10^{5}) — the number of events.Each of the next q lines contains a single event. The events are given in chronological order.Each event is described as either 1 p x (1 \le p \le n, 0 \le x \le 10^{9}), or 2 x (0 \le x \le 10^{9}). In the first case we have a receipt that the balance of the p-th person becomes equal to x. In the second case we have a payoff with parameter x.OutputPrint n integers — the balances of all citizens after all events.ExamplesInput
4
1 2 3 4
3
2 3
1 2 2
2 1
Output
3 2 3 4
Input
5
3 50 2 1 10
3
1 2 0
2 8
1 3 20
Output
8 8 20 8 10
NoteIn the first example the balances change as follows: 1 2 3 4 \rightarrow 3 3 3 4 \rightarrow 3 2 3 4 \rightarrow 3 2 3 4In the second example the balances change as follows: 3 50 2 1 10 \rightarrow 3 0 2 1 10 \rightarrow 8 8 8 8 10 \rightarrow 8 8 20 8 10 | 4
1 2 3 4
3
2 3
1 2 2
2 1
| 3 2 3 4 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'sortings', '*1600'] |
A. MP3time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers.If there are exactly K distinct values in the array, then we need k = \lceil \log_{2} K \rceil bits to store each value. It then takes nk bits to store the whole file.To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l \le r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities.Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible.We remind you that 1 byte contains 8 bits.k = \lceil log_{2} K \rceil is the smallest integer such that K \le 2^{k}. In particular, if K = 1, then k = 0.InputThe first line contains two integers n and I (1 \le n \le 4 \cdot 10^{5}, 1 \le I \le 10^{8}) — the length of the array and the size of the disk in bytes, respectively.The next line contains n integers a_{i} (0 \le a_{i} \le 10^{9}) — the array denoting the sound file.OutputPrint a single integer — the minimal possible number of changed elements.ExamplesInput
6 1
2 1 2 3 4 3
Output
2
Input
6 2
2 1 2 3 4 3
Output
0
Input
6 1
1 1 2 2 3 3
Output
2
NoteIn the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed.In the second example the disk is larger, so the initial file fits it and no changes are required.In the third example we have to change both 1s or both 3s. | 6 1
2 1 2 3 4 3
| 2 | 1 second | 256 megabytes | ['sortings', 'two pointers', '*1600'] |
F. Coloring Gametime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob want to play a game. They have n colored paper strips; the i-th strip is divided into a_i cells numbered from 1 to a_i. Each cell can have one of 3 colors.In the beginning of the game, Alice and Bob put n chips, the i-th chip is put in the a_i-th cell of the i-th strip. Then they take turns, Alice is first. Each player during their turn has to choose one chip and move it 1, 2 or 3 cells backwards (i. e. if the current cell is x, then the chip can be moved to the cell x - 1, x - 2 or x - 3). There are two restrictions: the chip cannot leave the borders of the strip (for example, if the current cell is 3, then you can't move the chip 3 cells backwards); and some moves may be prohibited because of color of the current cell (a matrix f with size 3 \times 3 is given, where f_{i, j} = 1 if it is possible to move the chip j cells backwards from the cell which has color i, or f_{i, j} = 0 if such move is prohibited). The player who cannot make a move loses the game.Initially some cells may be uncolored. Bob can color all uncolored cells as he wants (but he cannot leave any cell uncolored). Let's call a coloring good if Bob can win the game no matter how Alice acts, if the cells are colored according to this coloring. Two colorings are different if at least one cell is colored in different colors in these two colorings.Bob wants you to calculate the number of good colorings. Can you do it for him?Since the answer can be really large, you have to print it modulo 998244353.InputThe first line contains one integer n — the number of paper strips (1 \le n \le 1000).The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9), where a_i is the number of cells in the i-th strip.The third line contains one integer m (1 \le m \le 1000) — the number of cells that are already colored.Then m lines follow, each describing an already colored cell. The i-th of these lines contains three integers x_i, y_i and c_i (1 \le x_i \le n, 1 \le y_i \le a_{x_i}, 1 \le c_i \le 3) denoting that the cell y_i in the strip x_i has color c_i. It is guaranteed that if i \ne j, then either x_i \ne x_j or y_i \ne y_j (or both).Then 3 lines follow, i-th line containing 3 numbers f_{i, 1}, f_{i, 2}, f_{i, 3} (0 \le f_{i, j} \le 1). If f_{i, j} = 1, then it is possible to move the chip j cells backwards from the cell having color i; if f_{i, j} = 0, then such move is impossible.OutputPrint one integer: the number of good colorings, taken modulo 998244353.ExamplesInput
3
3 4 5
2
1 1 1
2 2 2
1 1 1
1 0 0
0 1 1
Output
14346
Input
1
1
1
1 1 1
1 1 1
1 1 1
1 1 1
Output
1
Input
3
1 1 1
1
1 1 1
1 1 1
1 1 1
1 1 1
Output
9
| 3
3 4 5
2
1 1 1
2 2 2
1 1 1
1 0 0
0 1 1
| 14346 | 5 seconds | 512 megabytes | ['dp', 'games', 'matrices', '*2700'] |
E. Culture Codetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has n different matryoshkas. Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll — inside the third one and so on. Matryoshka i can be nested inside matryoshka j if out_i \le in_j. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}}), where i_1, i_2, ..., i_k are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index i such that one of the subsets contains the i-th doll, and another subset doesn't.Since the answer can be large, print it modulo 10^9 + 7.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of matryoshkas.The next n lines contain a description of each doll: two integers out_i and in_i (1 \le in_i < out_i \le 10^9) — the outer and inners volumes of the i-th matryoshka.OutputPrint one integer — the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo 10^9 + 7.ExampleInput
7
4 1
4 2
4 2
2 1
5 4
6 4
3 2
Output
6
NoteThere are 6 big enough nested subsets with minimum possible extra space in the example: \{1, 5\}: we can't add any other matryoshka and keep it nested; it's extra space is 1; \{1, 6\}; \{2, 4, 5\}; \{2, 4, 6\}; \{3, 4, 5\}; \{3, 4, 6\}. There are no more "good" subsets because, for example, subset \{6, 7\} is not big enough (we can add the 4-th matryoshka to it) or subset \{4, 6, 7\} has extra space equal to 2. | 7
4 1
4 2
4 2
2 1
5 4
6 4
3 2
| 6 | 2 seconds | 256 megabytes | ['binary search', 'combinatorics', 'data structures', 'dp', 'shortest paths', 'sortings', '*2300'] |
D. Yet Another Subarray Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots , a_n and two integers m and k.You can choose some subarray a_l, a_{l+1}, \dots, a_{r-1}, a_r. The cost of subarray a_l, a_{l+1}, \dots, a_{r-1}, a_r is equal to \sum\limits_{i=l}^{r} a_i - k \lceil \frac{r - l + 1}{m} \rceil, where \lceil x \rceil is the least integer greater than or equal to x. The cost of empty subarray is equal to zero.For example, if m = 3, k = 10 and a = [2, -4, 15, -3, 4, 8, 3], then the cost of some subarrays are: a_3 \dots a_3: 15 - k \lceil \frac{1}{3} \rceil = 15 - 10 = 5; a_3 \dots a_4: (15 - 3) - k \lceil \frac{2}{3} \rceil = 12 - 10 = 2; a_3 \dots a_5: (15 - 3 + 4) - k \lceil \frac{3}{3} \rceil = 16 - 10 = 6; a_3 \dots a_6: (15 - 3 + 4 + 8) - k \lceil \frac{4}{3} \rceil = 24 - 20 = 4; a_3 \dots a_7: (15 - 3 + 4 + 8 + 3) - k \lceil \frac{5}{3} \rceil = 27 - 20 = 7. Your task is to find the maximum cost of some subarray (possibly empty) of array a.InputThe first line contains three integers n, m, and k (1 \le n \le 3 \cdot 10^5, 1 \le m \le 10, 1 \le k \le 10^9).The second line contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9).OutputPrint the maximum cost of some subarray of array a.ExamplesInput
7 3 10
2 -4 15 -3 4 8 3
Output
7
Input
5 2 1000
-13 -4 -9 -20 -11
Output
0
| 7 3 10
2 -4 15 -3 4 8 3
| 7 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'math', '*1900'] |
C. Array Splittingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sorted array a_1, a_2, \dots, a_n (for each index i > 1 condition a_i \ge a_{i-1} holds) and an integer k.You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to \sum\limits_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13.Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. InputThe first line contains two integers n and k (1 \le k \le n \le 3 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n ( 1 \le a_i \le 10^9, a_i \ge a_{i-1}). OutputPrint the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. ExamplesInput
6 3
4 8 15 16 23 42
Output
12
Input
4 4
1 3 3 7
Output
0
Input
8 1
1 1 2 3 5 8 13 21
Output
20
NoteIn the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. | 6 3
4 8 15 16 23 42
| 12 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1400'] |
B. Pillarstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n pillars aligned in a row and numbered from 1 to n.Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i.You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: there is no other pillar between pillars i and j. Formally, it means that |i - j| = 1; pillar i contains exactly one disk; either pillar j contains no disks, or the topmost disk on pillar j has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all n disks on the same pillar simultaneously?InputThe first line contains one integer n (3 \le n \le 2 \cdot 10^5) — the number of pillars.The second line contains n integers a_1, a_2, ..., a_i (1 \le a_i \le n), where a_i is the radius of the disk initially placed on the i-th pillar. All numbers a_i are distinct.OutputPrint YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExamplesInput
4
1 3 4 2
Output
YES
Input
3
3 1 2
Output
NO
NoteIn the first case it is possible to place all disks on pillar 3 using the following sequence of actions: take the disk with radius 3 from pillar 2 and place it on top of pillar 3; take the disk with radius 1 from pillar 1 and place it on top of pillar 2; take the disk with radius 2 from pillar 4 and place it on top of pillar 3; take the disk with radius 1 from pillar 2 and place it on top of pillar 3. | 4
1 3 4 2
| YES | 1.5 seconds | 256 megabytes | ['greedy', 'implementation', '*1000'] |
A. DIY Wooden Laddertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which two planks of length at least k+1 — the base of the ladder; k planks of length at least 1 — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders 1 and 3 are correct 2-step ladders and ladder 2 is a correct 1-step ladder. On the first picture the lengths of planks are [3, 3] for the base and [1] for the step. On the second picture lengths are [3, 3] for the base and [2] for the step. On the third picture lengths are [3, 4] for the base and [2, 3] for the steps. You have n planks. The length of the i-th planks is a_i. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number k such that you can choose some subset of the given planks and assemble a k-step ladder using them?InputThe first line contains a single integer T (1 \le T \le 100) — the number of queries. The queries are independent.Each query consists of two lines. The first line contains a single integer n (2 \le n \le 10^5) — the number of planks you have.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5) — the lengths of the corresponding planks.It's guaranteed that the total number of planks from all queries doesn't exceed 10^5.OutputPrint T integers — one per query. The i-th integer is the maximum number k, such that you can choose some subset of the planks given in the i-th query and assemble a k-step ladder using them.Print 0 if you can't make even 1-step ladder from the given set of planks.ExampleInput
4
4
1 3 1 3
3
3 3 2
5
2 3 3 4 2
3
1 1 2
Output
2
1
2
0
NoteExamples for the queries 1-3 are shown at the image in the legend section.The Russian meme to express the quality of the ladders: | 4
4
1 3 1 3
3
3 3 2
5
2 3 3 4 2
3
1 1 2
| 2 1 2 0 | 2 seconds | 256 megabytes | ['greedy', 'math', 'sortings', '*900'] |
F. K-th Pathtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected undirected weighted graph consisting of n vertices and m edges.You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 \le i < j \le n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 \le i < j \le n.InputThe first line of the input contains three integers n, m and k (2 \le n \le 2 \cdot 10^5, n - 1 \le m \le \min\Big(\frac{n(n-1)}{2}, 2 \cdot 10^5\Big), 1 \le k \le \min\Big(\frac{n(n-1)}{2}, 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.Then m lines follow, each containing three integers x, y and w (1 \le x, y \le n, 1 \le w \le 10^9, x \ne y) denoting an edge between vertices x and y of weight w.It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).OutputPrint one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).ExamplesInput
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9
| 6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
| 3 | 2.5 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'shortest paths', 'sortings', '*2200'] |
E. Connected Component on a Chessboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers b and w. You have a chessboard of size 10^9 \times 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white.Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a side (i.e. for the cell (x, y) there are at most four connected cells: (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)). A set of cells is called a connected component if for every pair of cells C_1 and C_2 from this set, there exists a sequence of cells c_1, c_2, ..., c_k such that c_1 = C_1, c_k = C_2, all c_i from 1 to k are belong to this set of cells and for every i \in [1, k - 1], cells c_i and c_{i + 1} are connected.Obviously, it can be impossible to find such component. In this case print "NO". Otherwise, print "YES" and any suitable connected component.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 10^5) — the number of queries. Then q queries follow.The only line of the query contains two integers b and w (1 \le b, w \le 10^5) — the number of black cells required and the number of white cells required.It is guaranteed that the sum of numbers of cells does not exceed 2 \cdot 10^5 (\sum w + \sum b \le 2 \cdot 10^5).OutputFor each query, print the answer to it.If it is impossible to find the required component, print "NO" on the first line.Otherwise, print "YES" on the first line. In the next b + w lines print coordinates of cells of your component in any order. There should be exactly b black cells and w white cells in your answer. The printed component should be connected.If there are several answers, you can print any. All coordinates in the answer should be in the range [1; 10^9].ExampleInput
3
1 1
1 4
2 5
Output
YES
2 2
1 2
YES
2 3
1 3
3 3
2 2
2 4
YES
2 3
2 4
2 5
1 3
1 5
3 3
3 5
| 3
1 1
1 4
2 5
| YES 2 2 1 2 YES 2 3 1 3 3 3 2 2 2 4 YES 2 3 2 4 2 5 1 3 1 5 3 3 3 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*1800'] |
D2. RGB Substring (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the size of the input.You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries. Then q queries follow.The first line of the query contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the length of the string s and the length of the substring.The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.It is guaranteed that the sum of n over all queries does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".ExampleInput
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | 3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
| 1 0 3 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'implementation', 'two pointers', '*1600'] |
D1. RGB Substring (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the size of the input.You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 2000) — the number of queries. Then q queries follow.The first line of the query contains two integers n and k (1 \le k \le n \le 2000) — the length of the string s and the length of the substring.The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.It is guaranteed that the sum of n over all queries does not exceed 2000 (\sum n \le 2000).OutputFor each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".ExampleInput
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | 3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
| 1 0 3 | 2 seconds | 256 megabytes | ['implementation', '*1500'] |
C. Robot Breakouttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the i-th robot is currently located at the point having coordinates (x_i, y_i). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers X and Y, and when each robot receives this command, it starts moving towards the point having coordinates (X, Y). The robot stops its movement in two cases: either it reaches (X, Y); or it cannot get any closer to (X, Y). Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as (x_c, y_c). Then the movement system allows it to move to any of the four adjacent points: the first action allows it to move from (x_c, y_c) to (x_c - 1, y_c); the second action allows it to move from (x_c, y_c) to (x_c, y_c + 1); the third action allows it to move from (x_c, y_c) to (x_c + 1, y_c); the fourth action allows it to move from (x_c, y_c) to (x_c, y_c - 1). Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers X and Y so that each robot can reach the point (X, Y). Is it possible to find such a point?InputThe first line contains one integer q (1 \le q \le 10^5) — the number of queries.Then q queries follow. Each query begins with one line containing one integer n (1 \le n \le 10^5) — the number of robots in the query. Then n lines follow, the i-th of these lines describes the i-th robot in the current query: it contains six integer numbers x_i, y_i, f_{i, 1}, f_{i, 2}, f_{i, 3} and f_{i, 4} (-10^5 \le x_i, y_i \le 10^5, 0 \le f_{i, j} \le 1). The first two numbers describe the initial location of the i-th robot, and the following four numbers describe which actions the i-th robot can use to move (f_{i, j} = 1 if the i-th robot can use the j-th action, and f_{i, j} = 0 if it cannot use the j-th action).It is guaranteed that the total number of robots over all queries does not exceed 10^5.OutputYou should answer each query independently, in the order these queries appear in the input.To answer a query, you should do one of the following: if it is impossible to find a point that is reachable by all n robots, print one number 0 on a separate line; if it is possible to find a point that is reachable by all n robots, print three space-separated integers on the same line: 1 X Y, where X and Y are the coordinates of the point reachable by all n robots. Both X and Y should not exceed 10^5 by absolute value; it is guaranteed that if there exists at least one point reachable by all robots, then at least one of such points has both coordinates not exceeding 10^5 by absolute value.ExampleInput
4
2
-1 -2 0 0 0 0
-1 -2 0 0 0 0
3
1 5 1 1 1 1
2 5 0 1 0 1
3 5 1 0 0 0
2
1337 1337 0 1 1 1
1336 1337 1 1 0 1
1
3 5 1 1 1 1
Output
1 -1 -2
1 2 5
0
1 -100000 -100000
| 4
2
-1 -2 0 0 0 0
-1 -2 0 0 0 0
3
1 5 1 1 1 1
2 5 0 1 0 1
3 5 1 0 0 0
2
1337 1337 0 1 1 1
1336 1337 1 1 0 1
1
3 5 1 1 1 1
| 1 -1 -2 1 2 5 0 1 -100000 -100000 | 3 seconds | 256 megabytes | ['implementation', '*1500'] |
B. Odd Sum Segmentstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers a_1, a_2, \dots, a_n. You want to split it into exactly k non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the n elements of the array a must belong to exactly one of the k subsegments.Let's see some examples of dividing the array of length 5 into 3 subsegments (not necessarily with odd sums): [1, 2, 3, 4, 5] is the initial array, then all possible ways to divide it into 3 non-empty non-intersecting subsegments are described below: [1], [2], [3, 4, 5]; [1], [2, 3], [4, 5]; [1], [2, 3, 4], [5]; [1, 2], [3], [4, 5]; [1, 2], [3, 4], [5]; [1, 2, 3], [4], [5]. Of course, it can be impossible to divide the initial array into exactly k subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and any possible division of the array. See the output format for the detailed explanation.You have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries. Then q queries follow.The first line of the query contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the number of elements in the array and the number of subsegments, respectively.The second line of the query contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the i-th element of a.It is guaranteed that the sum of n over all queries does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each query, print the answer to it. If it is impossible to divide the initial array into exactly k subsegments in such a way that each of them will have odd sum of elements, print "NO" in the first line. Otherwise, print "YES" in the first line and any possible division of the array in the second line. The division can be represented as k integers r_1, r_2, ..., r_k such that 1 \le r_1 < r_2 < \dots < r_k = n, where r_j is the right border of the j-th segment (the index of the last element that belongs to the j-th segment), so the array is divided into subsegments [1; r_1], [r_1 + 1; r_2], [r_2 + 1, r_3], \dots, [r_{k - 1} + 1, n]. Note that r_k is always n but you should print it anyway. ExampleInput
3
5 3
7 18 3 14 1
5 4
1 2 3 4 5
6 2
1 2 8 4 10 2
Output
YES
1 3 5
NO
NO
| 3
5 3
7 18 3 14 1
5 4
1 2 3 4 5
6 2
1 2 8 4 10 2
| YES 1 3 5 NO NO | 3 seconds | 256 megabytes | ['constructive algorithms', 'math', '*1200'] |
A. Three Piles of Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer q independent queries.Let's see the following example: [1, 3, 4]. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has 4 candies, and Bob has 4 candies.Another example is [1, 10, 100]. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes 54 candies, and Alice takes 46 candies. Now Bob has 55 candies, and Alice has 56 candies, so she has to discard one candy — and after that, she has 55 candies too.InputThe first line of the input contains one integer q (1 \le q \le 1000) — the number of queries. Then q queries follow.The only line of the query contains three integers a, b and c (1 \le a, b, c \le 10^{16}) — the number of candies in the first, second and third piles correspondingly.OutputPrint q lines. The i-th line should contain the answer for the i-th query — the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).ExampleInput
4
1 3 4
1 10 100
10000000000000000 10000000000000000 10000000000000000
23 34 45
Output
4
55
15000000000000000
51
| 4
1 3 4
1 10 100
10000000000000000 10000000000000000 10000000000000000
23 34 45
| 4 55 15000000000000000 51 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'math', '*800'] |
F. Geometers Anonymous Clubtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDenis holds a Geometers Anonymous Club meeting in SIS. He has prepared n convex polygons numbered from 1 to n for the club. He plans to offer members of the club to calculate Minkowski sums of these polygons. More precisely, he plans to give q tasks, the i-th of them asks to calculate the sum of Minkowski of polygons with indices from l_i to r_i inclusive.The sum of Minkowski of two sets A and B is the set C = \{a + b : a \in A, b \in B\}. It can be proven that if A and B are convex polygons then C will also be a convex polygon. Sum of two convex polygons To calculate the sum of Minkowski of p polygons (p > 2), you need to calculate the sum of Minkowski of the first p - 1 polygons, and then calculate the sum of Minkowski of the resulting polygon and the p-th polygon.For the convenience of checking answers, Denis has decided to prepare and calculate the number of vertices in the sum of Minkowski for each task he prepared. Help him to do it.InputThe first line of the input contains one integer n — the number of convex polygons Denis prepared (1 \le n \le 100\,000).Then n convex polygons follow. The description of the i-th polygon starts with one integer k_i — the number of vertices in the i-th polygon (3 \le k_i). The next k_i lines contain two integers x_{ij}, y_{ij} each — coordinates of vertices of the i-th polygon in counterclockwise order (|x_{ij}|, |y_{ij}| \le 10 ^ 9).It is guaranteed, that there are no three consecutive vertices lying on the same line. The total number of vertices over all polygons does not exceed 300\,000.The following line contains one integer q — the number of tasks (1 \le q \le 100\,000). The next q lines contain descriptions of tasks. Description of the i-th task contains two integers l_i and r_i (1 \le l_i \le r_i \le n).OutputFor each task print a single integer — the number of vertices in the sum of Minkowski of polygons with indices from l_i to r_i.ExampleInput
3
3
0 0
1 0
0 1
4
1 1
1 2
0 2
0 1
3
2 2
1 2
2 1
3
1 2
2 3
1 3
Output
5
5
6
NoteDescription of the example: First, second and third polygons from the example Minkowski sums of the first and second, the second and third and all polygons correspondingly | 3
3
0 0
1 0
0 1
4
1 1
1 2
0 2
0 1
3
2 2
1 2
2 1
3
1 2
2 3
1 3
| 5 5 6 | 2 seconds | 256 megabytes | ['data structures', 'geometry', 'math', 'sortings', '*2500'] |
E. OpenStreetMaptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSeryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size n \times m cells on a map (rows of grid are numbered from 1 to n from north to south, and columns are numbered from 1 to m from west to east). After that he measured the average height of each cell above Rybinsk sea level and obtained a matrix of heights of size n \times m. The cell (i, j) lies on the intersection of the i-th row and the j-th column and has height h_{i, j}. Seryozha is going to look at the result of his work in the browser. The screen of Seryozha's laptop can fit a subrectangle of size a \times b of matrix of heights (1 \le a \le n, 1 \le b \le m). Seryozha tries to decide how the weather can affect the recreation center — for example, if it rains, where all the rainwater will gather. To do so, he is going to find the cell having minimum height among all cells that are shown on the screen of his laptop.Help Seryozha to calculate the sum of heights of such cells for all possible subrectangles he can see on his screen. In other words, you have to calculate the sum of minimum heights in submatrices of size a \times b with top left corners in (i, j) over all 1 \le i \le n - a + 1 and 1 \le j \le m - b + 1.Consider the sequence g_i = (g_{i - 1} \cdot x + y) \bmod z. You are given integers g_0, x, y and z. By miraculous coincidence, h_{i, j} = g_{(i - 1) \cdot m + j - 1} ((i - 1) \cdot m + j - 1 is the index).InputThe first line of the input contains four integers n, m, a and b (1 \le n, m \le 3\,000, 1 \le a \le n, 1 \le b \le m) — the number of rows and columns in the matrix Seryozha has, and the number of rows and columns that can be shown on the screen of the laptop, respectively.The second line of the input contains four integers g_0, x, y and z (0 \le g_0, x, y < z \le 10^9).OutputPrint a single integer — the answer to the problem.ExampleInput
3 4 2 1
1 2 3 59
Output
111
NoteThe matrix from the first example: | 3 4 2 1
1 2 3 59
| 111 | 2 seconds | 256 megabytes | ['data structures', 'two pointers', '*2100'] |
D2. Submarine in the Rybinsk Sea (hard edition)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, \dots, a_n.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q), where a_1 \dots a_p and b_1 \dots b_q are digits of two integers written in the decimal notation without leading zeros.In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212Formally, if p \ge q then f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q; if p < q then f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q. Mishanya gives you an array consisting of n integers a_i, your task is to help students to calculate \sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j) modulo 998\,244\,353.InputThe first line of the input contains a single integer n (1 \le n \le 100\,000) — the number of elements in the array. The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the elements of the array.OutputPrint the answer modulo 998\,244\,353.ExamplesInput
3
12 3 45
Output
12330Input
2
123 456
Output
1115598 | 3
12 3 45
| 12330 | 2 seconds | 256 megabytes | ['combinatorics', 'math', 'number theory', '*1800'] |
D1. Submarine in the Rybinsk Sea (easy edition)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem differs from the next one only in the presence of the constraint on the equal length of all numbers a_1, a_2, \dots, a_n. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q), where a_1 \dots a_p and b_1 \dots b_q are digits of two integers written in the decimal notation without leading zeros.In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212Formally, if p \ge q then f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q; if p < q then f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q. Mishanya gives you an array consisting of n integers a_i. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate \sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j) modulo 998\,244\,353.InputThe first line of the input contains a single integer n (1 \le n \le 100\,000) — the number of elements in the array. The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the elements of the array. All numbers a_1, a_2, \dots, a_n are of equal length (that is, they consist of the same number of digits).OutputPrint the answer modulo 998\,244\,353.ExamplesInput
3
12 33 45
Output
26730Input
2
123 456
Output
1115598Input
1
1
Output
11Input
5
1000000000 1000000000 1000000000 1000000000 1000000000
Output
265359409 | 3
12 33 45
| 26730 | 2 seconds | 256 megabytes | ['combinatorics', 'math', 'number theory', '*1500'] |
C. Basketball Exercisetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFinally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 \cdot n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from left to right. Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all 2n students (there are no additional constraints), and a team can consist of any number of students. Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.InputThe first line of the input contains a single integer n (1 \le n \le 10^5) — the number of students in each row.The second line of the input contains n integers h_{1, 1}, h_{1, 2}, \ldots, h_{1, n} (1 \le h_{1, i} \le 10^9), where h_{1, i} is the height of the i-th student in the first row.The third line of the input contains n integers h_{2, 1}, h_{2, 2}, \ldots, h_{2, n} (1 \le h_{2, i} \le 10^9), where h_{2, i} is the height of the i-th student in the second row.OutputPrint a single integer — the maximum possible total height of players in a team Demid can choose.ExamplesInput
5
9 3 5 7 3
5 8 1 4 5
Output
29
Input
3
1 2 9
10 1 1
Output
19
Input
1
7
4
Output
7
NoteIn the first example Demid can choose the following team as follows: In the second example Demid can choose the following team as follows: | 5
9 3 5 7 3
5 8 1 4 5
| 29 | 2 seconds | 256 megabytes | ['dp', '*1400'] |
B. Sport Mafiatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach evening after the dinner the SIS's students gather together to play the game of Sport Mafia. For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remaining moves she can choose from two options: the first option, in case the box contains at least one candy, is to take exactly one candy out and eat it. This way the number of candies in the box decreased by 1; the second option is to put candies in the box. In this case, Alya will put 1 more candy, than she put in the previous time. Thus, if the box is empty, then it can only use the second option.For example, one possible sequence of Alya's actions look as follows: put one candy into the box; put two candies into the box; eat one candy from the box; eat one candy from the box; put three candies into the box; eat one candy from the box; put four candies into the box; eat one candy from the box; put five candies into the box; This way she will perform 9 actions, the number of candies at the end will be 11, while Alya will eat 4 candies in total.You know the total number of actions n and the number of candies at the end k. You need to find the total number of sweets Alya ate. That is the number of moves of the first option. It's guaranteed, that for the given n and k the answer always exists.Please note, that during an action of the first option, Alya takes out and eats exactly one candy.InputThe first line contains two integers n and k (1 \le n \le 10^9; 0 \le k \le 10^9) — the total number of moves and the number of candies in the box at the end. It's guaranteed, that for the given n and k the answer exists.OutputPrint a single integer — the number of candies, which Alya ate. Please note, that in this problem there aren't multiple possible answers — the answer is unique for any input data. ExamplesInput
1 1
Output
0Input
9 11
Output
4Input
5 0
Output
3Input
3 2
Output
1NoteIn the first example, Alya has made one move only. According to the statement, the first move is always putting one candy in the box. Hence Alya ate 0 candies.In the second example the possible sequence of Alya's actions looks as follows: put 1 candy, put 2 candies, eat a candy, eat a candy, put 3 candies, eat a candy, put 4 candies, eat a candy, put 5 candies. This way, she will make exactly n=9 actions and in the end the box will contain 1+2-1-1+3-1+4-1+5=11 candies. The answer is 4, since she ate 4 candies in total. | 1 1
| 0 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'math', '*1000'] |
A. Drinks Choosingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOld timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integers a_1, a_2, \dots, a_n, where a_i (1 \le a_i \le k) is the type of the favorite drink of the i-th student. The drink types are numbered from 1 to k.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are k types of drink sets, the j-th type contains two portions of the drink j. The available number of sets of each of the k types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly \lceil \frac{n}{2} \rceil, where \lceil x \rceil is x rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if n is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if \lceil \frac{n}{2} \rceil sets will be chosen optimally and students will distribute portions between themselves optimally?InputThe first line of the input contains two integers n and k (1 \le n, k \le 1\,000) — the number of students in the building and the number of different drinks.The next n lines contain student's favorite drinks. The i-th line contains a single integer from 1 to k — the type of the favorite drink of the i-th student.OutputPrint exactly one integer — the maximum number of students that can get a favorite drink.ExamplesInput
5 3
1
3
1
1
2
Output
4
Input
10 3
2
1
3
2
3
3
1
3
1
2
Output
9
NoteIn the first example, students could choose three sets with drinks 1, 1 and 2 (so they will have two sets with two drinks of the type 1 each and one set with two drinks of the type 2, so portions will be 1, 1, 1, 1, 2, 2). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks 1, 2 and 3. In this case the portions will be 1, 1, 2, 2, 3, 3. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with a_i = 1 (i.e. the first, the third or the fourth). | 5 3
1
3
1
1
2
| 4 | 2 seconds | 256 megabytes | ['greedy', 'math', '*1000'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.