contest_id
int32
1
2.13k
index
stringclasses
62 values
problem_id
stringlengths
2
6
title
stringlengths
0
67
rating
int32
0
3.5k
tags
stringlengths
0
139
statement
stringlengths
0
6.96k
input_spec
stringlengths
0
2.32k
output_spec
stringlengths
0
1.52k
note
stringlengths
0
5.06k
sample_tests
stringlengths
0
1.02k
difficulty_category
stringclasses
6 values
tag_count
int8
0
11
statement_length
int32
0
6.96k
input_spec_length
int16
0
2.32k
output_spec_length
int16
0
1.52k
contest_year
int16
0
21
1,325
D
1325D
D. Ehab the Xorcist
1,700
bitmasks; constructive algorithms; greedy; number theory
Given 2 integers \(u\) and \(v\), find the shortest array such that bitwise-xor of its elements is \(u\), and the sum of its elements is \(v\).
The only line contains 2 integers \(u\) and \(v\) \((0 \le u,v \le 10^{18})\).
If there's no array that satisfies the condition, print ""-1"". Otherwise:The first line should contain one integer, \(n\), representing the length of the desired array. The next line should contain \(n\) positive integers, the array itself. If there are multiple possible answers, print any.
In the first sample, \(3\oplus 1 = 2\) and \(3 + 1 = 4\). There is no valid array of smaller length.Notice that in the fourth sample the array is empty.
Input: 2 4 | Output: 2 3 1
Medium
4
143
78
292
13
1,572
C
1572C
C. Paint
2,700
dp; greedy
You are given a \(1\) by \(n\) pixel image. The \(i\)-th pixel of the image has color \(a_i\). For each color, the number of pixels of that color is at most \(20\).You can perform the following operation, which works like the bucket tool in paint programs, on this image: pick a color — an integer from \(1\) to \(n\); choose a pixel in the image; for all pixels connected to the selected pixel, change their colors to the selected color (two pixels of the same color are considered connected if all the pixels between them have the same color as those two pixels). Compute the minimum number of operations needed to make all the pixels in the image have the same color.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^3\)).The first line of each test case contains a single integer \(n\) (\(1 \le n \le 3\cdot10^3\)) — the number of pixels in the image.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le n\)) — the colors of the pixels in the image.Note: for each color, the number of pixels of that color is at most \(20\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(3\cdot10^3\).
For each test case, print one integer: the minimum number of operations needed to make all the pixels in the image have the same color.
In the first example, the optimal solution is to apply the operation on the third pixel changing its color to \(2\) and then to apply the operation on any pixel that has color \(2\) changing its color and the color of all pixels connected to it to \(1\). The sequence of operations is then: \([1, 2, 3, 2, 1] \to [1, 2, 2, 2, 1] \to [1, 1, 1, 1, 1]\).In the second example, we can either change the \(1\)s to \(2\)s in one operation or change the \(2\)s to \(1\)s also in one operation.In the third example, one possible way to make all the pixels have the same color is to apply the operation on the first, third and the fourth pixel each time changing its color to \(2\).
Input: 3 5 1 2 3 2 1 4 1 1 2 2 5 1 2 1 4 2 | Output: 2 1 3
Master
2
670
559
135
15
63
B
63B
B. Settlers' Training
1,200
implementation
In a strategic computer game ""Settlers II"" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.
The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).
Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.
In the first example the ranks will be raised in the following manner:1 2 2 3 → 2 2 3 4 → 2 3 4 4 → 3 4 4 4 → 4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.
Input: 4 41 2 2 3 | Output: 4
Easy
1
1,284
326
105
0
949
C
949C
C. Data Center Maintenance
1,900
dfs and similar; graphs
BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!).Main feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers.For each of m company clients, let us denote indices of two different data centers storing this client data as ci, 1 and ci, 2.In order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day.Data center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly h hours long. For each data center there is an integer uj (0 ≤ uj ≤ h - 1) defining the index of an hour of day, such that during this hour data center j is unavailable due to maintenance.Summing up everything above, the condition uci, 1 ≠ uci, 2 should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance.Due to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for them by an hour later (i.e. if uj = h - 1, then the new maintenance hour would become 0, otherwise it would become uj + 1). Nonetheless, such an experiment should not break the accessibility guarantees, meaning that data of any client should be still available during any hour of a day after the data center maintenance times are changed.Such an experiment would provide useful insights, but changing update time is quite an expensive procedure, that is why the company asked you to find out the minimum number of data centers that have to be included in an experiment in order to keep the data accessibility guarantees.
The first line of input contains three integers n, m and h (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000, 2 ≤ h ≤ 100 000), the number of company data centers, number of clients and the day length of day measured in hours. The second line of input contains n integers u1, u2, ..., un (0 ≤ uj < h), j-th of these numbers is an index of a maintenance hour for data center j. Each of the next m lines contains two integers ci, 1 and ci, 2 (1 ≤ ci, 1, ci, 2 ≤ n, ci, 1 ≠ ci, 2), defining the data center indices containing the data of client i.It is guaranteed that the given maintenance schedule allows each client to access at least one copy of his data at any moment of day.
In the first line print the minimum possible number of data centers k (1 ≤ k ≤ n) that have to be included in an experiment in order to keep the data available for any client.In the second line print k distinct integers x1, x2, ..., xk (1 ≤ xi ≤ n), the indices of data centers whose maintenance time will be shifted by one hour later. Data center indices may be printed in any order.If there are several possible answers, it is allowed to print any of them. It is guaranteed that at there is at least one valid choice of data centers.
Consider the first sample test. The given answer is the only way to conduct an experiment involving the only data center. In such a scenario the third data center has a maintenance during the hour 1, and no two data centers storing the information of the same client have maintenance at the same hour.On the other hand, for example, if we shift the maintenance time on hour later for the first data center, then the data of clients 1 and 3 will be unavailable during the hour 0.
Input: 3 3 54 4 01 33 23 1 | Output: 13
Hard
2
2,628
661
535
9
2,085
A
2085A
A. Serval and String Theory
900
constructive algorithms; implementation
A string \(r\) consisting only of lowercase Latin letters is called universal if and only if \(r\) is lexicographically smaller\(^{\text{∗}}\) than the reversal\(^{\text{†}}\) of \(r\).You are given a string \(s\) consisting of \(n\) lowercase Latin letters. You are required to make \(s\) universal. To achieve this, you can perform the following operation on \(s\) at most \(k\) times: Choose two indices \(i\) and \(j\) (\(1\le i,j\le n\)), then swap \(s_i\) and \(s_j\). Note that if \(i=j\), you do nothing. Determine whether you can make \(s\) universal by performing the above operation at most \(k\) times.\(^{\text{∗}}\)A string \(a\) is lexicographically smaller than a string \(b\) of the same length, if and only if the following holds: in the first position where \(a\) and \(b\) differ, the string \(a\) has a letter that appears earlier in the alphabet than the corresponding letter in \(b\). \(^{\text{†}}\)The reversal of a string \(r\) is the string obtained by writing \(r\) from right to left. For example, the reversal of the string \(\texttt{abcad}\) is \(\texttt{dacba}\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(k\) (\(1\le n\le 100\), \(0\le k\le 10^4\)) — the length of the string \(s\), and the maximum number of operations you can perform.The second line contains a string \(s\) consisting of \(n\) lowercase Latin letters.
For each test case, print ""YES"" if it is possible to make \(s\) universal by performing the operation at most \(k\) times. Otherwise, print ""NO"".You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In the first test case, \(s\) will keep the same after any operations. However, the reversal of \(\texttt{a}\) is still \(\texttt{a}\), so it is impossible to make \(s\) universal.In the second test case, the string \(\texttt{rev}\) is lexicographically smaller than \(\texttt{ver}\). Thus, \(s\) is already universal.In the fifth test case, you can perform the operations as follows: Swap \(s_4\) and \(s_7\). After this operation, \(s\) becomes \(\texttt{uniserval}\); Swap \(s_1\) and \(s_3\). After this operation, \(s\) becomes \(\texttt{inuserval}\). And the string \(\texttt{inuserval}\) is universal.
Input: 81 10000a3 3rev6 0string6 0theory9 2universal19 0codeforcesecrofedoc19 1codeforcesecrofedoc3 1zzz | Output: NO YES NO YES YES NO YES NO
Beginner
2
1,095
443
310
20
763
C
763C
C. Timofey and remoduling
2,600
brute force; implementation; math; number theory
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)·d, each taken modulo m.
The first line contains two integers m and n (2 ≤ m ≤ 109 + 7, 1 ≤ n ≤ 105, m is prime) — Timofey's favorite prime module and the length of the sequence.The second line contains n distinct integers a1, a2, ..., an (0 ≤ ai < m) — the elements of the sequence.
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.Otherwise, print two integers — the first element of the obtained progression x (0 ≤ x < m) and its difference d (0 ≤ d < m).If there are multiple answers, print any of them.
Input: 17 50 2 4 13 15 | Output: 13 2
Expert
4
624
258
303
7
928
C
928C
C. Dependency management
1,900
*special; graphs; implementation
Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version — positive integer from 1 to 106. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies.You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored.More formal, choose such a set of projects of minimum possible size that the following conditions hold: Polycarp's project is chosen; Polycarp's project depends (directly or indirectly) on all other projects in the set; no two projects share the name; for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order.
The first line contains an only integer n (1 ≤ n ≤ 1 000) — the number of projects in Vaja.The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to n - 1) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding.It's guaranteed that there are no cyclic dependencies.
Output all Polycarp's project's dependencies in lexicographical order.
The first sample is given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «a» (version 3) depends on are painted black. The second sample is again given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «codehorses» (version 5) depends on are paint it black. Note that «extra 1» is chosen instead of «extra 3» since «mashadb 1» and all of its dependencies are ignored due to «mashadb 2».
Input: 4a 32b 1c 1 b 20 b 11b 2 c 11b 2 | Output: 2b 1c 1
Hard
3
1,756
672
70
9
1,714
D
1714D
D. Color with Occurrences
1,600
brute force; data structures; dp; greedy; strings
You are given some text \(t\) and a set of \(n\) strings \(s_1, s_2, \dots, s_n\). In one step, you can choose any occurrence of any string \(s_i\) in the text \(t\) and color the corresponding characters of the text in red. For example, if \(t=\texttt{bababa}\) and \(s_1=\texttt{ba}\), \(s_2=\texttt{aba}\), you can get \(t=\color{red}{\texttt{ba}}\texttt{baba}\), \(t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}\) or \(t=\texttt{bab}\color{red}{\texttt{aba}}\) in one step.You want to color all the letters of the text \(t\) in red. When you color a letter in red again, it stays red.In the example above, three steps are enough: Let's color \(t[2 \dots 4]=s_2=\texttt{aba}\) in red, we get \(t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}\); Let's color \(t[1 \dots 2]=s_1=\texttt{ba}\) in red, we get \(t=\color{red}{\texttt{baba}}\texttt{ba}\); Let's color \(t[4 \dots 6]=s_2=\texttt{aba}\) in red, we get \(t=\color{red}{\texttt{bababa}}\). Each string \(s_i\) can be applied any number of times (or not at all). Occurrences for coloring can intersect arbitrarily.Determine the minimum number of steps needed to color all letters \(t\) in red and how to do it. If it is impossible to color all letters of the text \(t\) in red, output -1.
The first line of the input contains an integer \(q\) (\(1 \le q \le 100\)) —the number of test cases in the test.The descriptions of the test cases follow.The first line of each test case contains the text \(t\) (\(1 \le |t| \le 100\)), consisting only of lowercase Latin letters, where \(|t|\) is the length of the text \(t\).The second line of each test case contains a single integer \(n\) (\(1 \le n \le 10\)) — the number of strings in the set.This is followed by \(n\) lines, each containing a string \(s_i\) (\(1 \le |s_i| \le 10\)) consisting only of lowercase Latin letters, where \(|s_i|\) — the length of string \(s_i\).
For each test case, print the answer on a separate line.If it is impossible to color all the letters of the text in red, print a single line containing the number -1.Otherwise, on the first line, print the number \(m\) — the minimum number of steps it will take to turn all the letters \(t\) red.Then in the next \(m\) lines print pairs of indices: \(w_j\) and \(p_j\) (\(1 \le j \le m\)), which denote that the string with index \(w_j\) was used as a substring to cover the occurrences starting in the text \(t\) from position \(p_j\). The pairs can be output in any order.If there are several answers, output any of them.
The first test case is explained in the problem statement.In the second test case, it is impossible to color all the letters of the text in red.
Input: 6bababa2baabacaba2bacacababacabaca3ababacacabaca3acbcodeforces4defcodeefoforcesaaaabbbbcccceeee4eeeeccccaaaabbbb | Output: 3 2 2 1 1 2 4 -1 4 1 1 2 6 3 3 3 7 4 3 1 1 2 2 3 1 4 2 4 5 2 1 4 3 1 4 5 2 9 1 13
Medium
5
1,250
632
623
17
1,296
A
1296A
A. Array with Odd Sum
800
math
You are given an array \(a\) consisting of \(n\) integers.In one move, you can choose two indices \(1 \le i, j \le n\) such that \(i \ne j\) and set \(a_i := a_j\). You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose \(i\) and \(j\) and replace \(a_i\) with \(a_j\)).Your task is to say if it is possible to obtain an array with an odd (not divisible by \(2\)) sum of elements.You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 2000\)) — the number of test cases.The next \(2t\) lines describe test cases. The first line of the test case contains one integer \(n\) (\(1 \le n \le 2000\)) — the number of elements in \(a\). The second line of the test case contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 2000\)), where \(a_i\) is the \(i\)-th element of \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2000\) (\(\sum n \le 2000\)).
For each test case, print the answer on it — ""YES"" (without quotes) if it is possible to obtain the array with an odd sum of elements, and ""NO"" otherwise.
Input: 5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 | Output: YES NO YES NO NO
Beginner
1
561
526
158
12
231
D
231D
D. Magic Box
1,600
brute force; geometry
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0, 0, 0), and the opposite one is at point (x1, y1, z1). The six faces of the box contain some numbers a1, a2, ..., a6, exactly one number right in the center of each face. The numbers are located on the box like that: number a1 is written on the face that lies on the ZOX plane; a2 is written on the face, parallel to the plane from the previous point; a3 is written on the face that lies on the XOY plane; a4 is written on the face, parallel to the plane from the previous point; a5 is written on the face that lies on the YOZ plane; a6 is written on the face, parallel to the plane from the previous point. At the moment Vasya is looking at the box from point (x, y, z). Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the ai numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some ai = 6, then he can't mistake this number for 9 and so on).
The fist input line contains three space-separated integers x, y and z (|x|, |y|, |z| ≤ 106) — the coordinates of Vasya's position in space. The second line contains three space-separated integers x1, y1, z1 (1 ≤ x1, y1, z1 ≤ 106) — the coordinates of the box's vertex that is opposite to the vertex at point (0, 0, 0). The third line contains six space-separated integers a1, a2, ..., a6 (1 ≤ ai ≤ 106) — the numbers that are written on the box faces. It is guaranteed that point (x, y, z) is located strictly outside the box.
Print a single integer — the sum of all numbers on the box faces that Vasya sees.
The first sample corresponds to perspective, depicted on the picture. Vasya sees numbers a2 (on the top face that is the darkest), a6 (on the right face that is the lightest) and a4 (on the left visible face).In the second sample Vasya can only see number a4.
Input: 2 2 21 1 11 2 3 4 5 6 | Output: 12
Medium
2
1,623
527
81
2
1,286
B
1286B
B. Numbers on Tree
1,800
constructive algorithms; data structures; dfs and similar; graphs; greedy; trees
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from \(1\) to \(n\). Each of its vertices also has an integer \(a_i\) written on it. For each vertex \(i\), Evlampiy calculated \(c_i\) — the number of vertices \(j\) in the subtree of vertex \(i\), such that \(a_j < a_i\). Illustration for the second example, the first integer is \(a_i\) and the integer in parentheses is \(c_i\)After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of \(c_i\), but he completely forgot which integers \(a_i\) were written on the vertices.Help him to restore initial integers!
The first line contains an integer \(n\) \((1 \leq n \leq 2000)\) — the number of vertices in the tree.The next \(n\) lines contain descriptions of vertices: the \(i\)-th line contains two integers \(p_i\) and \(c_i\) (\(0 \leq p_i \leq n\); \(0 \leq c_i \leq n-1\)), where \(p_i\) is the parent of vertex \(i\) or \(0\) if vertex \(i\) is root, and \(c_i\) is the number of vertices \(j\) in the subtree of vertex \(i\), such that \(a_j < a_i\).It is guaranteed that the values of \(p_i\) describe a rooted tree with \(n\) vertices.
If a solution exists, in the first line print ""YES"", and in the second line output \(n\) integers \(a_i\) \((1 \leq a_i \leq {10}^{9})\). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all \(a_i\) are between \(1\) and \(10^9\).If there are no solutions, print ""NO"".
Input: 3 2 0 0 2 2 0 | Output: YES 1 2 1
Medium
6
634
533
357
12
1,182
C
1182C
C. Beautiful Lyrics
1,700
data structures; greedy; strings
You are given \(n\) words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters ""a"", ""e"", ""o"", ""i"", and ""u"" are vowels. Note that ""y"" is never vowel.For example of a beautiful lyric, ""hello hellooowww"" ""whatsup yowowowow"" is a beautiful lyric because there are two vowels each in ""hello"" and ""whatsup"", four vowels each in ""hellooowww"" and ""yowowowow"" (keep in mind that ""y"" is not a vowel), and the last vowel of each line is ""o"".For example of a not beautiful lyric, ""hey man""""iam mcdic"" is not a beautiful lyric because ""hey"" and ""iam"" don't have same number of vowels and the last vowels of two lines are different (""a"" in the first and ""i"" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.
The first line contains single integer \(n\) (\(1 \le n \le 10^{5}\)) — the number of words.The \(i\)-th of the next \(n\) lines contains string \(s_{i}\) consisting lowercase alphabet letters — the \(i\)-th word. It is guaranteed that the sum of the total word length is equal or less than \(10^{6}\). Each word contains at least one vowel.
In the first line, print \(m\) — the number of maximum possible beautiful lyrics.In next \(2m\) lines, print \(m\) beautiful lyrics (two lines per lyric).If there are multiple answers, print any.
In the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. ""about proud hooray round"" forms a beautiful lyric because ""about"" and ""hooray"" have same number of vowels, ""proud"" and ""round"" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word ""codeforces"".In the second example, you cannot form any beautiful lyric from given words.In the third example, you can use the word ""same"" up to three times.
Input: 14 wow this is the first mcdics codeforces round hooray i am proud about that | Output: 3 about proud hooray round wow first this is i that mcdics am
Medium
3
1,614
341
195
11
436
A
436A
A. Feed with Candy
1,500
greedy
The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters above the floor of the house, its mass is mi. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?
The first line contains two integers, n and x (1 ≤ n, x ≤ 2000) — the number of sweets Evan has and the initial height of Om Nom's jump. Each of the following n lines contains three integers ti, hi, mi (0 ≤ ti ≤ 1; 1 ≤ hi, mi ≤ 2000) — the type, height and the mass of the i-th candy. If number ti equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.
Print a single integer — the maximum number of candies Om Nom can eat.
One of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario: Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7. Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12. At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15. Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 4.
Input: 5 30 2 41 3 10 8 30 20 101 5 5 | Output: 4
Medium
1
707
379
70
4
632
B
632B
B. Alice, Bob, Two Teams
1,400
brute force; constructive algorithms
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.The way to split up game pieces is split into several steps: First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once. Alice will get all the pieces marked A and Bob will get all the pieces marked B. The strength of a player is then the sum of strengths of the pieces in the group.Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
The first line contains integer n (1 ≤ n ≤ 5·105) — the number of game pieces.The second line contains n integers pi (1 ≤ pi ≤ 109) — the strength of the i-th piece.The third line contains n characters A or B — the assignment of teams after the first step (after Alice's step).
Print the only integer a — the maximum strength Bob can achieve.
In the first sample Bob should flip the suffix of length one.In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.In the third sample Bob should do nothing.
Input: 51 2 3 4 5ABABA | Output: 11
Easy
2
863
277
64
6
1,137
F
1137F
F. Matches Are Not a Child's Play
3,400
data structures; trees
Lena is playing with matches. The natural question arising in the head of any child playing with matches is whether it's possible to set a tree on fire with a matches, or not.Let's say, that the tree is a connected graph without cycles and the vertices are labeled with integers \(1, 2, \ldots, n\). Also every vertex \(v\) has some integer priority \(p_v\) associated with it. All priorities are distinct.It turns out, that if you set a tree on fire, it will burn to nothing. However, this process doesn't happen instantly. At the beginning, burns out the leaf (a vertex is called to be a leaf if it has only one adjacent vertex) of the tree of the minimum priority. Then burns out the leaf of the minimal priority of the remaining tree, and so on. This way, the vertices turn into the leaves and burn out until only one vertex remains. Then this vertex burns out as well.Lena has prepared a tree of \(n\) vertices and every vertex in it has a priority \(p_v = v\). Lena is very curious about burning out this tree. However, she understands, that if she will burn the tree now, then it will disappear completely. Lena is a kind girl and she will feel bad for the burned tree, so she wants to study the process of burning the tree only in her mind. Lena wants to process \(q\) queries, each of them is one of three following types: ""up \(v\)"", assign the vertex \(v\) priority \(1 + \max\{p_1, p_2, \ldots, p_n\}\); ""when \(v\)"", find the step at which the vertex \(v\) will burn out, if the tree would be set on fire now; ""compare \(v\) \(u\)"", find out which of the vertices \(v\) and \(u\) will burn out first, if the tree would be set on fire now. Notice, that if all priorities would be distinct, then after the ""up"" query they will stay distinct as well. Initially all priorities are distinct, hence during any (purely hypothetical of course) burning of the tree, all leafs would have distinct priorities.
The first line contains two integers \(n\) and \(q\) (\(2 \le n \le 200\,000\), \(1 \le q \le 200\,000\)) — the number of vertices in the tree and the number of queries.The \(i\)-th of the following \(n - 1\) lines contains two integers \(v_i\), \(u_i\) (\(1 \le v_i, u_i \le n\)), denoting the endpoints of the \(i\)-th edge.Each of the remaining \(q\) lines contains a query of one of the following three types: ""up \(v\)"" (\(1 \le v \le n\)) — change the priority of vertex \(v\); ""when \(v\)"" (\(1 \le v \le n\)) — determine the step at which the vertex \(v\) will burn out; ""compare \(v\) \(u\)"" (\(1 \le v, u \le n\), \(v \ne u\)) — determine which of vertices \(v\) and \(u\) will burn out earlier in the current tree. It's guaranteed, that there is at least one query of type ""when"" or ""compare"".
For every query of type ""when"" print one integer in range from \(1\) to \(n\) — the step at which the vertex \(v\) will burn out.For every query of type ""compare"" print either \(v\) or \(u\), depending on which one will burn out earlier.
In the first example, the process of burning of the tree is illustrated on the following picture: In particular, the vertices of the tree will burn out in the following order: \([2, 4, 3, 1, 5]\).In the second example, after applying the ""up"" operation, the order of vertices will change to: \([2, 4, 3, 5, 1]\).
Input: 5 7 1 5 1 2 1 3 4 3 when 1 when 2 when 3 when 4 when 5 compare 2 3 compare 3 4 | Output: 4 1 3 2 5 2 4
Master
2
1,919
814
241
11
1,129
A2
1129A2
A2. Toy Train
1,800
brute force; greedy
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of \(n\) stations, enumerated from \(1\) through \(n\). The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station \(i\) is station \(i+1\) if \(1 \leq i < n\) or station \(1\) if \(i = n\). It takes the train \(1\) second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver \(m\) candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from \(1\) through \(m\). Candy \(i\) (\(1 \leq i \leq m\)), now at station \(a_i\), should be delivered to station \(b_i\) (\(a_i \neq b_i\)). The blue numbers on the candies correspond to \(b_i\) values. The image corresponds to the \(1\)-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
The first line contains two space-separated integers \(n\) and \(m\) (\(2 \leq n \leq 5\,000\); \(1 \leq m \leq 20\,000\)) — the number of stations and the number of candies, respectively.The \(i\)-th of the following \(m\) lines contains two space-separated integers \(a_i\) and \(b_i\) (\(1 \leq a_i, b_i \leq n\); \(a_i \neq b_i\)) — the station that initially contains candy \(i\) and the destination station of the candy, respectively.
In the first and only line, print \(n\) space-separated integers, the \(i\)-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station \(i\).
Consider the second sample.If the train started at station \(1\), the optimal strategy is as follows. Load the first candy onto the train. Proceed to station \(2\). This step takes \(1\) second. Deliver the first candy. Proceed to station \(1\). This step takes \(1\) second. Load the second candy onto the train. Proceed to station \(2\). This step takes \(1\) second. Deliver the second candy. Proceed to station \(1\). This step takes \(1\) second. Load the third candy onto the train. Proceed to station \(2\). This step takes \(1\) second. Deliver the third candy. Hence, the train needs \(5\) seconds to complete the tasks.If the train were to start at station \(2\), however, it would need to move to station \(1\) before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is \(5+1 = 6\) seconds.
Input: 5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5 | Output: 10 9 10 10 9
Medium
2
1,441
440
205
11
1,474
E
1474E
E. What Is It?
2,500
constructive algorithms; greedy
Lunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation \(p\) of length \(n\). Scientists found out, that to overcome an obstacle, the robot should make \(p\) an identity permutation (make \(p_i = i\) for all \(i\)).Unfortunately, scientists can't control the robot. Thus the only way to make \(p\) an identity permutation is applying the following operation to \(p\) multiple times: Select two indices \(i\) and \(j\) (\(i \neq j\)), such that \(p_j = i\) and swap the values of \(p_i\) and \(p_j\). It takes robot \((j - i)^2\) seconds to do this operation. Positions \(i\) and \(j\) are selected by the robot (scientists can't control it). He will apply this operation while \(p\) isn't an identity permutation. We can show that the robot will make no more than \(n\) operations regardless of the choice of \(i\) and \(j\) on each operation.Scientists asked you to find out the maximum possible time it will take the robot to finish making \(p\) an identity permutation (i. e. worst-case scenario), so they can decide whether they should construct a new lunar rover or just rest and wait. They won't believe you without proof, so you should build an example of \(p\) and robot's operations that maximizes the answer.For a better understanding of the statement, read the sample description.
The first line of input contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) — the number of test cases.Each of next \(t\) lines contains the single integer \(n\) (\(2 \leq n \leq 10^5\)) – the length of \(p\).Note, that \(p\) is not given to you. You should find the maximum possible time over all permutations of length \(n\).It is guaranteed, that the total sum of \(n\) over all test cases doesn't exceed \(10^5\).
For each test case in the first line, print how many seconds will the robot spend in the worst case.In the next line, print the initial value of \(p\) that you used to construct an answer.In the next line, print the number of operations \(m \leq n\) that the robot makes in your example.In the each of next \(m\) lines print two integers \(i\) and \(j\) — indices of positions that the robot will swap on this operation. Note that \(p_j = i\) must holds (at the time of operation).
For \(n = 2\), \(p\) can be either \([1, 2]\) or \([2, 1]\). In the first case \(p\) is already identity, otherwise robot will make it an identity permutation in \(1\) second regardless of choise \(i\) and \(j\) on the first operation.For \(n = 3\), \(p\) can be equals \([2, 3, 1]\). If robot will select \(i = 3, j = 2\) on the first operation, \(p\) will become \([2, 1, 3]\) in one second. Now robot can select only \(i = 1, j = 2\) or \(i = 2, j = 1\). In both cases, \(p\) will become identity in one more second (\(2\) seconds in total). If robot will select \(i = 1, j = 3\) on the first operation, \(p\) will become \([1, 3, 2]\) in four seconds. Regardless of choise of \(i\) and \(j\) on the second operation, \(p\) will become identity in five seconds. We can show, that for permutation of length \(3\) robot will always finish all operation in no more than \(5\) seconds.
Input: 3 2 3 3 | Output: 1 2 1 1 2 1 5 2 3 1 2 1 3 3 2 5 2 3 1 2 1 3 2 3
Expert
2
1,335
422
481
14
213
A
213A
A. Game
1,700
dfs and similar; greedy
Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies. Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions: Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer. Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that. Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that. Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.
The first line contains integer n (1 ≤ n ≤ 200) — the number of game parts. The next line contains n integers, the i-th integer — ci (1 ≤ ci ≤ 3) represents the number of the computer, on which you can complete the game part number i. Next n lines contain descriptions of game parts. The i-th line first contains integer ki (0 ≤ ki ≤ n - 1), then ki distinct integers ai, j (1 ≤ ai, j ≤ n; ai, j ≠ i) — the numbers of parts to complete before part i.Numbers on all lines are separated by single spaces. You can assume that the parts of the game are numbered from 1 to n in some way. It is guaranteed that there are no cyclic dependencies between the parts of the game.
On a single line print the answer to the problem.
Note to the second sample: before the beginning of the game the best strategy is to stand by the third computer. First we complete part 5. Then we go to the 1-st computer and complete parts 3 and 4. Then we go to the 2-nd computer and complete parts 1 and 2. In total we get 1+1+2+1+2, which equals 7 hours.
Input: 110 | Output: 1
Medium
2
1,398
668
49
2
1,285
E
1285E
E. Delete a Segment
2,300
brute force; constructive algorithms; data structures; dp; graphs; sortings; trees; two pointers
There are \(n\) segments on a \(Ox\) axis \([l_1, r_1]\), \([l_2, r_2]\), ..., \([l_n, r_n]\). Segment \([l, r]\) covers all points from \(l\) to \(r\) inclusive, so all \(x\) such that \(l \le x \le r\).Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is \(l_i=r_i\) is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if \(n=3\) and there are segments \([3, 6]\), \([100, 100]\), \([5, 8]\) then their union is \(2\) segments: \([3, 8]\) and \([100, 100]\); if \(n=5\) and there are segments \([1, 2]\), \([2, 3]\), \([4, 5]\), \([4, 6]\), \([6, 6]\) then their union is \(2\) segments: \([1, 3]\) and \([4, 6]\). Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given \(n\) so that the number of segments in the union of the rest \(n-1\) segments is maximum possible.For example, if \(n=4\) and there are segments \([1, 4]\), \([2, 3]\), \([3, 6]\), \([5, 7]\), then: erasing the first segment will lead to \([2, 3]\), \([3, 6]\), \([5, 7]\) remaining, which have \(1\) segment in their union; erasing the second segment will lead to \([1, 4]\), \([3, 6]\), \([5, 7]\) remaining, which have \(1\) segment in their union; erasing the third segment will lead to \([1, 4]\), \([2, 3]\), \([5, 7]\) remaining, which have \(2\) segments in their union; erasing the fourth segment will lead to \([1, 4]\), \([2, 3]\), \([3, 6]\) remaining, which have \(1\) segment in their union. Thus, you are required to erase the third segment to get answer \(2\).Write a program that will find the maximum number of segments in the union of \(n-1\) segments if you erase any of the given \(n\) segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly \(n-1\) segments.
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases in the test. Then the descriptions of \(t\) test cases follow.The first of each test case contains a single integer \(n\) (\(2 \le n \le 2\cdot10^5\)) — the number of segments in the given set. Then \(n\) lines follow, each contains a description of a segment — a pair of integers \(l_i\), \(r_i\) (\(-10^9 \le l_i \le r_i \le 10^9\)), where \(l_i\) and \(r_i\) are the coordinates of the left and right borders of the \(i\)-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot10^5\).
Print \(t\) integers — the answers to the \(t\) given test cases in the order of input. The answer is the maximum number of segments in the union of \(n-1\) segments if you erase any of the given \(n\) segments.
Input: 3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 | Output: 2 1 5
Expert
8
1,989
677
211
12
2,085
B
2085B
B. Serval and Final MEX
1,200
constructive algorithms; implementation
You are given an array \(a\) consisting of \(n\ge 4\) non-negative integers.You need to perform the following operation on \(a\) until its length becomes \(1\): Select two indices \(l\) and \(r\) (\(1\le {\color{red}{ l < r }} \le |a|\)), and replace the subarray \([a_l,a_{l+1},\ldots,a_r]\) with a single integer \(\operatorname{mex}([a_l,a_{l+1},\ldots,a_r])\), where \(\operatorname{mex}(b)\) denotes the minimum excluded (MEX)\(^{\text{∗}}\) of the integers in \(b\). In other words, let \(x=\operatorname{mex}([a_l,a_{l+1},\ldots,a_r])\), the array \(a\) will become \([a_1,a_2,\ldots,a_{l-1},x,a_{r+1},a_{r+2},\ldots,a_{|a|}]\). Note that the length of \(a\) decreases by \((r-l)\) after this operation. Serval wants the final element in \(a\) to be \(0\). Help him! More formally, you have to find a sequence of operations, such that after performing these operations in order, the length of \(a\) becomes \(1\), and the final element in \(a\) is \(0\).It can be shown that at least one valid operation sequence exists under the constraints of the problem, and the length of any valid operation sequence does not exceed \(n\).Note that you do not need to minimize the number of operations.\(^{\text{∗}}\)The minimum excluded (MEX) of a collection of integers \(b_1, b_2, \ldots, b_k\) is defined as the smallest non-negative integer \(x\) which does not occur in the collection \(b\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 1000\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(4\le n\le 5000\)) — the length of the array \(a\).The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0\le a_i\le n\)) — the elements of the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5000\).
For each test case, output a single integer \(k\) (\(0\le k\le n\)) in the first line of output — the length of the operation sequence.Then, output \(k\) lines, the \(i\)-th line containing two integers \(l_i\) and \(r_i\) (\(1\le l_i<r_i\le |a|\)) — the two indices you choose in the \(i\)-th operation, where \(|a|\) denotes the length of the array before this operation.If there are multiple answers, you may print any of them.
In the first test case, since \(\operatorname{mex}([1,2,3,4])=0\), after the only operation, the array becomes \([0]\).In the second test case, the array \(a\) changes as follows: $$$\( [\underline{0,1},0,0,1]\to [\underline{2,0},0,1]\to [\underline{1,0},1]\to [\underline{2,1}]\to [0]. \)\(In the third test case, the array \)a\( changes as follows: \)\( [0,0,0,0,\underline{0,0}]\to [0,0,\underline{0,0},1]\to [\underline{0,0},1,1]\to [\underline{1,1,1}]\to [0]. \)$$$
Input: 641 2 3 450 1 0 0 160 0 0 0 0 065 4 3 2 1 040 0 1 141 0 0 0 | Output: 1 1 4 4 1 2 1 2 1 2 1 2 4 5 6 3 4 1 2 1 3 3 4 5 4 5 1 4 2 1 2 1 3 2 2 4 1 2
Easy
2
1,392
484
430
20
1,012
A
1012A
A. Photo of The Sky
1,500
brute force; implementation; math; sortings
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates \((x, y)\), such that \(x_1 \leq x \leq x_2\) and \(y_1 \leq y \leq y_2\), where \((x_1, y_1)\) and \((x_2, y_2)\) are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of \(n\) of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
The first line of the input contains an only integer \(n\) (\(1 \leq n \leq 100\,000\)), the number of points in Pavel's records.The second line contains \(2 \cdot n\) integers \(a_1\), \(a_2\), ..., \(a_{2 \cdot n}\) (\(1 \leq a_i \leq 10^9\)), coordinates, written by Pavel in some order.
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
In the first sample stars in Pavel's records can be \((1, 3)\), \((1, 3)\), \((2, 3)\), \((2, 4)\). In this case, the minimal area of the rectangle, which contains all these points is \(1\) (rectangle with corners at \((1, 3)\) and \((2, 4)\)).
Input: 44 1 3 2 3 2 1 3 | Output: 1
Medium
4
1,283
290
117
10
198
B
198B
B. Jumping on Walls
1,400
shortest paths
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water ""move in turns"" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question.
The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly.The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character ""X"" represents a dangerous area and character ""-"" represents a safe area.The third line describes the right wall in the same format.It is guaranteed that the first area of the left wall is not dangerous.
Print ""YES"" (without the quotes) if the ninja can get out from the canyon, otherwise, print ""NO"" (without the quotes).
In the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon.
Input: 7 3---X--X-X--XX- | Output: YES
Easy
1
1,603
519
122
1
1,637
F
1637F
F. Towers
2,500
constructive algorithms; dfs and similar; dp; greedy; trees
You are given a tree with \(n\) vertices numbered from \(1\) to \(n\). The height of the \(i\)-th vertex is \(h_i\). You can place any number of towers into vertices, for each tower you can choose which vertex to put it in, as well as choose its efficiency. Setting up a tower with efficiency \(e\) costs \(e\) coins, where \(e > 0\).It is considered that a vertex \(x\) gets a signal if for some pair of towers at the vertices \(u\) and \(v\) (\(u \neq v\), but it is allowed that \(x = u\) or \(x = v\)) with efficiencies \(e_u\) and \(e_v\), respectively, it is satisfied that \(\min(e_u, e_v) \geq h_x\) and \(x\) lies on the path between \(u\) and \(v\).Find the minimum number of coins required to set up towers so that you can get a signal at all vertices.
The first line contains an integer \(n\) (\(2 \le n \le 200\,000\)) — the number of vertices in the tree.The second line contains \(n\) integers \(h_i\) (\(1 \le h_i \le 10^9\)) — the heights of the vertices.Each of the next \(n - 1\) lines contain a pair of numbers \(v_i, u_i\) (\(1 \le v_i, u_i \le n\)) — an edge of the tree. It is guaranteed that the given edges form a tree.
Print one integer — the minimum required number of coins.
In the first test case it's optimal to install two towers with efficiencies \(2\) at vertices \(1\) and \(3\).In the second test case it's optimal to install a tower with efficiency \(1\) at vertex \(1\) and two towers with efficiencies \(3\) at vertices \(2\) and \(5\).In the third test case it's optimal to install two towers with efficiencies \(6\) at vertices \(1\) and \(2\).
Input: 3 1 2 1 1 2 2 3 | Output: 4
Expert
5
763
380
57
16
1,025
F
1025F
F. Disjoint Triangles
2,700
geometry
A point belongs to a triangle if it lies inside the triangle or on one of its sides. Two triangles are disjoint if there is no point on the plane that belongs to both triangles.You are given \(n\) points on the plane. No two points coincide and no three points are collinear.Find the number of different ways to choose two disjoint triangles with vertices in the given points. Two ways which differ only in order of triangles or in order of vertices inside triangles are considered equal.
The first line of the input contains an integer \(n\) (\(6 \le n \le 2000\)) – the number of points.Each of the next \(n\) lines contains two integers \(x_i\) and \(y_i\) (\(|x_i|, |y_i| \le 10^9\)) – the coordinates of a point.No two points coincide and no three points are collinear.
Print one integer – the number of ways to choose two disjoint triangles.
In the first example there are six pairs of disjoint triangles, they are shown on the picture below. All other pairs of triangles are not disjoint, for example the following pair:
Input: 61 12 24 64 57 25 3 | Output: 6
Master
1
488
285
72
10
1,882
C
1882C
C. Card Game
1,500
brute force; greedy
There are \(n\) cards stacked in a deck. Initially, \(a_{i}\) is written on the \(i\)-th card from the top. The value written on a card does not change.You will play a game. Initially your score is \(0\). In each turn, you can do one of the following operations: Choose an odd\(^{\dagger}\) positive integer \(i\), which is not greater than the number of cards left in the deck. Remove the \(i\)-th card from the top of the deck and add the number written on the card to your score. The remaining cards will be reindexed starting from the top. Choose an even\(^{\ddagger}\) positive integer \(i\), which is not greater than the number of cards left in the deck. Remove the \(i\)-th card from the top of the deck. The remaining cards will be reindexed starting from the top. End the game. You can end the game whenever you want, you do not have to remove all cards from the initial deck. What is the maximum score you can get when the game ends?\(^{\dagger}\) An integer \(i\) is odd, if there exists an integer \(k\) such that \(i = 2k + 1\).\(^{\ddagger}\) An integer \(i\) is even, if there exists an integer \(k\) such that \(i = 2k\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^{4}\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^{5}\)).The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(-10^{9} \le a_i \le 10^{9}\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^{5}\).
For each test case, print a single integer — the maximum score you can get when the game ends.
In the first test case, one can get the score of \(5\) as follows: In the first turn, choose \(i=2\). Your score remains \(0\) and the numbers written on the cards from the top will become \([-4, -3, 5]\). In the second turn, choose \(i=3\). Your score will become \(5\) and the numbers written on the cards from the top will become \([-4, -3]\). In the third turn, end the game with the score of \(5\). In the second test case, one can get the score of \(4\) as follows: In the first turn, choose \(i=3\). Your score will become \(3\) and the numbers written on the cards from the top will become \([1, -2, -4]\). In the second turn, choose \(i=1\). Your score will become \(4\) and the numbers written on the cards from the top will become \([-2, -4]\). In the third turn, end the game with the score of \(4\). In the third test case, one can get the score of \(2\) as follows: In the first turn, choose \(i=1\). Your score will become \(-1\) and the numbers written on the cards from the top will become \([3, -5]\). In the second turn, choose \(i=1\). Your score will become \(2\) and the numbers written on the cards from the top will become \([-5]\). In the third turn, end the game with the score of \(2\).
Input: 44-4 1 -3 541 -2 3 -43-1 3 -51-1 | Output: 5 4 2 0
Medium
2
1,138
472
94
18
675
D
675D
D. Tree Construction
1,800
data structures; trees
During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence \(a\), consisting of \(n\) distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. First element \(a_1\) becomes the root of the tree. Elements \(a_2, a_3, \ldots, a_n\) are added one by one. To add element \(a_i\) one needs to traverse the tree starting from the root and using the following rules: The pointer to the current node is set to the root. If \(a_i\) is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. If at some point there is no required child, the new node is created, it is assigned value \(a_i\) and becomes the corresponding child of the current node.
The first line of the input contains a single integer \(n\) (\(2 \leq n \leq 100\,000\)) — the length of the sequence \(a\).The second line contains \(n\) distinct integers \(a_i\) (\(1 \leq a_i \leq 10^9\)) — the sequence \(a\) itself.
Output \(n - 1\) integers. For all \(i > 1\) print the value written in the node that is the parent of the node with value \(a_i\) in it.
Input: 31 2 3 | Output: 1 2
Medium
2
971
236
137
6
981
D
981D
D. Bookshelves
1,900
bitmasks; dp; greedy
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly \(k\) bookshelves. He decided that the beauty of the \(k\) shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on \(k\) shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
The first line contains two integers \(n\) and \(k\) (\(1 \leq k \leq n \leq 50\)) — the number of books and the number of shelves in the new office.The second line contains \(n\) integers \(a_1, a_2, \ldots a_n\), (\(0 < a_i < 2^{50}\)) — the prices of the books in the order they stand on the old shelf.
Print the maximum possible beauty of \(k\) shelves in the new office.
In the first example you can split the books as follows:$$$\((9 + 14 + 28 + 1 + 7) \& (13 + 15) \& (29 + 2) \& (31) = 24.\)\(In the second example you can split the books as follows:\)\((3 + 14 + 15 + 92) \& (65) \& (35 + 89) = 64.\)$$$
Input: 10 49 14 28 1 7 13 15 29 2 31 | Output: 24
Hard
3
877
305
69
9
203
A
203A
A. Two Problems
1,200
brute force; implementation
A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result.He knows that the contest number 300 was unusual because there were only two problems. The contest lasted for t minutes, the minutes are numbered starting from zero. The first problem had the initial cost of a points, and every minute its cost reduced by da points. The second problem had the initial cost of b points, and every minute this cost reduced by db points. Thus, as soon as the zero minute of the contest is over, the first problem will cost a - da points, and the second problem will cost b - db points. It is guaranteed that at any moment of the contest each problem has a non-negative cost.Arkady asks you to find out whether Valera could have got exactly x points for this contest. You should assume that Valera could have solved any number of the offered problems. You should also assume that for each problem Valera made no more than one attempt, besides, he could have submitted both problems at the same minute of the contest, starting with minute 0 and ending with minute number t - 1. Please note that Valera can't submit a solution exactly t minutes after the start of the contest or later.
The single line of the input contains six integers x, t, a, b, da, db (0 ≤ x ≤ 600; 1 ≤ t, a, b, da, db ≤ 300) — Valera's result, the contest's duration, the initial cost of the first problem, the initial cost of the second problem, the number of points that the first and the second problem lose per minute, correspondingly.It is guaranteed that at each minute of the contest each problem has a non-negative cost, that is, a - i·da ≥ 0 and b - i·db ≥ 0 for all 0 ≤ i ≤ t - 1.
If Valera could have earned exactly x points at a contest, print ""YES"", otherwise print ""NO"" (without the quotes).
In the first sample Valera could have acted like this: he could have submitted the first problem at minute 0 and the second problem — at minute 2. Then the first problem brings him 20 points and the second problem brings him 10 points, that in total gives the required 30 points.
Input: 30 5 20 20 3 5 | Output: YES
Easy
2
1,409
476
118
2
1,896
G
1896G
G. Pepe Racing
3,200
constructive algorithms; implementation; interactive; sortings
This is an interactive problem.There are \(n^2\) pepes labeled \(1, 2, \ldots, n^2\) with pairwise distinct speeds. You would like to set up some races to find out the relative speed of these pepes.In one race, you can choose exactly \(n\) distinct pepes and make them race against each other. After each race, you will only know the fastest pepe of these \(n\) pepes.Can you order the \(n^2-n+1\) fastest pepes in at most \(2n^2 - 2n + 1\) races? Note that the slowest \(n - 1\) pepes are indistinguishable from each other.Note that the interactor is adaptive. That is, the relative speeds of the pepes are not fixed in the beginning and may depend on your queries. But it is guaranteed that at any moment there is at least one initial configuration of pepes such that all the answers to the queries are consistent.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.The only line of each test case contains a single integer \(n\) (\(2 \le n \le 20\)) — the number of pepes in one race.After reading the integer \(n\) for each test case, you should begin the interaction.It is guaranteed that the sum of \(n^3\) over all test cases does not exceed \(3 \cdot 10^5\).
Input: 1 2 2 4 4 3 2 | Output: ? 1 2 ? 3 4 ? 2 4 ? 2 3 ? 2 1 ! 4 3 2
Master
4
816
459
0
18
2,107
F1
2107F1
F1. Cycling (Easy Version)
2,300
binary search; brute force; dp; greedy
This is the easy version of the problem. The difference between the versions is that in this version, \(1\le n\le 5\cdot 10^3\) and you don't need to output the answer for each prefix. You can hack only if you solved all versions of this problem.Leo works as a programmer in the city center, and his lover teaches at a high school in the suburbs. Every weekend, Leo would ride his bike to the suburbs to spend a nice weekend with his lover.There are \(n\) cyclists riding in front of Leo on this road right now. They are numbered \(1\), \(2\), \(\ldots\), \(n\) from front to back. Initially, Leo is behind the \(n\)-th cyclist. The \(i\)-th cyclist has an agility value \(a_i\). Leo wants to get ahead of the \(1\)-st cyclist. Leo can take the following actions as many times as he wants: Assuming that the first person in front of Leo is cyclist \(i\), he can go in front of cyclist \(i\) for a cost of \(a_i\). This puts him behind cyclist \(i - 1\). Using his super powers, swap \(a_i\) and \(a_j\) (\(1\le i < j\le n\)) for a cost of \((j - i)\). Leo wants to know the minimum cost to get in front of the \(1\)-st cyclist. Here you only need to print the answer for the whole array, i.e. \([a_1, a_2, \ldots, a_n]\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^3\)). The description of the test cases follows. The first line of each test case contains a positive integer \(n\) (\(1 \leq n \leq 5\cdot 10^3\)), representing the number of the cyclists.The second line of each test case contains \(n\) integers \(a_1, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5\cdot 10^3\).
For each test case, print one integer representing the minimum cost for Leo to go from behind the \(n\)-th cyclist to in front of the \(1\)-st cyclist.
In the first test case, one possible way to move from the position behind the \(n\)-th cyclist to the position in front of the \(1\)-st cyclist is: Leo swaps \(a_2\) \((i=2)\) and \(a_3\) \((j=3)\), then the array becomes \([1,4,2]\); it costs \(j-i=3-2=1\). Leo is behind the \(3\)-rd cyclist and moves behind the \(2\)-nd cyclist; it costs \(a_3=2\). Leo swaps \(a_1\) \((i=1)\) and \(a_2\) \((j=2)\), then the array becomes \([4,1,2]\); it costs \(j-i=2-1=1\). Leo is behind the \(2\)-nd cyclist and moves behind the \(1\)-st cyclist; it costs \(a_2=1\). Leo swaps \(a_1\) \((i=1)\) and \(a_2\) \((j=2)\), then the array becomes \([1,4,2]\); it costs \(j-i=2-1=1\). Leo moves ahead of the \(1\)-st cyclist; it costs \(a_1=1\). So the total cost is \(1+2+1+1+1+1=7\). It can be proved that \(7\) is the minimum cost.In the second test case, to move ahead of the \(1\)-st cyclist from the position behind the \(n\)-th cyclist, Leo should not swap anyone's agility value. The total cost is \(1+1+1+1=4\).
Input: 431 2 441 1 1 121 244 1 3 2 | Output: 7 4 3 8
Expert
4
1,221
499
151
21
177
G2
177G2
G2. Fibonacci Strings
2,600
matrices; strings
Fibonacci strings are defined as follows: f1 = «a» f2 = «b» fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: ""a"", ""b"", ""ba"", ""bab"", ""babba"".You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring.
The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly.Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters ""a"" and ""b"".The input limitations for getting 30 points are: 1 ≤ k ≤ 3000 1 ≤ m ≤ 3000 The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: 1 ≤ k ≤ 1018 1 ≤ m ≤ 104 The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input.
Input: 6 5ababbaaba | Output: 35331
Expert
2
322
689
264
1
743
A
743A
A. Vladik and flights
1,200
constructive algorithms; greedy; implementation
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.Print the minimum cost Vladik has to pay to get to the olympiad.
The first line contains three integers n, a, and b (1 ≤ n ≤ 105, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach. The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.
Print single integer — the minimum cost Vladik has to pay to get to the olympiad.
In the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company.
Input: 4 1 41010 | Output: 1
Easy
3
1,004
425
81
7
204
B
204B
B. Little Elephant and Cards
1,500
binary search; data structures
The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card.The numbers in the lines are separated by single spaces.
On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.
Input: 34 74 77 4 | Output: 0
Medium
2
570
499
130
2
1,898
A
1898A
A. Milica and String
800
brute force; implementation; strings
Milica has a string \(s\) of length \(n\), consisting only of characters A and B. She wants to modify \(s\) so it contains exactly \(k\) instances of B. In one operation, she can do the following: Select an integer \(i\) (\(1 \leq i \leq n\)) and a character \(c\) (\(c\) is equal to either A or B). Then, replace each of the first \(i\) characters of string \(s\) (that is, characters \(s_1, s_2, \ldots, s_i\)) with \(c\). Milica does not want to perform too many operations in order not to waste too much time on them.She asks you to find the minimum number of operations required to modify \(s\) so it contains exactly \(k\) instances of B. She also wants you to find these operations (that is, integer \(i\) and character \(c\) selected in each operation).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \leq t \leq 500\)). The description of test cases follows.The first line of each test case contains two integers \(n\) and \(k\) (\(3 \leq n \leq 100\), \(0 \leq k \leq n\)) — the length of the string \(s\) and the number of characters B Milica wants to appear in \(s\) in the end.The second line of each test case contains the string \(s\) of length \(n\), consisting only of characters A and B.
For each test case, in the first line output a single integer \(m\) — the minimum number of operations Milica should perform.In the \(j\)-th of the next \(m\) lines output an integer \(i\) (\(1 \le i \le n\)) and a character \(c\) (\(c\) is 'A' or 'B') — the parameters of the \(j\)-th operation as described in the statement.If there are multiple solutions with the minimum possible number of operations, output any of them.
In the first test case, there are already \(2\) characters B in \(s\), so Milica does not have to perform any operations.In the second test case, the only way to achieve \(3\) characters B in \(s\) in one operation is to replace the first character of \(s\) by B on the first operation: AABAB \(\rightarrow\) BABAB.In the third test case, the only way to achieve \(0\) characters B in \(s\) in one operation is to replace the first \(5\) characters of \(s\) by A on the first operation: BBBBB \(\rightarrow\) AAAAA.In the fourth test case, one of the ways to achieve \(0\) characters B in \(s\) in one operation is to replace the first \(2\) characters of \(s\) by A on the first operation: BAA \(\rightarrow\) AAA. Note that ""1 A"" and ""3 A"" are also correct one-operation solutions.
Input: 5 5 2 AAABB 5 3 AABAB 5 0 BBBBB 3 0 BAA 10 3 BBBABBBBAB | Output: 0 1 1 B 1 5 A 1 2 A 1 6 A
Beginner
3
761
496
425
18
2,081
C
2081C
C. Quaternary Matrix
2,700
bitmasks; constructive algorithms; greedy; implementation; matrices
A matrix is called quaternary if all its elements are \(0\), \(1\), \(2\), or \(3\).Ecrade calls a quaternary matrix \(A\) good if the following two properties hold. The bitwise XOR of all numbers in each row of matrix \(A\) is equal to \(0\). The bitwise XOR of all numbers in each column of matrix \(A\) is equal to \(0\). Ecrade has a quaternary matrix of size \(n \times m\). He is interested in the minimum number of elements that need to be changed for the matrix to become good, and he also wants to find one of the possible resulting matrices.However, it seems a little difficult, so please help him!
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 2 \cdot 10^5\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n, m \le 10^3\)).This is followed by \(n\) lines, each containing exactly \(m\) characters and consisting only of \(0\), \(1\), \(2\), and \(3\), describing the elements of Ecrade's matrix.It is guaranteed that the sum of \(n\cdot m\) over all test cases does not exceed \(10^6\).
For each test case, print the minimum number of elements that need to be changed for the matrix to become good on the first line, then print \(n\) lines, each containing exactly \(m\) characters and consisting only of \(0\), \(1\), \(2\), and \(3\), describing one of the possible resulting matrices.If there are multiple possible resulting matrices, output any of them.
Input: 53 33131213133 30000000004 401231230230130124 412322110312213114 41232211031221312 | Output: 3 213 101 312 0 000 000 000 0 0123 1230 2301 3012 6 0132 2310 3131 1313 5 0132 2310 3120 1302
Master
5
608
530
370
20
1,103
E
1103E
E. Radix sum
3,400
fft; math; number theory
Let's define radix sum of number \(a\) consisting of digits \(a_1, \ldots ,a_k\) and number \(b\) consisting of digits \(b_1, \ldots ,b_k\)(we add leading zeroes to the shorter number to match longer length) as number \(s(a,b)\) consisting of digits \((a_1+b_1)\mod 10, \ldots ,(a_k+b_k)\mod 10\). The radix sum of several integers is defined as follows: \(s(t_1, \ldots ,t_n)=s(t_1,s(t_2, \ldots ,t_n))\)You are given an array \(x_1, \ldots ,x_n\). The task is to compute for each integer \(i (0 \le i < n)\) number of ways to consequently choose one of the integers from the array \(n\) times, so that the radix sum of these integers is equal to \(i\). Calculate these values modulo \(2^{58}\).
The first line contains integer \(n\) — the length of the array(\(1 \leq n \leq 100000\)).The second line contains \(n\) integers \(x_1, \ldots x_n\) — array elements(\(0 \leq x_i < 100000\)).
Output \(n\) integers \(y_0, \ldots, y_{n-1}\) — \(y_i\) should be equal to corresponding number of ways modulo \(2^{58}\).
In the first example there exist sequences: sequence \((5,5)\) with radix sum \(0\), sequence \((5,6)\) with radix sum \(1\), sequence \((6,5)\) with radix sum \(1\), sequence \((6,6)\) with radix sum \(2\).
Input: 2 5 6 | Output: 1 2
Master
3
696
192
123
11
892
B
892B
B. Wrath
1,200
greedy; implementation; two pointers
Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people.Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.
Print one integer — the total number of alive people after the bell rings.
In first sample the last person kills everyone in front of him.
Input: 40 1 0 10 | Output: 1
Easy
3
414
211
74
8
150
C
150C
C. Smart Cheater
2,200
data structures; math; probabilities
I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus 62 has exactly n stops (stop 1 goes first on its way and stop n goes last). The stops are positioned on a straight line and their coordinates are 0 = x1 < x2 < ... < xn. Each day exactly m people use bus 62. For each person we know the number of the stop where he gets on the bus and the number of the stop where he gets off the bus. A ticket from stop a to stop b (a < b) costs xb - xa rubles. However, the conductor can choose no more than one segment NOT TO SELL a ticket for. We mean that conductor should choose C and D (С <= D) and sell a ticket for the segments [A, C] and [D, B], or not sell the ticket at all. The conductor and the passenger divide the saved money between themselves equally. The conductor's ""untaxed income"" is sometimes interrupted by inspections that take place as the bus drives on some segment of the route located between two consecutive stops. The inspector fines the conductor by c rubles for each passenger who doesn't have the ticket for this route's segment.You know the coordinated of all stops xi; the numbers of stops where the i-th passenger gets on and off, ai and bi (ai < bi); the fine c; and also pi — the probability of inspection on segment between the i-th and the i + 1-th stop. The conductor asked you to help him make a plan of selling tickets that maximizes the mathematical expectation of his profit.
The first line contains three integers n, m and c (2 ≤ n ≤ 150 000, 1 ≤ m ≤ 300 000, 1 ≤ c ≤ 10 000).The next line contains n integers xi (0 ≤ xi ≤ 109, x1 = 0, xi < xi + 1) — the coordinates of the stops on the bus's route.The third line contains n - 1 integer pi (0 ≤ pi ≤ 100) — the probability of inspection in percents on the segment between stop i and stop i + 1.Then follow m lines that describe the bus's passengers. Each line contains exactly two integers ai and bi (1 ≤ ai < bi ≤ n) — the numbers of stops where the i-th passenger gets on and off.
Print the single real number — the maximum expectation of the conductor's profit. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
A comment to the first sample:The first and third passengers get tickets from stop 1 to stop 2. The second passenger doesn't get a ticket. There always is inspection on the segment 1-2 but both passengers have the ticket for it. There never is an inspection on the segment 2-3, that's why the second passenger gets away with the cheating. Our total profit is (0 + 90 / 2 + 90 / 2) = 90.
Input: 3 3 100 10 100100 01 22 31 3 | Output: 90.000000000
Hard
3
1,528
557
315
1
1,923
E
1923E
E. Count Paths
2,000
data structures; dfs and similar; dp; dsu; graphs; trees
You are given a tree, consisting of \(n\) vertices, numbered from \(1\) to \(n\). Every vertex is colored in some color, denoted by an integer from \(1\) to \(n\).A simple path of the tree is called beautiful if: it consists of at least \(2\) vertices; the first and the last vertices of the path have the same color; no other vertex on the path has the same color as the first vertex. Count the number of the beautiful simple paths of the tree. Note that paths are considered undirected (i. e. the path from \(x\) to \(y\) is the same as the path from \(y\) to \(x\)).
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of testcases.The first line of each testcase contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) — the number of vertices in the tree.The second line contains \(n\) integers \(c_1, c_2, \dots, c_n\) (\(1 \le c_i \le n\)) — the color of each vertex.The \(i\)-th of the next \(n - 1\) lines contains two integers \(v_i\) and \(u_i\) (\(1 \le v_i, u_i \le n\); \(v_i \neq u_i\)) — the \(i\)-th edge of the tree.The given edges form a valid tree. The sum of \(n\) over all testcases doesn't exceed \(2 \cdot 10^5\).
For each testcase, print a single integer — the number of the beautiful simple paths of the tree.
Input: 431 2 11 22 352 1 2 1 21 21 33 44 551 2 3 4 51 21 33 44 542 2 2 23 13 23 4 | Output: 1 3 0 3
Hard
6
569
605
97
19
721
D
721D
D. Maxim and Array
2,000
constructive algorithms; data structures; greedy; math
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. ) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.The second line contains n integers a1, a2, ..., an () — the elements of the array found by Maxim.
Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible.If there are multiple answers, print any of them.
Input: 5 3 15 4 3 5 2 | Output: 5 4 3 5 -1
Hard
4
660
314
293
7
1,929
C
1929C
C. Sasha and the Casino
1,400
binary search; brute force; constructive algorithms; games; greedy; math
Sasha decided to give his girlfriend the best handbag, but unfortunately for Sasha, it is very expensive. Therefore, Sasha wants to earn it. After looking at earning tips on the internet, he decided to go to the casino.Sasha knows that the casino operates under the following rules. If Sasha places a bet of \(y\) coins (where \(y\) is a positive integer), then in case of winning, he will receive \(y \cdot k\) coins (i.e., his number of coins will increase by \(y \cdot (k - 1)\)). And in case of losing, he will lose the entire bet amount (i.e., his number of coins will decrease by \(y\)).Note that the bet amount must always be a positive (\(> 0\)) integer and cannot exceed Sasha's current number of coins.Sasha also knows that there is a promotion at the casino: he cannot lose more than \(x\) times in a row.Initially, Sasha has \(a\) coins. He wonders whether he can place bets such that he is guaranteed to win any number of coins. In other words, is it true that for any integer \(n\), Sasha can make bets so that for any outcome that does not contradict the rules described above, at some moment of time he will have at least \(n\) coins.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) — the number of test cases. The description of the test cases follows.The single line of each test case contains three integers \(k, x\) and \(a\) (\(2 \leq k \leq 30\), \(1 \leq x \leq 100\), \(1 \leq a \leq 10^9\)) — the number of times the bet is increased in case of a win, the maximum number of consecutive losses, and the initial number of coins Sasha has.
For each test case, output ""YES"" (without quotes) if Sasha can achieve it and ""NO"" (without quotes) otherwise.You can output ""YES"" and ""NO"" in any case (for example, the strings ""yEs"", ""yes"" and ""Yes"" will be recognized as a positive answer).
In the first test case, Sasha can proceed as follows: If Sasha places a bet for the first time or if he won the previous bet, then he places \(1\) coin. If Sasha lost the previous bet, then he places \(2\) coins.Note that Sasha cannot lose more than once in a row.It can be proven that with this strategy, Sasha can obtain as many coins as he wants.In the second test case, Sasha can only place \(1\) coin for the first time. But in case of a loss, he will not be able to place any more bets, so he will not be able to guarantee having as many coins as he wants.
Input: 92 1 72 1 12 3 153 3 64 4 55 4 74 88 100000000025 69 23113 97 18806 | Output: YES NO YES NO NO YES NO NO NO
Easy
6
1,150
475
256
19
1,822
G2
1822G2
G2. Magic Triples (Hard Version)
2,200
brute force; data structures; math; number theory
This is the hard version of the problem. The only difference is that in this version, \(a_i \le 10^9\).For a given sequence of \(n\) integers \(a\), a triple \((i, j, k)\) is called magic if: \(1 \le i, j, k \le n\). \(i\), \(j\), \(k\) are pairwise distinct. there exists a positive integer \(b\) such that \(a_i \cdot b = a_j\) and \(a_j \cdot b = a_k\). Kolya received a sequence of integers \(a\) as a gift and now wants to count the number of magic triples for it. Help him with this task!Note that there are no constraints on the order of integers \(i\), \(j\) and \(k\).
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of the test cases follows.The first line of the test case contains a single integer \(n\) (\(3 \le n \le 2 \cdot 10^5\)) — the length of the sequence.The second line of the test contains \(n\) integers \(a_1, a_2, a_3, \dots, a_n\) (\(1 \le a_i \le 10^9\)) — the elements of the sequence \(a\).The sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single integer — the number of magic triples for the sequence \(a\).
In the first example, there are \(6\) magic triples for the sequence \(a\) — \((2, 3, 5)\), \((2, 5, 3)\), \((3, 2, 5)\), \((3, 5, 2)\), \((5, 2, 3)\), \((5, 3, 2)\).In the second example, there is a single magic triple for the sequence \(a\) — \((2, 1, 3)\).
Input: 751 7 7 2 736 2 1891 2 3 4 5 6 7 8 941000 993 986 17971 10 100 1000 10000 100000 100000081 1 2 2 4 4 8 891 1 1 2 2 2 4 4 4 | Output: 6 1 3 0 9 16 45
Hard
4
577
478
97
18
1,810
A
1810A
A. Beautiful Sequence
800
brute force; greedy
A sequence of \(m\) integers \(a_{1}, a_{2}, \ldots, a_{m}\) is good, if and only if there exists at least one \(i\) (\(1 \le i \le m\)) such that \(a_{i} = i\). For example, \([3,2,3]\) is a good sequence, since \(a_{2} = 2\), \(a_{3} = 3\), while \([3,1,1]\) is not a good sequence, since there is no \(i\) such that \(a_{i} = i\).A sequence \(a\) is beautiful, if and only if there exists at least one subsequence of \(a\) satisfying that this subsequence is good. For example, \([4,3,2]\) is a beautiful sequence, since its subsequence \([4,2]\) is good, while \([5,3,4]\) is not a beautiful sequence.A sequence \(b\) is a subsequence of a sequence \(a\) if \(b\) can be obtained from \(a\) by the deletion of several (possibly, zero or all) elements. Now you are given a sequence, check whether it is beautiful or not.
Each test contains multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 500\)) — the number of test cases. Their description follows.The first line of each test case contains an integer \(n\) (\(1 \le n \le 100\)) — the length of the given sequence.The second line of each test case contains \(n\) integers \(a_{1}, a_{2}, \ldots, a_{n}\) (\(1 \le a_{i} \le 10^9\)), representing the sequence.
For each test case, output ""YES"" or ""NO""(without quotes) in one line, representing whether the given sequence is beautiful.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In the first test case, the good subsequence is \(b=[3,2]\), where \(b_{2} = 2\).In the second test case, the good subsequence is \(b=[2,4,3]\), where \(b_{3} = 3\).In the fourth test case, the good subsequence is \(b=[1]\), where \(b_{1} = 1\).In the fifth test case, the good subsequence is \(b=[2,2]\), where \(b_{2} = 2\).
Input: 733 2 142 4 3 552 3 5 5 623 152 4 5 2 345 6 7 866 5 4 3 2 1 | Output: YES YES NO YES YES NO YES
Beginner
2
823
423
288
18
459
D
459D
D. Pashmak and Parmida's problem
1,800
data structures; divide and conquer; sortings
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, ai) > f(j, n, aj).Help Pashmak with the test.
The first line of the input contains an integer n (1 ≤ n ≤ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Print a single integer — the answer to the problem.
Input: 71 2 1 1 2 2 1 | Output: 8
Medium
3
497
148
51
4
1,625
A
1625A
A. Ancient Civilization
800
bitmasks; greedy; math
Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly \(\ell\) letters long. So, the scientists decided to write each word of this language as an integer from \(0\) to \(2^{\ell} - 1\) inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between \(1001_2\) and \(1100_2\) (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words \(x\) and \(y\) as \(d(x, y)\).Let the word have \(n\) forms, the \(i\)-th of which is described with an integer \(x_i\). All the \(x_i\) are not necessarily different, as two various forms of the word can be written the same. Consider some word \(y\). Then, closeness of the word \(y\) is equal to the sum of distances to each of the word forms, i. e. the sum \(d(x_i, y)\) over all \(1 \le i \le n\).The initial form is the word \(y\) with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the \(n\) given forms.
The first line contains an integer \(t\) (\(1 \le t \le 100\)) — the number of test cases. The following are descriptions of the test cases.The first line contains two integers \(n\) and \(\ell\) (\(1 \le n \le 100\), \(1 \le \ell \le 30\)) — the amount of word forms, and the number of letters in one word.The second line contains \(n\) integers \(x_i\) (\(0 \le x_i \le 2^\ell - 1\)) — word forms. The integers are not necessarily different.
For each test, print a single integer, the initial form of the word, i. e. such \(y\) (\(0 \le y \le 2^\ell - 1\)) that the sum \(d(x_i, y)\) over all \(1 \le i \le n\) is minimal possible. Note that \(y\) can differ from all the integers \(x_i\).If there are multiple ways to restore the initial form, print any.
In the first test case, the words can be written as \(x_1 = 10010_2\), \(x_2 = 01001_2\) and \(x_3 = 10101_2\) in binary. Let \(y = 10001_2\). Then, \(d(x_1, y) = 2\) (the difference is in the fourth and the fifth positions), \(d(x_2, y) = 2\) (the difference is in the first and the second positions), \(d(x_3, y) = 1\) (the difference is in the third position). So, the closeness is \(2 + 2 + 1 = 5\). It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to \(18\) (\(10010_2\) in binary), so the initial form is also \(18\). It's easy to see that closeness is equal to zero in this case.
Input: 73 518 9 213 518 18 181 115 301 2 3 4 56 1099 35 85 46 78 552 10 18 85 16 42 15 83 65 78 42 | Output: 17 18 1 1 39 0 2
Beginner
3
1,752
443
313
16
388
D
388D
D. Fox and Perfect Sets
2,700
math
Fox Ciel studies number theory.She thinks a non-empty set S contains non-negative integers is perfect if and only if for any (a can be equal to b), . Where operation xor means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or).Please calculate the number of perfect sets consisting of integers not greater than k. The answer can be very large, so print it modulo 1000000007 (109 + 7).
The first line contains an integer k (0 ≤ k ≤ 109).
Print a single integer — the number of required sets modulo 1000000007 (109 + 7).
In example 1, there are 2 such sets: {0} and {0, 1}. Note that {1} is not a perfect set since 1 xor 1 = 0 and {1} doesn't contain zero.In example 4, there are 6 such sets: {0}, {0, 1}, {0, 2}, {0, 3}, {0, 4} and {0, 1, 2, 3}.
Input: 1 | Output: 2
Master
1
400
51
81
3
232
C
232C
C. Doe Graphs
2,600
constructive algorithms; divide and conquer; dp; graphs; shortest paths
John Doe decided that some mathematical object must be named after him. So he invented the Doe graphs. The Doe graphs are a family of undirected graphs, each of them is characterized by a single non-negative number — its order. We'll denote a graph of order k as D(k), and we'll denote the number of vertices in the graph D(k) as |D(k)|. Then let's define the Doe graphs as follows: D(0) consists of a single vertex, that has number 1. D(1) consists of two vertices with numbers 1 and 2, connected by an edge. D(n) for n ≥ 2 is obtained from graphs D(n - 1) and D(n - 2). D(n - 1) and D(n - 2) are joined in one graph, at that numbers of all vertices of graph D(n - 2) increase by |D(n - 1)| (for example, vertex number 1 of graph D(n - 2) becomes vertex number 1 + |D(n - 1)|). After that two edges are added to the graph: the first one goes between vertices with numbers |D(n - 1)| and |D(n - 1)| + 1, the second one goes between vertices with numbers |D(n - 1)| + 1 and 1. Note that the definition of graph D(n) implies, that D(n) is a connected graph, its vertices are numbered from 1 to |D(n)|. The picture shows the Doe graphs of order 1, 2, 3 and 4, from left to right. John thinks that Doe graphs are that great because for them exists a polynomial algorithm for the search of Hamiltonian path. However, your task is to answer queries of finding the shortest-length path between the vertices ai and bi in the graph D(n).A path between a pair of vertices u and v in the graph is a sequence of vertices x1, x2, ..., xk (k > 1) such, that x1 = u, xk = v, and for any i (i < k) vertices xi and xi + 1 are connected by a graph edge. The length of path x1, x2, ..., xk is number (k - 1).
The first line contains two integers t and n (1 ≤ t ≤ 105; 1 ≤ n ≤ 103) — the number of queries and the order of the given graph. The i-th of the next t lines contains two integers ai and bi (1 ≤ ai, bi ≤ 1016, ai ≠ bi) — numbers of two vertices in the i-th query. It is guaranteed that ai, bi ≤ |D(n)|.Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
For each query print a single integer on a single line — the length of the shortest path between vertices ai and bi. Print the answers to the queries in the order, in which the queries are given in the input.
Input: 10 51 21 31 41 52 32 42 53 43 54 5 | Output: 1112123121
Expert
5
1,689
446
208
2
732
A
732A
A. Buy a Shovel
800
brute force; constructive algorithms; implementation; math
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.In his pocket Polycarp has an unlimited number of ""10-burle coins"" and exactly one coin of r burles (1 ≤ r ≤ 9).What is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of r burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.
The single line of input contains two integers k and r (1 ≤ k ≤ 1000, 1 ≤ r ≤ 9) — the price of one shovel and the denomination of the coin in Polycarp's pocket that is different from ""10-burle coins"". Remember that he has an unlimited number of coins in the denomination of 10, that is, Polycarp has enough money to buy any number of shovels.
Print the required minimum number of shovels Polycarp has to buy so that he can pay for them without any change.
In the first example Polycarp can buy 9 shovels and pay 9·117 = 1053 burles. Indeed, he can pay this sum by using 10-burle coins and one 3-burle coin. He can't buy fewer shovels without any change.In the second example it is enough for Polycarp to buy one shovel.In the third example Polycarp should buy two shovels and pay 2·15 = 30 burles. It is obvious that he can pay this sum without any change.
Input: 117 3 | Output: 9
Beginner
4
703
345
112
7
1,644
A
1644A
A. Doors and Keys
800
implementation
The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters: R, G, B — denoting red, green and blue doors, respectively; r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway.
The first line contains a single integer \(t\) (\(1 \le t \le 720\)) — the number of testcases.Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once.
For each testcase, print YES if the knight can open all doors. Otherwise, print NO.
In the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door.
Input: 4rgbBRGRgbrBGbBrRgGrgRGBb | Output: YES NO YES NO
Beginner
1
1,051
250
83
16
1,499
B
1499B
B. Binary Removals
1,000
brute force; dp; greedy; implementation
You are given a string \(s\), consisting only of characters '0' or '1'. Let \(|s|\) be the length of \(s\).You are asked to choose some integer \(k\) (\(k > 0\)) and find a sequence \(a\) of length \(k\) such that: \(1 \le a_1 < a_2 < \dots < a_k \le |s|\); \(a_{i-1} + 1 < a_i\) for all \(i\) from \(2\) to \(k\). The characters at positions \(a_1, a_2, \dots, a_k\) are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence \(a\) should not be adjacent.Let the resulting string be \(s'\). \(s'\) is called sorted if for all \(i\) from \(2\) to \(|s'|\) \(s'_{i-1} \le s'_i\).Does there exist such a sequence \(a\) that the resulting string \(s'\) is sorted?
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) — the number of testcases.Then the descriptions of \(t\) testcases follow.The only line of each testcase contains a string \(s\) (\(2 \le |s| \le 100\)). Each character is either '0' or '1'.
For each testcase print ""YES"" if there exists a sequence \(a\) such that removing the characters at positions \(a_1, a_2, \dots, a_k\) and concatenating the parts without changing the order produces a sorted string.Otherwise, print ""NO"".You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
In the first testcase you can choose a sequence \(a=[1,3,6,9]\). Removing the underlined letters from ""10101011011"" will produce a string ""0011111"", which is sorted.In the second and the third testcases the sequences are already sorted.In the fourth testcase you can choose a sequence \(a=[3]\). \(s'=\) ""11"", which is sorted.In the fifth testcase there is no way to choose a sequence \(a\) such that \(s'\) is sorted.
Input: 5 10101011011 0000 11111 110 1100 | Output: YES YES YES YES NO
Beginner
4
734
260
380
14
1,859
D
1859D
D. Andrey and Escape from Capygrad
1,800
binary search; data structures; dp; dsu; greedy; sortings
An incident occurred in Capygrad, the capital of Tyagoland, where all the capybaras in the city went crazy and started throwing mandarins. Andrey was forced to escape from the city as far as possible, using portals.Tyagoland is represented by a number line, and the city of Capygrad is located at point \(0\). There are \(n\) portals all over Tyagoland, each of which is characterised by four integers \(l_i\), \(r_i\), \(a_i\) and \(b_i\) (\(1 \le l_i \le a_i \le b_i \le r_i \le 10^9\)). Note that the segment \([a_i, b_i]\) is contained in the segment \([l_i, r_i]\).If Andrey is on the segment \([l_i, r_i]\), then the portal can teleport him to any point on the segment \([a_i, b_i]\). Andrey has a pass that allows him to use the portals an unlimited number of times.Andrey thinks that the point \(x\) is on the segment \([l, r]\) if the inequality \(l \le x \le r\) is satisfied.Andrey has \(q\) options for where to start his escape, each option is characterized by a single integer \(x_i\) — the starting position of the escape. He wants to escape from Capygrad as far as possible (to the point with the maximum possible coordinate). Help Andrey determine how far he could escape from Capygrad, starting at each of the \(q\) positions.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of sets of test cases. The description of test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) — the number of portals.Each of the next \(n\) lines contains four integers \(l_i\), \(r_i\), \(a_i\), and \(b_i\) \((1 \le l_i \le a_i \le b_i \le r_i \le 10^9)\) — the characteristics of the portals.The next line contains a single integer \(q\) (\(1 \le q \le 2 \cdot 10^5\)) — the number of positions.The following line contains \(q\) integers \(x_1, x_2, \ldots, x_q\) (\(1 \le x_i \le 10^9\)) — the position from which Andrey will start his escape in the \(i\)-th options.It is guaranteed that the sum of \(n\) and the sum of \(q\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output a single line of \(q\) integers, containing the answers to Andrey's questions.
In the first test case: Optimal actions when starting from each position: Use portal \(1\) and teleport to point \(b_1 = 14\). Use portal \(2\) first and teleport to point \(6\), which is on the segment \([l_1, r_1] = [6, 17]\), then use portal \(1\) and teleport to point \(b_1 = 14\). Stay at point \(x_3=23\) without using any portals. Stay at point \(x_4=15\) without using any portals. Point \(x_5=28\) is not on any segment, so Andrey won't be able to teleport anywhere. Point \(x_6=18\) is only on the segment \([l_3, r_3] = [16, 24]\), use portal \(3\) and teleport to point \(b_3 = 22\). In the fifth test case: Optimal actions when starting from each position: Use portal \(1\) first and teleport to point \(15\) on the segment \([a_1, b_1] = [14, 20]\), then use portal \(2\) and teleport to point \(21\), which is on the segment \([l_4, r_4] = [21, 33]\) and on the segment \([a_2, b_2] = [13, 24]\), then teleport to point \(b_4 = 32\). Use portal \(6\) first and teleport to point \(20\) on the segment \([a_6, b_6] = [20, 21]\), then use portal \(2\) and teleport to point \(22\), which is simultaneously on the segment \([l_4, r_4] = [21, 33]\) and on the segment \([a_2, b_2] = [13, 24]\), then teleport to point \(b_4 = 32\). Perform the same actions as from the first position. Stay at point \(x_4=5\) without using any portals. Point \(8\) is not on any segment, so Andrey won't be able to teleport anywhere. Stay at point \(x_6=33\) without using any portals. Use portal \(5\) and teleport to point \(b_5 = 4\). Perform the same actions as from the first position.
Input: 536 17 7 141 12 3 816 24 20 22610 2 23 15 28 1833 14 7 1016 24 20 221 16 3 1492 4 6 8 18 23 11 13 1521 4 2 33 9 6 734 8 1518 24 18 241 8 2 411 16 14 1426 32 28 305 10 6 8915 14 13 27 22 17 31 1 769 22 14 2011 26 13 2421 33 22 2321 33 25 321 6 3 418 29 20 21811 23 16 5 8 33 2 21 | Output: 14 14 23 15 28 22 14 14 14 14 22 23 14 14 15 7 8 7 15 14 14 30 24 17 31 4 8 32 32 32 5 8 33 4 32
Medium
6
1,244
873
105
18
700
D
700D
D. Huffman Coding on Segment
3,100
data structures; greedy
Alice wants to send an important message to Bob. Message a = (a1, ..., an) is a sequence of positive integers (characters).To compress the message Alice wants to use binary Huffman coding. We recall that binary Huffman code, or binary prefix code is a function f, that maps each letter that appears in the string to some binary string (that is, string consisting of characters '0' and '1' only) such that for each pair of different characters ai and aj string f(ai) is not a prefix of f(aj) (and vice versa). The result of the encoding of the message a1, a2, ..., an is the concatenation of the encoding of each character, that is the string f(a1)f(a2)... f(an). Huffman codes are very useful, as the compressed message can be easily and uniquely decompressed, if the function f is given. Code is usually chosen in order to minimize the total length of the compressed message, i.e. the length of the string f(a1)f(a2)... f(an).Because of security issues Alice doesn't want to send the whole message. Instead, she picks some substrings of the message and wants to send them separately. For each of the given substrings ali... ari she wants to know the minimum possible length of the Huffman coding. Help her solve this problem.
The first line of the input contains the single integer n (1 ≤ n ≤ 100 000) — the length of the initial message. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000) — characters of the message.Next line contains the single integer q (1 ≤ q ≤ 100 000) — the number of queries.Then follow q lines with queries descriptions. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the position of the left and right ends of the i-th substring respectively. Positions are numbered from 1. Substrings may overlap in any way. The same substring may appear in the input more than once.
Print q lines. Each line should contain a single integer — the minimum possible length of the Huffman encoding of the substring ali... ari.
In the first query, one of the optimal ways to encode the substring is to map 1 to ""0"", 2 to ""10"" and 3 to ""11"".Note that it is correct to map the letter to the empty substring (as in the fifth query from the sample).
Input: 71 2 1 3 1 2 151 71 33 52 44 4 | Output: 103350
Master
2
1,226
617
139
7
629
D
629D
D. Babaei and Birthday Cake
2,000
data structures; dp
As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special cake placing some cylinders on each other.However, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number i can be placed only on the table or on some cake number j where j < i. Moreover, in order to impress friends Babaei will put the cake i on top of the cake j only if the volume of the cake i is strictly greater than the volume of the cake j.Babaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of simple cakes Babaei has.Each of the following n lines contains two integers ri and hi (1 ≤ ri, hi ≤ 10 000), giving the radius and height of the i-th cake.
Print the maximum volume of the cake that Babaei can make. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
In first sample, the optimal way is to choose the cake number 1.In second sample, the way to get the maximum volume is to use cakes with indices 1, 2 and 4.
Input: 2100 3040 10 | Output: 942477.796077000
Hard
2
822
245
291
6
644
B
644B
B. Processing Queries
1,700
*special; constructive algorithms; data structures; two pointers
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.When a query appears server may react in three possible ways: If server is free and query queue is empty, then server immediately starts to process this query. If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue. If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.
The first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue.Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1 ≤ ti, di ≤ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.
Print the sequence of n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or - 1 if the corresponding query will be rejected.
Consider the first sample. The server will start to process first query at the moment 2 and will finish to process it at the moment 11. At the moment 4 second query appears and proceeds to the queue. At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected. At the moment 11 server will finish to process first query and will take the second query from the queue. At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue. At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there. Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue. Server finishes to process query number 5 at the moment 22.
Input: 5 12 94 810 915 219 1 | Output: 11 19 -1 21 22
Medium
4
1,068
450
234
6
1,995
B1
1995B1
B1. Bouquet (Easy Version)
1,100
binary search; brute force; greedy; sortings; two pointers
This is the easy version of the problem. The only difference is that in this version, the flowers are specified by enumeration.A girl is preparing for her birthday and wants to buy the most beautiful bouquet. There are a total of \(n\) flowers in the store, each of which is characterized by the number of petals, and a flower with \(k\) petals costs \(k\) coins. The girl has decided that the difference in the number of petals between any two flowers she will use in her bouquet should not exceed one. At the same time, the girl wants to assemble a bouquet with the maximum possible number of petals. Unfortunately, she only has \(m\) coins, and she cannot spend more. What is the maximum total number of petals she can assemble in the bouquet?
Each test consists of several test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10\,000\)) — the number of test cases. This is followed by descriptions of the test cases.The first line of each test case contains two integers \(n\), \(m\) (\(1 \le n \le 2 \cdot 10^5, 1 \le m \le 10^{18}\)) — the number of flowers in the store and the number of coins the girl possesses, respectively. The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)), where \(a_i\) is the number of petals of the \(i\)-th flower in the store.The sum of \(n\) over all test cases does not exceed \(2 \cdot {10}^5\).
For each test case, output a single integer — the maximum possible number of petals in the bouquet that the girl can assemble while meeting all the conditions listed above.
In the first test case, you can assemble a bouquet with \((1, 1, 2, 2), (2, 2, 3), (1, 1), (2, 2)\). The maximum over all valid bouquets not greater than \(10\) is \(7\) for \((2, 2, 3)\). In the third test case, you can assemble a bouquet with only one flower of any type, so the answer is \(610\). In the fourth test case, you can assemble a bouquet with \((4, 4, 5)\), which gives you \(13\) petals, and it is the maximum amount of petals that the girl can buy.
Input: 55 101 1 2 2 38 204 2 7 5 6 1 1 18 100000239 30 610 122 24 40 8 211 132 4 11 1 1 2 3 5 4 3 28 1033206 206 206 207 207 207 207 1000 | Output: 7 13 610 13 1033
Easy
5
746
665
172
19
1,753
D
1753D
D. The Beach
2,400
constructive algorithms; dfs and similar; graphs; shortest paths
Andrew loves the sea. That's why, at the height of the summer season, he decided to go to the beach, taking a sunbed with him to sunbathe.The beach is a rectangular field with \(n\) rows and \(m\) columns. Some cells of the beach are free, some have roads, stones, shops and other non-movable objects. Some of two adjacent along the side cells can have sunbeds located either horizontally or vertically.Andrew hopes to put his sunbed somewhere, but that's a bad luck, there may no longer be free places for him! That's why Andrew asked you to help him to find a free place for his sunbed. Andrew's sunbed also should be places on two adjacent cells. If there are no two adjacent free cells, then in order to free some place for a sunbed, you will have to disturb other tourists. You can do the following actions: Come to some sunbed and, after causing \(p\) units of discomfort to its owner, lift the sunbed by one of its sides and rotate it by \(90\) degrees. One half of the sunbed must remain in the same cell and another half of the sunbed must move to the free cell. At the same time, anything could be on the way of a sunbed during the rotation . Rotation of the sunbed by \(90\) degrees around cell \((1, 2)\). Come to some sunbed and, after causing \(q\) units of discomfort to its owner, shift the sunbed along its long side by one cell. One half of the sunbed must move to the place of another, and another — to the free cell. Shift of the sunbed by one cell to the right. In any moment each sunbed occupies two adjacent free cells. You cannot move more than one sunbed at a time.Help Andrew to free a space for his sunbed, causing the minimum possible number of units of discomfort to other tourists, or detect that it is impossible.
The first line contains two integers \(n\) and \(m\) (\(1 \le n, m \le 300\,000\), \(1 \le n \cdot m \le 300\,000\)) — the number of rows and columns in rectangle.The second line contains two integers \(p\) and \(q\) (\(1 \le p, q \le 10^9\)) — the number of units of discomfort caused by rotation and shift of a sunbed, respectively.Each of the following \(n\) lines contains \(m\) characters, describing cells of the rectangle. Each lines consists of characters ""L"", ""R"", ""D"", ""U"", ""."" and ""#"", denoting the type of the cell. Characters ""L"", ""R"", ""D"" and ""U"" denote a half of a sunbed placed in the cell — left, right, bottom and top half, respectively. Character ""."" denotes a free cell and character ""#"" — a cell, occupied by some non-movable object.
Print one integer — the minimum possible number of units of discomfort, caused to other tourists, to free a space for a sunbed. If it is impossible to free a space for a sunbed, print \(-1\).
In the first example we can shift upper sunbed to the left and lower sunbed — to the right. Andrew will be able to put his sunbed vertically in the middle of the beach. We well cause \(2 + 2 = 4\) units of discomfort. It is easy to prove that it is an optimal answer. Optimal strategy in the first example (Andrew's sunbed is colored white). In the second example it is impossible to free a space for Andrew's sunbed. All possible states of the beach after any rotates and shifts are illustrated in the problem statement.
Input: 2 55 2.LR####LR. | Output: 4
Expert
4
1,744
778
191
17
306
B
306B
B. Optimizer
2,100
data structures; greedy; sortings
A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as ""memset"", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like ""set13 a_i l_i"". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13.In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program.
The first line contains integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 2·105) — the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≤ ai ≤ n, 1 ≤ li ≤ n - ai + 1).
Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them.
Input: 10 43 33 14 19 2 | Output: 22 3
Hard
3
883
262
293
3
1,107
A
1107A
A. Digits Sequence Dividing
900
greedy; strings
You are given a sequence \(s\) consisting of \(n\) digits from \(1\) to \(9\).You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is \(t_1, t_2, \dots, t_k\), where \(k\) is the number of element in a division, then for each \(i\) from \(1\) to \(k-1\) the condition \(t_{i} < t_{i + 1}\) (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if \(s=654\) then you can divide it into parts \([6, 54]\) and it will be suitable division. But if you will divide it into parts \([65, 4]\) then it will be bad division because \(65 > 4\). If \(s=123\) then you can divide it into parts \([1, 23]\), \([1, 2, 3]\) but not into parts \([12, 3]\).Your task is to find any suitable division for each of the \(q\) independent queries.
The first line of the input contains one integer \(q\) (\(1 \le q \le 300\)) — the number of queries.The first line of the \(i\)-th query contains one integer number \(n_i\) (\(2 \le n_i \le 300\)) — the number of digits in the \(i\)-th query.The second line of the \(i\)-th query contains one string \(s_i\) of length \(n_i\) consisting only of digits from \(1\) to \(9\).
If the sequence of digits in the \(i\)-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line ""NO"" for this query.Otherwise in the first line of the answer to this query print ""YES"", on the second line print \(k_i\) — the number of parts in your division of the \(i\)-th query sequence and in the third line print \(k_i\) strings \(t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}\) — your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string \(s_i\).See examples for better understanding.
Input: 4 6 654321 4 1337 2 33 4 2122 | Output: YES 3 6 54 321 YES 3 1 3 37 NO YES 2 21 22
Beginner
2
1,216
373
676
11
1,560
F1
1560F1
F1. Nearest Beautiful Number (easy version)
1,900
binary search; bitmasks; brute force; constructive algorithms; dfs and similar; greedy
It is a simplified version of problem F2. The difference between them is the constraints (F1: \(k \le 2\), F2: \(k \le 10\)).You are given an integer \(n\). Find the minimum integer \(x\) such that \(x \ge n\) and the number \(x\) is \(k\)-beautiful.A number is called \(k\)-beautiful if its decimal representation having no leading zeroes contains no more than \(k\) different digits. E.g. if \(k = 2\), the numbers \(3434443\), \(55550\), \(777\) and \(21\) are \(k\)-beautiful whereas the numbers \(120\), \(445435\) and \(998244353\) are not.
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. Then \(t\) test cases follow.Each test case consists of one line containing two integers \(n\) and \(k\) (\(1 \le n \le 10^9\), \(1 \le k \le 2\)).
For each test case output on a separate line \(x\) — the minimum \(k\)-beautiful integer such that \(x \ge n\).
Input: 4 1 1 221 2 177890 2 998244353 1 | Output: 1 221 181111 999999999
Hard
6
546
240
111
15
1,843
B
1843B
B. Long Long
800
greedy; math; two pointers
Today Alex was brought array \(a_1, a_2, \dots, a_n\) of length \(n\). He can apply as many operations as he wants (including zero operations) to change the array elements.In \(1\) operation Alex can choose any \(l\) and \(r\) such that \(1 \leq l \leq r \leq n\), and multiply all elements of the array from \(l\) to \(r\) inclusive by \(-1\). In other words, Alex can replace the subarray \([a_l, a_{l + 1}, \dots, a_r]\) by \([-a_l, -a_{l + 1}, \dots, -a_r]\) in \(1\) operation.For example, let \(n = 5\), the array is \([1, -2, 0, 3, -1]\), \(l = 2\) and \(r = 4\), then after the operation the array will be \([1, 2, 0, -3, -1]\).Alex is late for school, so you should help him find the maximum possible sum of numbers in the array, which can be obtained by making any number of operations, as well as the minimum number of operations that must be done for this.
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) — number of test cases. Then the descriptions of the test cases follow.The first line of each test case contains one integer \(n\) (\(1 \leq n \leq 2 \cdot 10^5\)) — length of the array.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(-10^9 \leq a_i \leq 10^9\)) — elements of the array.It is guaranteed that the sum of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case output two space-separated numbers: the maximum possible sum of numbers in the array and the minimum number of operations to get this sum.Pay attention that an answer may not fit in a standard integer type, so do not forget to use 64-bit integer type.
Below, for each test case, only one of the possible shortest sequences of operations is provided among many. There are others that have the same length and lead to the maximum sum of elements.In the first test case, Alex can make operations: \((1, 4)\), \((2, 2)\), \((6, 6)\).In the second test case, to get the largest sum you need to make operations: \((1, 8)\), \((5, 6)\).In the fourth test case, it is necessary to make only one operation: \((2, 3)\).
Input: 56-1 7 -4 -2 5 -88-1 0 0 -2 1 0 -3 052 -1 0 -3 -750 -17 0 1 04-1 0 -2 -1 | Output: 27 3 7 2 13 1 18 1 4 1
Beginner
3
868
469
270
18
1,663
A
1663A
A. Who Tested?
0
*special; expression parsing; trees
Beginner
3
0
0
0
16
1,744
B
1744B
B. Even-Odd Increments
800
implementation; math
You are given \(n\) of integers \(a_1, a_2, \ldots, a_n\). Process \(q\) queries of two types: query of the form ""0 \(x_j\)"": add the value \(x_j\) to all even elements of the array \(a\), query of the form ""1 \(x_j\)"": add the value \(x_j\) to all odd elements of the array \(a\).Note that when processing the query, we look specifically at the odd/even value of \(a_i\), not its index.After processing each query, print the sum of the elements of the array \(a\).Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
The first line of the input contains an integer \(t\) \((1 \leq t \leq 10^4\)) — the number of test cases.The descriptions of the test cases follow.The first line of each test case contains two integers \(n\) and \(q\) (\(1 \leq n\), \(q \leq 10^5\)) — the length of array \(a\) and the number of queries.The second line of each test case contains exactly \(n\) integers: \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 10^9\)) — elements of the array \(a\).The following \(q\) lines contain queries as two integers \(type_j\) and \(x_j\) \((0 \leq type_j \leq 1\), \(1 \leq x_j \leq 10^4\)).It is guaranteed that the sum of values \(n\) over all test cases in a test does not exceed \(10^5\). Similarly, the sum of values \(q\) over all test cases does not exceed \(10^5\).
For each test case, print \(q\) numbers: the sum of the elements of the array \(a\) after processing a query.
In the first test case, the array \(a = [2]\) after the first query.In the third test case, the array \(a\) is modified as follows: \([1, 3, 2, 4, 10, 48]\) \(\rightarrow\) \([7, 9, 2, 4, 10, 48]\) \(\rightarrow\) \([7, 9, 7, 9, 15, 53]\) \(\rightarrow\) \([7, 9, 7, 9, 15, 53]\) \(\rightarrow\) \([10, 12, 10, 12, 18, 56]\) \(\rightarrow\) \([22, 24, 22, 24, 30, 68]\) \(\rightarrow\) \([23, 25, 23, 25, 31, 69]\).
Input: 41 111 13 31 2 40 21 30 56 71 3 2 4 10 481 60 50 40 51 30 120 16 71000000000 1000000000 1000000000 11 15 170 171 100001 510 920 531 160 1 | Output: 2 11 14 29 80 100 100 100 118 190 196 3000000094 3000060094 3000060400 3000060952 3000061270 3000061366 3000061366
Beginner
2
654
771
109
17
1,938
J
1938J
2,100
Hard
0
0
0
0
19
877
E
877E
E. Danil and a Part-time Job
2,000
bitmasks; data structures; trees
Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.There are two types of tasks: pow v describes a task to switch lights in the subtree of vertex v. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v.Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.
The first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the ancestor of vertex i.The third line contains n space-separated integers t1, t2, ..., tn (0 ≤ ti ≤ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise.The fourth line contains a single integer q (1 ≤ q ≤ 200 000) — the number of tasks.The next q lines are get v or pow v (1 ≤ v ≤ n) — the tasks described above.
For each task get v print the number of rooms in the subtree of v, in which the light is turned on.
The tree before the task pow 1. The tree after the task pow 1.
Input: 41 1 11 0 0 19get 1get 2get 3get 4pow 1get 1get 2get 3get 4 | Output: 20012110
Hard
3
1,262
531
99
8
251
B
251B
B. Playing with Permutations
1,800
implementation; math
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n.A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below. During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times.Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding.
The first line contains two integers n and k (1 ≤ n, k ≤ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≤ qi ≤ n) — the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format.It is guaranteed that the given sequences q and s are correct permutations.
If the situation that is described in the statement is possible, print ""YES"" (without the quotes), otherwise print ""NO"" (without the quotes).
In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed.In the second sample the described situation is possible, in case if after we toss a coin, we get tails.In the third sample the possible coin tossing sequence is: heads-tails-tails.In the fourth sample the possible coin tossing sequence is: heads-heads.
Input: 4 12 3 4 11 2 3 4 | Output: NO
Medium
2
1,785
337
145
2
1,144
G
1144G
G. Two Merged Sequences
2,400
dp; greedy
Two integer sequences existed initially, one of them was strictly increasing, and another one — strictly decreasing.Strictly increasing sequence is a sequence of integers \([x_1 < x_2 < \dots < x_k]\). And strictly decreasing sequence is a sequence of integers \([y_1 > y_2 > \dots > y_l]\). Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.Elements of increasing sequence were inserted between elements of the decreasing one (and, possibly, before its first element and after its last element) without changing the order. For example, sequences \([1, 3, 4]\) and \([10, 4, 2]\) can produce the following resulting sequences: \([10, \textbf{1}, \textbf{3}, 4, 2, \textbf{4}]\), \([\textbf{1}, \textbf{3}, \textbf{4}, 10, 4, 2]\). The following sequence cannot be the result of these insertions: \([\textbf{1}, 10, \textbf{4}, 4, \textbf{3}, 2]\) because the order of elements in the increasing sequence was changed.Let the obtained sequence be \(a\). This sequence \(a\) is given in the input. Your task is to find any two suitable initial sequences. One of them should be strictly increasing, and another one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence \(a\) into one increasing sequence and one decreasing sequence, print ""NO"".
The first line of the input contains one integer \(n\) (\(1 \le n \le 2 \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\) (\(0 \le a_i \le 2 \cdot 10^5\)), where \(a_i\) is the \(i\)-th element of \(a\).
If there is a contradiction in the input and it is impossible to split the given sequence \(a\) into one increasing sequence and one decreasing sequence, print ""NO"" in the first line.Otherwise print ""YES"" in the first line. In the second line, print a sequence of \(n\) integers \(res_1, res_2, \dots, res_n\), where \(res_i\) should be either \(0\) or \(1\) for each \(i\) from \(1\) to \(n\). The \(i\)-th element of this sequence should be \(0\) if the \(i\)-th element of \(a\) belongs to the increasing sequence, and \(1\) otherwise. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.
Input: 9 5 1 3 6 8 2 9 0 10 | Output: YES 1 0 0 0 0 1 0 1 0
Expert
2
1,487
279
661
11
1,566
G
1566G
G. Four Vertices
3,100
constructive algorithms; data structures; graphs; greedy; implementation; shortest paths
You are given an undirected weighted graph, consisting of \(n\) vertices and \(m\) edges.Some queries happen with this graph: Delete an existing edge from the graph. Add a non-existing edge to the graph. At the beginning and after each query, you should find four different vertices \(a\), \(b\), \(c\), \(d\) such that there exists a path between \(a\) and \(b\), there exists a path between \(c\) and \(d\), and the sum of lengths of two shortest paths from \(a\) to \(b\) and from \(c\) to \(d\) is minimal. The answer to the query is the sum of the lengths of these two shortest paths. The length of the path is equal to the sum of weights of edges in this path.
The first line contains two integers \(n\) and \(m\) \((4 \le n, m \le 10^5)\) — the number of vertices and edges in the graph respectively.Each of the next \(m\) lines contain three integers \(v\), \(u\), \(w\) (\(1 \le v, u \le n, v \neq u\), \(1 \le w \le 10^9\)) — this triple means that there is an edge between vertices \(v\) and \(u\) with weight \(w\).The next line contains a single integer \(q\) \((0 \le q \le 10^5)\) — the number of queries.The next \(q\) lines contain the queries of two types: \(0\) \(v\) \(u\) — this query means deleting an edge between \(v\) and \(u\) \((1 \le v, u \le n, v \neq u)\). It is guaranteed that such edge exists in the graph. \(1\) \(v\) \(u\) \(w\) — this query means adding an edge between vertices \(v\) and \(u\) with weight \(w\) (\(1 \le v, u \le n, v \neq u\), \(1 \le w \le 10^9\)). It is guaranteed that there was no such edge in the graph. It is guaranteed that the initial graph does not contain multiple edges.At the beginning and after each query, the graph doesn't need to be connected.It is guaranteed that at each moment the number of edges will be at least \(4\). It can be proven, that at each moment there exist some four vertices \(a\), \(b\), \(c\), \(d\) such that there exists a path between vertices \(a\) and \(b\), and there exists a path between vertices \(c\) and \(d\).
Print \(q + 1\) integers — the minimal sum of lengths of shortest paths between chosen pairs of vertices before the queries and after each of them.
Before the queries you can choose vertices \((a, b) = (3, 2)\) and \((c, d) = (1, 4)\). The sum of lengths of two shortest paths is \(3 + 1 = 4\).After the first query you can choose vertices \((a, b) = (2, 5)\) and \((c, d) = (1, 4)\). The sum of lengths of two shortest paths is \(2 + 1 = 3\).After the second query you can choose vertices \((a, b) = (3, 4)\) and \((c, d) = (2, 5)\). The sum of lengths of two shortest paths is \(1 + 2 = 3\).After the third query, you can choose vertices \((a, b) = (2, 6)\) and \((c, d) = (4, 5)\). The sum of lengths of two shortest paths is \(4 + 3 = 7\).After the last query you can choose vertices \((a, b) = (1, 6)\) and \((c, d) = (2, 5)\). The sum of lengths of two shortest paths is \(3 + 2 = 5\).
Input: 6 6 1 3 6 4 3 1 1 4 1 2 6 4 2 4 2 5 4 3 4 1 2 5 2 0 1 4 0 3 4 1 6 1 3 | Output: 4 3 3 7 5
Master
6
666
1,345
147
15
70
A
70A
A. Cookies
1,300
math
Fangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square k × k in size, divided into blocks 1 × 1 in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie k in size. Fangy also has a box with a square base 2n × 2n, divided into blocks 1 × 1 in size. In a box the cookies should not overlap, and they should not be turned over or rotated. See cookies of sizes 2 and 4 respectively on the figure: To stack the cookies the little walrus uses the following algorithm. He takes out of the repository the largest cookie which can fit in some place in the box and puts it there. Everything could be perfect but alas, in the repository the little walrus has infinitely many cookies of size 2 and larger, and there are no cookies of size 1, therefore, empty cells will remain in the box. Fangy wants to know how many empty cells will be left in the end.
The first line contains a single integer n (0 ≤ n ≤ 1000).
Print the single number, equal to the number of empty cells in the box. The answer should be printed modulo 106 + 3.
If the box possesses the base of 23 × 23 (as in the example), then the cookies will be put there in the following manner:
Input: 3 | Output: 9
Easy
1
995
58
116
0
1,910
A
1910A
A. Username
1,100
*special; implementation
On the official website of Berland, each account has two parameters: username and ID.Username is a string consisting of lowercase Latin letters and/or digits, which contains at least one letter. For example, user0, 1fox1, zzzz are correct usernames, but 1337 and User22 are not. The ID of the account for a given username is generated as follows: a positive integer without leading zeroes is appended to the end of the username. For example, the ID user0125 can be generated by the following usernames: user012, user01, user0; but neither by user nor us.You are given a string \(s\) — a valid ID. Your task is to determine any valid username that can generate the given ID. If there are several correct usernames, you can print any of them.
The first line contains a single integer \(t\) (\(1 \le t \le 10^3\)) — the number of test cases.The only line of each test case contains a string \(s\) (\(2 \le |s| \le 50\)), consisting of lowercase Latin letters and/or digits.Additional constraint on input: there is at least one valid username that can generate the given ID.
For each test case on a separate line, print a string — any valid username that can generate the given ID. If there are multiple correct usernames, you can print any of them.
Input: 4user0125a1kotlin9900001code0forces101 | Output: user0 a kotlin9 1code0forces
Easy
2
740
329
174
19
1,778
D
1778D
D. Flexible String Revisit
2,100
combinatorics; dp; math; probabilities
You are given two binary strings \(a\) and \(b\) of length \(n\). In each move, the string \(a\) is modified in the following way. An index \(i\) (\(1 \leq i \leq n\)) is chosen uniformly at random. The character \(a_i\) will be flipped. That is, if \(a_i\) is \(0\), it becomes \(1\), and if \(a_i\) is \(1\), it becomes \(0\). What is the expected number of moves required to make both strings equal for the first time?A binary string is a string, in which the character is either \(\tt{0}\) or \(\tt{1}\).
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^5\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \leq n \leq 10^6\)) — the length of the strings.The second line of each test case contains the binary string \(a\) of length \(n\).The third line of each test case contains the binary string \(b\) of length \(n\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\).
For each test case, output a single line containing the expected number of moves modulo \(998\,244\,353\).Formally, let \(M = 998\,244\,353\). It can be shown that the answer can be expressed as an irreducible fraction \(\frac{p}{q}\), where \(p\) and \(q\) are integers and \(q \not \equiv 0 \pmod{M}\). Output the integer equal to \(p \cdot q^{-1} \bmod M\). In other words, output such an integer \(x\) that \(0 \le x < M\) and \(x \cdot q \equiv p \pmod{M}\).
In the first test case, index \(1\) is chosen randomly and \(a_1\) is flipped. After the move, the strings \(a\) and \(b\) are equal. The expected number of moves is \(1\).The strings \(a\) and \(b\) are already equal in the second test case. So, the expected number of moves is \(0\).The expected number of moves for the third and fourth test cases are \(\frac{56}{3}\) and \(\frac{125}{3}\) respectively.
Input: 41012000041000111050100110111 | Output: 1 0 665496254 665496277
Hard
4
508
509
463
17
1,812
D
1812D
D. Trivial Conjecture
0
*special; constructive algorithms; math; number theory
$$$\(f(n) = \left\{ \begin{array}{ll} \frac{n}{2} & n \equiv 0 \pmod{2}\\ 3n+1 & n \equiv 1 \pmod{2}\\ \end{array} \right.\)\(Find an integer \)n\( so that none of the first \)k\( terms of the sequence \)n, f(n), f(f(n)), f(f(f(n))), \dots\( are equal to \)1$$$.
The only line contains an integer \(k\) (\(1 \leq k \leq \min(\textbf{[REDACTED]}, 10^{18})\)).
Output a single integer \(n\) such that none of the first \(k\) terms of the sequence \(n, f(n), f(f(n)), f(f(f(n))), \dots\) are equal to \(1\).Integer \(n\) should have at most \(10^3\) digits.
In the first test, the sequence created with \(n = 5\) looks like \(5, 16, 8, 4, 2, 1, 4, \dots\), and none of the first \(k=1\) terms are equal to \(1\).In the second test, the sequence created with \(n = 6\) looks like \(6, 3, 10, 5, 16, 8, 4, \dots\), and none of the first \(k=5\) terms are equal to \(1\).
Input: 1 | Output: 5
Beginner
4
262
95
195
18
897
B
897B
B. Chtholly's request
1,300
brute force
— Thanks a lot for today.— I experienced so many great things.— You gave me memories like dreams... But I have to leave now...— One last request, can you...— Help me solve a Codeforces problem?— ......— What?Chtholly has been thinking about a problem for days:If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!
The first line contains two integers k and p (1 ≤ k ≤ 105, 1 ≤ p ≤ 109).
Output single integer — answer to the problem.
In the first example, the smallest zcy number is 11, and the second smallest zcy number is 22.In the second example, .
Input: 2 100 | Output: 33
Easy
1
832
72
46
8
873
B
873B
B. Balanced Substring
1,500
dp; implementation
You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.You have to determine the length of the longest balanced substring of s.
The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s.The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.
If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.
In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.In the second example it's impossible to find a non-empty balanced substring.
Input: 811010111 | Output: 4
Medium
2
336
187
121
8
1,767
C
1767C
C. Count Binary Strings
2,100
data structures; dp
You are given an integer \(n\). You have to calculate the number of binary (consisting of characters 0 and/or 1) strings \(s\) meeting the following constraints.For every pair of integers \((i, j)\) such that \(1 \le i \le j \le n\), an integer \(a_{i,j}\) is given. It imposes the following constraint on the string \(s_i s_{i+1} s_{i+2} \dots s_j\): if \(a_{i,j} = 1\), all characters in \(s_i s_{i+1} s_{i+2} \dots s_j\) should be the same; if \(a_{i,j} = 2\), there should be at least two different characters in \(s_i s_{i+1} s_{i+2} \dots s_j\); if \(a_{i,j} = 0\), there are no additional constraints on the string \(s_i s_{i+1} s_{i+2} \dots s_j\). Count the number of binary strings \(s\) of length \(n\) meeting the aforementioned constraints. Since the answer can be large, print it modulo \(998244353\).
The first line contains one integer \(n\) (\(2 \le n \le 100\)).Then \(n\) lines follow. The \(i\)-th of them contains \(n-i+1\) integers \(a_{i,i}, a_{i,i+1}, a_{i,i+2}, \dots, a_{i,n}\) (\(0 \le a_{i,j} \le 2\)).
Print one integer — the number of strings meeting the constraints, taken modulo \(998244353\).
In the first example, the strings meeting the constraints are 001, 010, 011, 100, 101, 110.In the second example, the strings meeting the constraints are 001, 110.
Input: 3 1 0 2 1 0 1 | Output: 6
Hard
2
815
214
94
17
1,286
E
1286E
E. Fedya the Potter Strikes Back
3,200
data structures; strings
Fedya has a string \(S\), initially empty, and an array \(W\), also initially empty.There are \(n\) queries to process, one at a time. Query \(i\) consists of a lowercase English letter \(c_i\) and a nonnegative integer \(w_i\). First, \(c_i\) must be appended to \(S\), and \(w_i\) must be appended to \(W\). The answer to the query is the sum of suspiciousnesses for all subsegments of \(W\) \([L, \ R]\), \((1 \leq L \leq R \leq i)\).We define the suspiciousness of a subsegment as follows: if the substring of \(S\) corresponding to this subsegment (that is, a string of consecutive characters from \(L\)-th to \(R\)-th, inclusive) matches the prefix of \(S\) of the same length (that is, a substring corresponding to the subsegment \([1, \ R - L + 1]\)), then its suspiciousness is equal to the minimum in the array \(W\) on the \([L, \ R]\) subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is \(0\).Help Fedya answer all the queries before the orderlies come for him!
The first line contains an integer \(n\) \((1 \leq n \leq 600\,000)\) — the number of queries.The \(i\)-th of the following \(n\) lines contains the query \(i\): a lowercase letter of the Latin alphabet \(c_i\) and an integer \(w_i\) \((0 \leq w_i \leq 2^{30} - 1)\).All queries are given in an encrypted form. Let \(ans\) be the answer to the previous query (for the first query we set this value equal to \(0\)). Then, in order to get the real query, you need to do the following: perform a cyclic shift of \(c_i\) in the alphabet forward by \(ans\), and set \(w_i\) equal to \(w_i \oplus (ans \ \& \ MASK)\), where \(\oplus\) is the bitwise exclusive ""or"", \(\&\) is the bitwise ""and"", and \(MASK = 2^{30} - 1\).
Print \(n\) lines, \(i\)-th line should contain a single integer — the answer to the \(i\)-th query.
For convenience, we will call ""suspicious"" those subsegments for which the corresponding lines are prefixes of \(S\), that is, those whose suspiciousness may not be zero.As a result of decryption in the first example, after all requests, the string \(S\) is equal to ""abacaba"", and all \(w_i = 1\), that is, the suspiciousness of all suspicious sub-segments is simply equal to \(1\). Let's see how the answer is obtained after each request:1. \(S\) = ""a"", the array \(W\) has a single subsegment — \([1, \ 1]\), and the corresponding substring is ""a"", that is, the entire string \(S\), thus it is a prefix of \(S\), and the suspiciousness of the subsegment is \(1\).2. \(S\) = ""ab"", suspicious subsegments: \([1, \ 1]\) and \([1, \ 2]\), total \(2\).3. \(S\) = ""aba"", suspicious subsegments: \([1, \ 1]\), \([1, \ 2]\), \([1, \ 3]\) and \([3, \ 3]\), total \(4\).4. \(S\) = ""abac"", suspicious subsegments: \([1, \ 1]\), \([1, \ 2]\), \([1, \ 3]\), \([1, \ 4]\) and \([3, \ 3]\), total \(5\).5. \(S\) = ""abaca"", suspicious subsegments: \([1, \ 1]\), \([1, \ 2]\), \([1, \ 3]\), \([1, \ 4]\) , \([1, \ 5]\), \([3, \ 3]\) and \([5, \ 5]\), total \(7\).6. \(S\) = ""abacab"", suspicious subsegments: \([1, \ 1]\), \([1, \ 2]\), \([1, \ 3]\), \([1, \ 4]\) , \([1, \ 5]\), \([1, \ 6]\), \([3, \ 3]\), \([5, \ 5]\) and \([5, \ 6]\), total \(9\).7. \(S\) = ""abacaba"", suspicious subsegments: \([1, \ 1]\), \([1, \ 2]\), \([1, \ 3]\), \([1, \ 4]\) , \([1, \ 5]\), \([1, \ 6]\), \([1, \ 7]\), \([3, \ 3]\), \([5, \ 5]\), \([5, \ 6]\), \([5, \ 7]\) and \([7, \ 7]\), total \(12\).In the second example, after all requests \(S\) = ""aaba"", \(W = [2, 0, 2, 0]\).1. \(S\) = ""a"", suspicious subsegments: \([1, \ 1]\) (suspiciousness \(2\)), totaling \(2\).2. \(S\) = ""aa"", suspicious subsegments: \([1, \ 1]\) (\(2\)), \([1, \ 2]\) (\(0\)), \([2, \ 2]\) ( \(0\)), totaling \(2\).3. \(S\) = ""aab"", suspicious subsegments: \([1, \ 1]\) (\(2\)), \([1, \ 2]\) (\(0\)), \([1, \ 3]\) ( \(0\)), \([2, \ 2]\) (\(0\)), totaling \(2\).4. \(S\) = ""aaba"", suspicious subsegments: \([1, \ 1]\) (\(2\)), \([1, \ 2]\) (\(0\)), \([1, \ 3]\) ( \(0\)), \([1, \ 4]\) (\(0\)), \([2, \ 2]\) (\(0\)), \([4, \ 4]\) (\(0\)), totaling \(2\).In the third example, from the condition after all requests \(S\) = ""abcde"", \(W = [7, 2, 10, 1, 7]\).1. \(S\) = ""a"", suspicious subsegments: \([1, \ 1]\) (\(7\)), totaling \(7\).2. \(S\) = ""ab"", suspicious subsegments: \([1, \ 1]\) (\(7\)), \([1, \ 2]\) (\(2\)), totaling \(9\).3. \(S\) = ""abc"", suspicious subsegments: \([1, \ 1]\) (\(7\)), \([1, \ 2]\) (\(2\)), \([1, \ 3]\) ( \(2\)), totaling \(11\).4. \(S\) = ""abcd"", suspicious subsegments: \([1, \ 1]\) (\(7\)), \([1, \ 2]\) (\(2\)), \([1, \ 3]\) ( \(2\)), \([1, \ 4]\) (\(1\)), totaling \(12\).5. \(S\) = ""abcde"", suspicious subsegments: \([1, \ 1]\) (\(7\)), \([1, \ 2]\) (\(2\)), \([1, \ 3]\) ( \(2\)), \([1, \ 4]\) (\(1\)), \([1, \ 5]\) (\(1\)), totaling \(13\).
Input: 7 a 1 a 0 y 3 y 5 v 4 u 6 r 8 | Output: 1 2 4 5 7 9 12
Master
2
1,029
719
100
12
1,292
D
1292D
D. Chaotic V.
2,700
dp; graphs; greedy; math; number theory; trees
Æsir - CHAOS Æsir - V.""Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time.""The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (\(1, 2, 3, \ldots\)). The node with a number \(x\) (\(x > 1\)), is directly connected with a node with number \(\frac{x}{f(x)}\), with \(f(x)\) being the lowest prime divisor of \(x\).Vanessa's mind is divided into \(n\) fragments. Due to more than 500 years of coma, the fragments have been scattered: the \(i\)-th fragment is now located at the node with a number \(k_i!\) (a factorial of \(k_i\)).To maximize the chance of successful awakening, Ivy decides to place the samples in a node \(P\), so that the total length of paths from each fragment to \(P\) is smallest possible. If there are multiple fragments located at the same node, the path from that node to \(P\) needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node \(P\).
The first line contains an integer \(n\) (\(1 \le n \le 10^6\)) — number of fragments of Vanessa's mind.The second line contains \(n\) integers: \(k_1, k_2, \ldots, k_n\) (\(0 \le k_i \le 5000\)), denoting the nodes where fragments of Vanessa's mind are located: the \(i\)-th fragment is at the node with a number \(k_i!\).
Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node \(P\)).As a reminder, if there are multiple fragments at the same node, the distance from that node to \(P\) needs to be counted multiple times as well.
Considering the first \(24\) nodes of the system, the node network will look as follows (the nodes \(1!\), \(2!\), \(3!\), \(4!\) are drawn bold):For the first example, Ivy will place the emotion samples at the node \(1\). From here: The distance from Vanessa's first fragment to the node \(1\) is \(1\). The distance from Vanessa's second fragment to the node \(1\) is \(0\). The distance from Vanessa's third fragment to the node \(1\) is \(4\). The total length is \(5\).For the second example, the assembly node will be \(6\). From here: The distance from Vanessa's first fragment to the node \(6\) is \(0\). The distance from Vanessa's second fragment to the node \(6\) is \(2\). The distance from Vanessa's third fragment to the node \(6\) is \(2\). The distance from Vanessa's fourth fragment to the node \(6\) is again \(2\). The total path length is \(6\).
Input: 3 2 1 4 | Output: 5
Master
6
1,485
323
279
12
343
A
343A
A. Rational Resistance
1,600
math; number theory
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements: one resistor; an element and one resistor plugged in sequence; an element and one resistor plugged in parallel. With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals . In this case Re equals the resistance of the element being connected.Mike needs to assemble an element with a resistance equal to the fraction . Determine the smallest possible number of resistors he needs to make such an element.
The single input line contains two space-separated integers a and b (1 ≤ a, b ≤ 1018). It is guaranteed that the fraction is irreducible. It is guaranteed that a solution always exists.
Print a single number — the answer to the problem.Please do not use the %lld specifier to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams or the %I64d specifier.
In the first sample, one resistor is enough.In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance . We cannot make this element using two resistors.
Input: 1 1 | Output: 1
Medium
2
852
185
198
3
1,701
E
1701E
E. Text Editor
2,500
brute force; dp; greedy; strings
You wanted to write a text \(t\) consisting of \(m\) lowercase Latin letters. But instead, you have written a text \(s\) consisting of \(n\) lowercase Latin letters, and now you want to fix it by obtaining the text \(t\) from the text \(s\).Initially, the cursor of your text editor is at the end of the text \(s\) (after its last character). In one move, you can do one of the following actions: press the ""left"" button, so the cursor is moved to the left by one position (or does nothing if it is pointing at the beginning of the text, i. e. before its first character); press the ""right"" button, so the cursor is moved to the right by one position (or does nothing if it is pointing at the end of the text, i. e. after its last character); press the ""home"" button, so the cursor is moved to the beginning of the text (before the first character of the text); press the ""end"" button, so the cursor is moved to the end of the text (after the last character of the text); press the ""backspace"" button, so the character before the cursor is removed from the text (if there is no such character, nothing happens). Your task is to calculate the minimum number of moves required to obtain the text \(t\) from the text \(s\) using the given set of actions, or determine it is impossible to obtain the text \(t\) from the text \(s\).You have to answer \(T\) independent test cases.
The first line of the input contains one integer \(T\) (\(1 \le T \le 5000\)) — the number of test cases. Then \(T\) test cases follow.The first line of the test case contains two integers \(n\) and \(m\) (\(1 \le m \le n \le 5000\)) — the length of \(s\) and the length of \(t\), respectively.The second line of the test case contains the string \(s\) consisting of \(n\) lowercase Latin letters.The third line of the test case contains the string \(t\) consisting of \(m\) lowercase Latin letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(5000\) (\(\sum n \le 5000\)).
For each test case, print one integer — the minimum number of moves required to obtain the text \(t\) from the text \(s\) using the given set of actions, or -1 if it is impossible to obtain the text \(t\) from the text \(s\) in the given test case.
Input: 69 4aaaaaaaaaaaaa7 3abacabaaaa5 4aabcdabcd4 2abbabb6 4barakabaka8 7questionproblem | Output: 5 6 3 4 4 -1
Expert
4
1,385
605
248
17
1,719
B
1719B
B. Mathematical Circus
800
constructive algorithms; math
A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — \(n\) and \(k\), where \(n\) is even. Next, he takes all the integers from \(1\) to \(n\), and splits them all into pairs \((a, b)\) (each integer must be in exactly one pair) so that for each pair the integer \((a + k) \cdot b\) is divisible by \(4\) (note that the order of the numbers in the pair matters), or reports that, unfortunately for viewers, such a split is impossible.Burenka really likes such performances, so she asked her friend Tonya to be a magician, and also gave him the numbers \(n\) and \(k\).Tonya is a wolf, and as you know, wolves do not perform in the circus, even in a mathematical one. Therefore, he asks you to help him. Let him know if a suitable splitting into pairs is possible, and if possible, then tell it.
The first line contains one integer \(t\) (\(1 \leq t \leq 10^4\)) — the number of test cases. The following is a description of the input data sets.The single line of each test case contains two integers \(n\) and \(k\) (\(2 \leq n \leq 2 \cdot 10^5\), \(0 \leq k \leq 10^9\), \(n\) is even) — the number of integers and the number being added \(k\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, first output the string ""YES"" if there is a split into pairs, and ""NO"" if there is none.If there is a split, then in the following \(\frac{n}{2}\) lines output pairs of the split, in each line print \(2\) numbers — first the integer \(a\), then the integer \(b\).
In the first test case, splitting into pairs \((1, 2)\) and \((3, 4)\) is suitable, same as splitting into \((1, 4)\) and \((3, 2)\).In the second test case, \((1 + 0) \cdot 2 = 1 \cdot (2 + 0) = 2\) is not divisible by \(4\), so there is no partition.
Input: 44 12 012 1014 11 | Output: YES 1 2 3 4 NO YES 3 4 7 8 11 12 2 1 6 5 10 9 YES 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Beginner
2
860
443
287
17
1,791
D
1791D
D. Distinct Split
1,000
brute force; greedy; strings
Let's denote the \(f(x)\) function for a string \(x\) as the number of distinct characters that the string contains. For example \(f(\texttt{abc}) = 3\), \(f(\texttt{bbbbb}) = 1\), and \(f(\texttt{babacaba}) = 3\).Given a string \(s\), split it into two non-empty strings \(a\) and \(b\) such that \(f(a) + f(b)\) is the maximum possible. In other words, find the maximum possible value of \(f(a) + f(b)\) such that \(a + b = s\) (the concatenation of string \(a\) and string \(b\) is equal to string \(s\)).
The input consists of multiple test cases. The first line contains an integer \(t\) (\(1 \leq t \leq 10^4\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer \(n\) (\(2 \leq n \leq 2\cdot10^5\)) — the length of the string \(s\).The second line contains the string \(s\), consisting of lowercase English letters.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2\cdot10^5\).
For each test case, output a single integer — the maximum possible value of \(f(a) + f(b)\) such that \(a + b = s\).
For the first test case, there is only one valid way to split \(\texttt{aa}\) into two non-empty strings \(\texttt{a}\) and \(\texttt{a}\), and \(f(\texttt{a}) + f(\texttt{a}) = 1 + 1 = 2\).For the second test case, by splitting \(\texttt{abcabcd}\) into \(\texttt{abc}\) and \(\texttt{abcd}\) we can get the answer of \(f(\texttt{abc}) + f(\texttt{abcd}) = 3 + 4 = 7\) which is maximum possible.For the third test case, it doesn't matter how we split the string, the answer will always be \(2\).
Input: 52aa7abcabcd5aaaaa10paiumoment4aazz | Output: 2 7 2 10 3
Beginner
3
508
475
116
17
990
C
990C
C. Bracket Sequences Concatenation Problem
1,500
implementation
A bracket sequence is a string containing only characters ""("" and "")"".A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters ""1"" and ""+"" between the original characters of the sequence. For example, bracket sequences ""()()"", ""(())"" are regular (the resulting expressions are: ""(1)+(1)"", ""((1+1)+1)""), and "")("" and ""("" are not.You are given \(n\) bracket sequences \(s_1, s_2, \dots , s_n\). Calculate the number of pairs \(i, j \, (1 \le i, j \le n)\) such that the bracket sequence \(s_i + s_j\) is a regular bracket sequence. Operation \(+\) means concatenation i.e. ""()("" + "")()"" = ""()()()"".If \(s_i + s_j\) and \(s_j + s_i\) are regular bracket sequences and \(i \ne j\), then both pairs \((i, j)\) and \((j, i)\) must be counted in the answer. Also, if \(s_i + s_i\) is a regular bracket sequence, the pair \((i, i)\) must be counted in the answer.
The first line contains one integer \(n \, (1 \le n \le 3 \cdot 10^5)\) — the number of bracket sequences. The following \(n\) lines contain bracket sequences — non-empty strings consisting only of characters ""("" and "")"". The sum of lengths of all bracket sequences does not exceed \(3 \cdot 10^5\).
In the single line print a single integer — the number of pairs \(i, j \, (1 \le i, j \le n)\) such that the bracket sequence \(s_i + s_j\) is a regular bracket sequence.
In the first example, suitable pairs are \((3, 1)\) and \((2, 2)\).In the second example, any pair is suitable, namely \((1, 1), (1, 2), (2, 1), (2, 2)\).
Input: 3)()( | Output: 2
Medium
1
958
303
170
9
2,046
D
2046D
D. For the Emperor!
3,100
flows; graphs
In Ancient Rome, a plan to defeat the barbarians was developed, but for its implementation, each city must be informed about it.The northern part of the Roman Empire consists of \(n\) cities connected by \(m\) one-way roads. Initially, the \(i\)-th city has \(a_i\) messengers, and each messenger can freely move between cities following the existing roads. A messenger can carry a copy of the plan with him and inform the cities he visits, and can make unlimited copies for other messengers in the city he is currently in.At the start, you will produce some number of plans and deliver them to messengers of your choice. Your goal is to make sure that every city is visited by a messenger with a plan. Find the smallest number of the plans you need to produce originally, so that the messengers will deliver them to every city, or determine that it is impossible to do so at all.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). The description of the test cases follows. The first line contains two integers \(n\) and \(m\) (\(2 \le n \le 200\), \(1 \le m \le 800\)) — the number of cities and roads.The second line contains \(n\) non-negative integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_{i} \le n\)) — the initial number of messengers in each city.Each of the following \(m\) lines contains two integers \(u\) and \(v\) (\(1 \le u,v \le n, u \ne v\)), indicating that there is a one-way road from city \(u\) to city \(v\). The roads may repeat.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(200\). It is guaranteed that the sum of \(m\) over all test cases does not exceed \(800\).
Output a single line containing a single integer — the smallest number of messengers you need to give a copy of the plan in the beginning, or \(-1\) if it is not possible to inform all cities.
Input: 27 62 1 0 1 2 3 41 21 32 42 53 63 74 41 1 1 11 21 32 43 4 | Output: 2 2
Master
2
880
804
192
20
1,902
E
1902E
E. Collapsing Strings
1,900
data structures; strings; trees
You are given \(n\) strings \(s_1, s_2, \dots, s_n\), consisting of lowercase Latin letters. Let \(|x|\) be the length of string \(x\).Let a collapse \(C(a, b)\) of two strings \(a\) and \(b\) be the following operation: if \(a\) is empty, \(C(a, b) = b\); if \(b\) is empty, \(C(a, b) = a\); if the last letter of \(a\) is equal to the first letter of \(b\), then \(C(a, b) = C(a_{1,|a|-1}, b_{2,|b|})\), where \(s_{l,r}\) is the substring of \(s\) from the \(l\)-th letter to the \(r\)-th one; otherwise, \(C(a, b) = a + b\), i. e. the concatenation of two strings. Calculate \(\sum\limits_{i=1}^n \sum\limits_{j=1}^n |C(s_i, s_j)|\).
The first line contains a single integer \(n\) (\(1 \le n \le 10^6\)).Each of the next \(n\) lines contains a string \(s_i\) (\(1 \le |s_i| \le 10^6\)), consisting of lowercase Latin letters.The total length of the strings doesn't exceed \(10^6\).
Print a single integer — \(\sum\limits_{i=1}^n \sum\limits_{j=1}^n |C(s_i, s_j)|\).
Input: 3abaabba | Output: 20
Hard
3
636
247
83
19
1,407
E
1407E
E. Egor in the Republic of Dagestan
2,500
constructive algorithms; dfs and similar; dp; graphs; greedy; shortest paths
Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are \(n\) cities in the republic, some of them are connected by \(m\) directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city \(1\), travel to the city \(n\) by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads — in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from \(1\) to \(n\), and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from \(1\) to \(n\) or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.
The first line contains two integers \(n\), \(m\) (\(1 \leq n \leq 500000\), \(0 \leq m \leq 500000\)) — the number of cities and the number of roads.The \(i\)-th of next \(m\) lines contains three integers — \(u_i\), \(v_i\) and \(t_i\) (\(1 \leq u_i, v_i \leq n\), \(t_i \in \{0, 1\}\)) — numbers of cities connected by road and its type, respectively (\(0\) — night road, \(1\) — morning road).
In the first line output the length of the desired path (or \(-1\), if it's possible to choose such schedule that there's no path from \(1\) to \(n\)).In the second line output the desired schedule — a string of \(n\) digits, where \(i\)-th digit is \(0\), if the \(i\)-th city is a night one, and \(1\) if it's a morning one.If there are multiple answers, print any.
For the first sample, if we paint city \(1\) white, the shortest path is \(1 \rightarrow 3\). Otherwise, it's \(1 \rightarrow 2 \rightarrow 3\) regardless of other cities' colors.For the second sample, we should paint city \(3\) black, and there are both black and white roads going from \(2\) to \(4\). Note that there can be a road connecting a city with itself.
Input: 3 4 1 2 0 1 3 1 2 3 0 2 3 1 | Output: 2 011
Expert
6
1,688
397
367
14
555
A
555A
A. Case of Matryoshkas
1,500
implementation
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5. In one second, you can perform one of the two following operations: Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b; Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.
The first line contains integers n (1 ≤ n ≤ 105) and k (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration.The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 ≤ mi ≤ n), and then mi numbers ai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka).It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.
In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.
In the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.
Input: 3 22 1 21 3 | Output: 1
Medium
1
1,310
679
121
5
10
A
10A
A. Power Consumption Calculation
900
implementation
Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minutes from the start of the screensaver, laptop switches to the ""sleep"" mode and consumes P3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into n time periods [l1, r1], [l2, r2], ..., [ln, rn]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [l1, rn].
The first line contains 6 integer numbers n, P1, P2, P3, T1, T2 (1 ≤ n ≤ 100, 0 ≤ P1, P2, P3 ≤ 100, 1 ≤ T1, T2 ≤ 60). The following n lines contain description of Tom's work. Each i-th of these lines contains two space-separated integers li and ri (0 ≤ li < ri ≤ 1440, ri < li + 1 for i < n), which stand for the start and the end of the i-th period of work.
Output the answer to the problem.
Input: 1 3 2 1 5 100 10 | Output: 30
Beginner
1
896
358
33
0
822
B
822B
B. Crossword solving
1,000
brute force; implementation; strings
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark ""?"". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s=""ab?b"" as a result, it will appear in t=""aabrbb"" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol ""?"" should be considered equal to any other symbol.
The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly.The second line contains n lowercase English letters — string s.The third line contains m lowercase English letters — string t.
In the first line print single integer k — the minimal number of symbols that need to be replaced.In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.
Input: 3 5abcxaybz | Output: 22 3
Beginner
3
1,122
267
351
8
261
B
261B
B. Maxim and Restaurant
1,900
dp; math; probabilities
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.
The first line contains integer n (1 ≤ n ≤ 50) — the number of guests in the restaurant. The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 50) — the guests' sizes in meters. The third line contains integer p (1 ≤ p ≤ 50) — the table's length in meters. The numbers in the lines are separated by single spaces.
In a single line print a real number — the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10 - 4.
In the first sample the people will come in the following orders: (1, 2, 3) — there will be two people in the restaurant; (1, 3, 2) — there will be one person in the restaurant; (2, 1, 3) — there will be two people in the restaurant; (2, 3, 1) — there will be one person in the restaurant; (3, 1, 2) — there will be one person in the restaurant; (3, 2, 1) — there will be one person in the restaurant. In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 1.(3).
Input: 31 2 33 | Output: 1.3333333333
Hard
3
1,240
317
161
2
1,472
B
1472B
B. Fair Division
800
dp; greedy; math
Alice and Bob received \(n\) candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half.
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. Then \(t\) test cases follow.The first line of each test case contains an integer \(n\) (\(1 \le n \le 100\)) — the number of candies that Alice and Bob received.The next line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) — the weights of the candies. The weight of each candy is either \(1\) or \(2\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, output on a separate line: ""YES"", if all candies can be divided into two sets with the same weight; ""NO"" otherwise. You can output ""YES"" and ""NO"" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
In the first test case, Alice and Bob can each take one candy, then both will have a total weight of \(1\).In the second test case, any division will be unfair.In the third test case, both Alice and Bob can take two candies, one of weight \(1\) and one of weight \(2\).In the fourth test case, it is impossible to divide three identical candies between two people.In the fifth test case, any division will also be unfair.
Input: 5 2 1 1 2 1 2 4 1 2 1 2 3 2 2 2 3 2 1 2 | Output: YES NO YES NO NO
Beginner
3
329
483
266
14
1,783
A
1783A
A. Make it Beautiful
800
constructive algorithms; math; sortings
An array \(a\) is called ugly if it contains at least one element which is equal to the sum of all elements before it. If the array is not ugly, it is beautiful.For example: the array \([6, 3, 9, 6]\) is ugly: the element \(9\) is equal to \(6 + 3\); the array \([5, 5, 7]\) is ugly: the element \(5\) (the second one) is equal to \(5\); the array \([8, 4, 10, 14]\) is beautiful: \(8 \ne 0\), \(4 \ne 8\), \(10 \ne 8 + 4\), \(14 \ne 8 + 4 + 10\), so there is no element which is equal to the sum of all elements before it. You are given an array \(a\) such that \(1 \le a_1 \le a_2 \le \dots \le a_n \le 100\). You have to reorder the elements of \(a\) in such a way that the resulting array is beautiful. Note that you are not allowed to insert new elements or erase existing ones, you can only change the order of elements of \(a\). You are allowed to keep the array \(a\) unchanged, if it is beautiful.
The first line contains one integer \(t\) (\(1 \le t \le 2000\)) — the number of test cases.Each test case consists of two lines. The first line contains one integer \(n\) (\(2 \le n \le 50\)). The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_1 \le a_2 \le \dots \le a_n \le 100\)).
For each test case, print the answer as follows: if it is impossible to reorder the elements of \(a\) in such a way that it becomes beautiful, print NO; otherwise, in the first line, print YES. In the second line, print \(n\) integers — any beautiful array which can be obtained from \(a\) by reordering its elements. If there are multiple such arrays, print any of them.
Input: 443 3 6 6210 1051 2 3 4 531 4 4 | Output: YES 3 6 3 6 NO YES 2 4 1 5 3 YES 1 4 4
Beginner
3
906
309
371
17
1,555
A
1555A
A. PizzaForces
900
brute force; math
PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of \(6\) slices, medium ones consist of \(8\) slices, and large pizzas consist of \(10\) slices each. Baking them takes \(15\), \(20\) and \(25\) minutes, respectively.Petya's birthday is today, and \(n\) of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least \(n\) slices in total. For example: if \(12\) friends come to Petya's birthday, he has to order pizzas containing at least \(12\) slices in total. He can order two small pizzas, containing exactly \(12\) slices, and the time to bake them is \(30\) minutes; if \(15\) friends come to Petya's birthday, he has to order pizzas containing at least \(15\) slices in total. He can order a small pizza and a large pizza, containing \(16\) slices, and the time to bake them is \(40\) minutes; if \(300\) friends come to Petya's birthday, he has to order pizzas containing at least \(300\) slices in total. He can order \(15\) small pizzas, \(10\) medium pizzas and \(13\) large pizzas, in total they contain \(15 \cdot 6 + 10 \cdot 8 + 13 \cdot 10 = 300\) slices, and the total time to bake them is \(15 \cdot 15 + 10 \cdot 20 + 13 \cdot 25 = 750\) minutes; if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is \(15\) minutes.
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) — the number of testcases.Each testcase consists of a single line that contains a single integer \(n\) (\(1 \le n \le 10^{16}\)) — the number of Petya's friends.
For each testcase, print one integer — the minimum number of minutes that is needed to bake pizzas containing at least \(n\) slices in total.
Input: 6 12 15 300 1 9999999999999999 3 | Output: 30 40 750 15 25000000000000000 15
Beginner
2
1,656
231
141
15
2,019
B
2019B
B. All Pairs Segments
1,200
implementation; math
Shirobon - FOX⠀You are given \(n\) points on the \(x\) axis, at increasing positive integer coordinates \(x_1 < x_2 < \ldots < x_n\).For each pair \((i, j)\) with \(1 \leq i < j \leq n\), you draw the segment \([x_i, x_j]\). The segments are closed, i.e., a segment \([a, b]\) contains the points \(a, a+1, \ldots, b\).You are given \(q\) queries. In the \(i\)-th query, you are given a positive integer \(k_i\), and you have to determine how many points with integer coordinates are contained in exactly \(k_i\) segments.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows.The first line of each test case contains two integers \(n\), \(q\) (\(2 \le n \le 10^5\), \(1 \le q \le 10^5\)) — the number of points and the number of queries.The second line of each test case contains \(n\) integers \(x_1, x_2, \ldots, x_n\) (\(1 \leq x_1 < x_2 < \ldots < x_n \leq 10^9\)) — the coordinates of the \(n\) points.The third line of each test case contains \(q\) integers \(k_1, k_2, \ldots, k_q\) (\(1 \leq k_i \leq 10^{18}\)) — the parameters of the \(q\) queries.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\), and the sum of \(q\) over all test cases does not exceed \(10^5\).
For each test case, output a single line with \(q\) integers: the \(i\)-th integer is the answer to the \(i\)-th query.
In the first example, you only draw the segment \([101, 200]\). No point is contained in exactly \(2\) segments, and the \(100\) points \(101, 102, \ldots, 200\) are contained in exactly \(1\) segment.In the second example, you draw \(15\) segments: \([1, 2], [1, 3], [1, 5], [1, 6], [1, 7], [2, 3], [2, 5], [2, 6], [2, 7], [3, 5], [3, 6], [3, 7], [5, 6], [5, 7], [6, 7]\). Points \(1, 7\) are contained in exactly \(5\) segments; points \(2, 4, 6\) are contained in exactly \(9\) segments; points \(3, 5\) are contained in exactly \(11\) segments.
Input: 32 2101 2002 16 151 2 3 5 6 71 2 3 4 5 6 7 8 9 10 11 12 13 14 155 8254618033 265675151 461318786 557391198 8480837786 9 15 10 6 9 4 4294967300 | Output: 0 100 0 0 0 0 2 0 0 0 3 0 2 0 0 0 0 291716045 0 0 0 291716045 0 301749698 0
Easy
2
522
795
119
20
1,037
B
1037B
B. Reach Median
1,300
greedy
You are given an array \(a\) of \(n\) integers and an integer \(s\). It is guaranteed that \(n\) is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to \(s\).The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array \(6, 5, 8\) is equal to \(6\), since if we sort this array we will get \(5, 6, 8\), and \(6\) is located on the middle position.
The first line contains two integers \(n\) and \(s\) (\(1\le n\le 2\cdot 10^5-1\), \(1\le s\le 10^9\)) — the length of the array and the required value of median.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 \(a\).It is guaranteed that \(n\) is odd.
In a single line output the minimum number of operations to make the median being equal to \(s\).
In the first sample, \(6\) can be increased twice. The array will transform to \(8, 5, 8\), which becomes \(5, 8, 8\) after sorting, hence the median is equal to \(8\).In the second sample, \(19\) can be increased once and \(15\) can be increased five times. The array will become equal to \(21, 20, 12, 11, 20, 20, 12\). If we sort this array we get \(11, 12, 12, 20, 20, 20, 21\), this way the median is \(20\).
Input: 3 86 5 8 | Output: 2
Easy
1
589
321
97
10
1,823
E
1823E
E. Removing Graph
2,500
brute force; dp; games; graphs; math
Alice and Bob are playing a game on a graph. They have an undirected graph without self-loops and multiple edges. All vertices of the graph have degree equal to \(2\). The graph may consist of several components. Note that if such graph has \(n\) vertices, it will have exactly \(n\) edges.Alice and Bob take turn. Alice goes first. In each turn, the player can choose \(k\) (\(l \le k \le r\); \(l < r\)) vertices that form a connected subgraph and erase these vertices from the graph, including all incident edges.The player who can't make a step loses.For example, suppose they are playing on the given graph with given \(l = 2\) and \(r = 3\): A valid vertex set for Alice to choose at the first move is one of the following: \(\{1, 2\}\) \(\{1, 3\}\) \(\{2, 3\}\) \(\{4, 5\}\) \(\{4, 6\}\) \(\{5, 6\}\) \(\{1, 2, 3\}\) \(\{4, 5, 6\}\) Suppose, Alice chooses subgraph \(\{4, 6\}\).Then a valid vertex set for Bob to choose at the first move is one of the following: \(\{1, 2\}\) \(\{1, 3\}\) \(\{2, 3\}\) \(\{1, 2, 3\}\) Suppose, Bob chooses subgraph \(\{1, 2, 3\}\).Alice can't make a move, so she loses.You are given a graph of size \(n\) and integers \(l\) and \(r\). Who will win if both Alice and Bob play optimally.
The first line contains three integers \(n\), \(l\) and \(r\) (\(3 \le n \le 2 \cdot 10^5\); \(1 \le l < r \le n\)) — the number of vertices in the graph, and the constraints on the number of vertices Alice or Bob can choose in one move.Next \(n\) lines contains edges of the graph: one edge per line. The \(i\)-th line contains two integers \(u_i\) and \(v_i\) (\(1 \le u_i, v_i \le n\); \(u_i \neq v_i\)) — description of the \(i\)-th edge.It's guaranteed that the degree of each vertex of the given graph is equal to \(2\).
Print Alice (case-insensitive) if Alice wins, or Bob otherwise.
In the first test the same input as in legend is shown.In the second test the same graph as in legend is shown, but with \(l = 1\) and \(r = 2\).
Input: 6 2 3 1 2 2 3 3 1 4 5 5 6 6 4 | Output: Bob
Expert
5
1,225
526
63
18
1,861
B
1861B
B. Two Binary Strings
1,000
constructive algorithms; dp; greedy
You are given two strings \(a\) and \(b\) of equal length, consisting of only characters 0 and/or 1; both strings start with character 0 and end with character 1. You can perform the following operation any number of times (possibly zero): choose one of the strings and two equal characters in it; then turn all characters between them into those characters. Formally, you choose one of these two strings (let the chosen string be \(s\)), then pick two integers \(l\) and \(r\) such that \(1 \le l < r \le |s|\) and \(s_l = s_r\), then replace every character \(s_i\) such that \(l < i < r\) with \(s_l\).For example, if the chosen string is 010101, you can transform it into one of the following strings by applying one operation: 000101 if you choose \(l = 1\) and \(r = 3\); 000001 if you choose \(l = 1\) and \(r = 5\); 010001 if you choose \(l = 3\) and \(r = 5\); 010111 if you choose \(l = 4\) and \(r = 6\); 011111 if you choose \(l = 2\) and \(r = 6\); 011101 if you choose \(l = 2\) and \(r = 4\). You have to determine if it's possible to make the given strings equal by applying this operation any number of times.
The first line contains a single integer \(t\) (\(1 \le t \le 2000\)) — the number of test cases.Each test case consists of two lines: the first line contains the string \(a\) (\(2 \le |a| \le 5000\)), consisting of only characters 0 and/or 1. the second line contains the string \(b\) (\(2 \le |b| \le 5000\)), consisting of only characters 0 and/or 1. Additional constraints on the input: in each test case, \(|a| = |b|\) (the strings have equal length); in each test case, both strings start with 0 and end with 1; the total length of all strings \(a\) in all test cases does not exceed \(5000\).
For each test case, print YES if it is possible to make the strings equal. Otherwise, print NO. You can print each letter in any register.
In the first test case, we can perform the following operations: choose the string \(a\), \(l = 2\), \(r = 4\); after this operation, \(a\) is 01110001, \(b\) is 01110101; choose the string \(b\), \(l = 5\), \(r = 7\); after this operation, \(a\) is 01110001, \(b\) is 01110001. In the second test case, the strings are already equal.In the third test case, we can perform the following operations: choose the string \(a\), \(l = 4\), \(r = 6\); after this operation, \(a\) is 000111, \(b\) is 010111; choose the string \(b\), \(l = 1\), \(r = 3\); after this operation, \(a\) is 000111, \(b\) is 000111; In the fourth and fifth test cases, it's impossible to make the given strings equal.
Input: 7010100010111010101001010010001010101110000101111011001001001011011010001011011 | Output: YES YES YES NO NO NO YES
Beginner
3
1,126
599
138
18
1,893
A
1893A
A. Anonymous Informant
1,400
brute force; dfs and similar; graphs; implementation
You are given an array \(b_1, b_2, \ldots, b_n\).An anonymous informant has told you that the array \(b\) was obtained as follows: initially, there existed an array \(a_1, a_2, \ldots, a_n\), after which the following two-component operation was performed \(k\) times: A fixed point\(^{\dagger}\) \(x\) of the array \(a\) was chosen. Then, the array \(a\) was cyclically shifted to the left\(^{\ddagger}\) exactly \(x\) times.As a result of \(k\) such operations, the array \(b_1, b_2, \ldots, b_n\) was obtained. You want to check if the words of the anonymous informant can be true or if they are guaranteed to be false.\(^{\dagger}\)A number \(x\) is called a fixed point of the array \(a_1, a_2, \ldots, a_n\) if \(1 \leq x \leq n\) and \(a_x = x\).\(^{\ddagger}\)A cyclic left shift of the array \(a_1, a_2, \ldots, a_n\) is the array \(a_2, \ldots, a_n, a_1\).
Each test contains multiple test cases. The first line contains an integer \(t\) (\(1 \le t \le 10^4\)) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers \(n, k\) (\(1 \le n \le 2 \cdot 10^5\), \(1 \le k \le 10^9\)) — the length of the array \(b\) and the number of operations performed.The second line of each test case contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(1 \le b_i \le 10^9\)) — the elements of the array \(b\).It is guaranteed that the sum of the values of \(n\) for all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output ""Yes"" if the words of the anonymous informant can be true, and ""No"" if they are guaranteed to be false.
In the first test case, the array \(a\) could be equal to \([3, 2, 3, 4, 3]\). In the first operation, a fixed point \(x = 2\) was chosen, and after \(2\) left shifts, the array became \([3, 4, 3, 3, 2]\). In the second operation, a fixed point \(x = 3\) was chosen, and after \(3\) left shifts, the array became \([3, 2, 3, 4, 3]\). In the third operation, a fixed point \(x = 3\) was chosen again, and after \(3\) left shifts, the array became \([4, 3, 3, 2, 3]\), which is equal to the array \(b\).In the second test case, the array \(a\) could be equal to \([7, 2, 1]\). After the operation with a fixed point \(x = 2\), the array became \([1, 7, 2]\). Then, after the operation with a fixed point \(x = 1\), the array returned to its initial state \([7, 2, 1]\). These same \(2\) operations (with \(x = 2\), and \(x = 1\)) were repeated \(49\) times. So, after \(100\) operations, the array returned to \([7, 2, 1]\).In the third test case, it can be shown that there is no solution.
Input: 65 34 3 3 2 33 1007 2 15 56 1 1 1 11 100000000018 489 10 11 12 13 14 15 82 11 42 | Output: Yes Yes No Yes Yes No
Easy
4
866
610
134
18
2,055
F
2055F
F. Cosmic Divide
3,200
brute force; geometry; hashing; math; strings
With the artifact in hand, the fabric of reality gives way to its true master — Florida Man.A polyomino is a connected\(^{\text{∗}}\) figure constructed by joining one or more equal \(1 \times 1\) unit squares edge to edge. A polyomino is convex if, for any two squares in the polyomino that share the same row or the same column, all squares between them are also part of the polyomino. Below are four polyominoes, only the first and second of which are convex. You are given a convex polyomino with \(n\) rows and an even area. For each row \(i\) from \(1\) to \(n\), the unit squares from column \(l_i\) to column \(r_i\) are part of the polyomino. In other words, there are \(r_i - l_i + 1\) unit squares that are part of the polyomino in the \(i\)-th row: \((i, l_i), (i, l_i + 1), \ldots, (i, r_i-1), (i, r_i)\).Two polyominoes are congruent if and only if you can make them fit exactly on top of each other by translating the polyominoes. Note that you are not allowed to rotate or reflect the polyominoes. Determine whether it is possible to partition the given convex polyomino into two disjoint connected polyominoes that are congruent to each other. The following examples illustrate a valid partition of each of the two convex polyominoes shown above: The partitioned polyominoes do not need to be convex, and each unit square should belong to exactly one of the two partitioned polyominoes.\(^{\text{∗}}\)A polyomino is connected if and only if for every two unit squares \(u \neq v\) that are part of the polyomino, there exists a sequence of distinct squares \(s_1, s_2, \ldots, s_k\), such that \(s_1 = u\), \(s_k = v\), \(s_i\) are all part of the polyomino, and \(s_i, s_{i+1}\) share an edge for each \(1 \le i \le k - 1\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(1\le n\le 2\cdot 10^5\)) — the number of rows of the polyomino.The \(i\)-th of the next \(n\) lines contains two integers \(l_i\) and \(r_i\) (\(1\le l_i\le r_i\le 10^9\)) — the range of columns that are part of the polyomino in the \(i\)-th row.It is guaranteed that the area of the polyomino is even. In other words, \(\sum_{i=1}^n r_i - l_i + 1\equiv 0\pmod{2}\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print a single line containing either ""YES"" or ""NO"", representing whether or not the polyomino can be partitioned as described in the problem.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
The first and second test cases are the polyominoes depicted in the problem statement and can be partitioned as shown.The polyomino in the third test case, shown below, can be shown to be impossible to partition. None of the following partitions are valid: The partition on the left does not use polyominoes that are translations of each other, and the partition on the right does not use connected polyominoes.The polyomino in the fourth test case, shown below, can be shown to be impossible to partition. Note that while you can partition it into two \(1 \times 2\) rectangles, these rectangles are not translations of each other.
Input: 721 22 344 42 41 41 231 21 22 321 33 321 32 231 21 31 348 96 86 85 6 | Output: YES YES NO NO NO NO YES
Master
5
1,742
688
327
20
2,117
H
2117H
H. Incessant Rain
2,500
data structures; divide and conquer; sortings
Note the unusual memory limit.Silver Wolf gives you an array \(a\) of length \(n\) and \(q\) queries. In each query, she replaces an element in \(a\). After each query, she asks you to output the maximum integer \(k\) such that there exists an integer \(x\) such that it is the \(k\)-majority of a subarray\(^{\text{∗}}\) of \(a\).An integer \(y\) is the \(k\)-majority of array \(b\) if \(y\) appears at least \(\lfloor \frac{|b|+1}{2} \rfloor +k\) times in \(b\), where \(|b|\) represents the length of \(b\). Note that \(b\) may not necessarily have a \(k\)-majority.\(^{\text{∗}}\)An array \(b\) is a subarray of an array \(a\) if \(b\) can be obtained from \(a\) by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
The first line contains an integer \(t\) (\(1 \leq t \leq 10^4\)) — the number of test cases.The first line of each test case contains two integers \(n\) and \(q\) (\(1 \leq n, q \leq 3 \cdot 10^5\)) — the length of \(a\) and the number of queries.The following line contains \(n\) space-separated integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq n\)). The following \(q\) lines contain two integers \(i\) and \(x\), denoting the query that replaces \(a_i\) with \(x\) (\(1 \leq i, x \leq n\)).It is guaranteed that the sum of \(n\) and the sum of \(q\) over all test cases does not exceed \(3 \cdot 10^5\).
For each test case, output the answer to all queries on a single new line, separated by a space.
Input: 25 51 2 3 4 53 41 42 44 32 37 83 2 3 3 2 2 32 35 36 33 44 47 46 42 4 | Output: 1 1 2 1 0 2 2 3 2 1 1 1 2
Expert
3
805
612
96
21
290
F
290F
F. Greedy Petya
2,800
*special; dfs and similar; graphs; greedy
Petya is an unexperienced programming contestant. Recently he has come across the following problem:You are given a non-directed graph which consists of n nodes and m edges. Your task is to determine whether the graph contains a Hamiltonian path.Petya wrote a quick bug-free code which he believes solves this problem. After that Petya decided to give this problem for April Fools Day contest. Unfortunately, Petya might have made a mistake, and it's quite possible that his algorithm is wrong. But this isn't a good excuse to leave the contest without submitting this problem, is it?
The first line contains two integers n, m (1 ≤ n ≤ 20; 0 ≤ m ≤ 400). Next m lines contain pairs of integers vi, ui (1 ≤ vi, ui ≤ n).
Follow the format of Petya's code output.
Input: 2 31 22 11 1 | Output: Yes
Master
4
584
132
41
2
659
E
659E
E. New Reform
1,600
data structures; dfs and similar; dsu; graphs; greedy
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000). Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road.It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.
Print a single integer — the minimum number of separated cities after the reform.
In the first sample the following road orientation is allowed: , , .The second sample: , , , , .The third sample: , , , , .
Input: 4 32 11 34 3 | Output: 1
Medium
5
825
551
81
6