id
stringlengths
6
10
question
stringlengths
29
13k
language
stringclasses
1 value
seed_125
"This problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" β€” people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy. Input The only line of the input contains an integer between 1 and 5, inclusive. All tests for this problem are different. The contents of the test case doesn't need to be equal to its index. Output The only line of the output contains an integer between 1 and 3, inclusive. Examples Note This problem has no samples, since there so few test cases.
Python
seed_126
"Time," Mino thinks aloud. "What?" "Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this." "And what are you recording?" "You see it, tide. Everything has its own period, and I think I've figured out this one," says Mino with confidence. Doubtfully, Kanno peeks at Mino's records. The records are expressed as a string $s$ of characters '0', '1' and '.', where '0' denotes a low tide, '1' denotes a high tide, and '.' denotes an unknown one (either high or low). You are to help Mino determine whether it's possible that after replacing each '.' independently with '0' or '1', a given integer $p$ is not a period of the resulting string. In case the answer is yes, please also show such a replacement to Mino. In this problem, a positive integer $p$ is considered a period of string $s$, if for all $1 \leq i \leq \lvert s \rvert - p$, the $i$-th and $(i + p)$-th characters of $s$ are the same. Here $\lvert s \rvert$ is the length of $s$. Input The first line contains two space-separated integers $n$ and $p$ ($1 \leq p \leq n \leq 2000$)Β β€” the length of the given string and the supposed period, respectively. The second line contains a string $s$ of $n$ charactersΒ β€” Mino's records. $s$ only contains characters '0', '1' and '.', and contains at least one '.' character. Output Output one lineΒ β€” if it's possible that $p$ is not a period of the resulting string, output any one of such strings; otherwise output "No" (without quotes, you can print letters in any case (upper or lower)). Examples Input 10 7 1.0.1.0.1. Output 1000100010 Input 10 6 1.0.1.1000 Output 1001101000 Input 10 9 1........1 Output No In the first example, $7$ is not a period of the resulting string because the $1$-st and $8$-th characters of it are different. In the second example, $6$ is not a period of the resulting string because the $4$-th and $10$-th characters of it are different. In the third example, $9$ is always a period because the only constraint that the first and last characters are the same is already satisfied. Note that there are multiple acceptable answers for the first two examples, you can print any of them.
Python
seed_127
"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino. "See? The clouds are coming." Kanno gazes into the distance. "That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $0$. There are $n$ clouds floating in the sky. Each cloud has the same length $l$. The $i$-th initially covers the range of $(x_i, x_i + l)$ (endpoints excluded). Initially, it moves at a velocity of $v_i$, which equals either $1$ or $-1$. Furthermore, no pair of clouds intersect initially, that is, for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$. With a wind velocity of $w$, the velocity of the $i$-th cloud becomes $v_i + w$. That is, its coordinate increases by $v_i + w$ during each unit of time. Note that the wind can be strong and clouds can change their direction. You are to help Mino count the number of pairs $(i, j)$ ($i < j$), such that with a proper choice of wind velocity $w$ not exceeding $w_\mathrm{max}$ in absolute value (possibly negative and/or fractional), the $i$-th and $j$-th clouds both cover the moon at the same future moment. This $w$ doesn't need to be the same across different pairs. Input The first line contains three space-separated integers $n$, $l$, and $w_\mathrm{max}$ ($1 \leq n \leq 10^5$, $1 \leq l, w_\mathrm{max} \leq 10^8$)Β β€” the number of clouds, the length of each cloud and the maximum wind speed, respectively. The $i$-th of the following $n$ lines contains two space-separated integers $x_i$ and $v_i$ ($-10^8 \leq x_i \leq 10^8$, $v_i \in \{-1, 1\}$)Β β€” the initial position and the velocity of the $i$-th cloud, respectively. The input guarantees that for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$. Output Output one integerΒ β€” the number of unordered pairs of clouds such that it's possible that clouds from each pair cover the moon at the same future moment with a proper choice of wind velocity $w$. Examples Input 5 1 2 -2 1 2 1 3 -1 5 -1 7 -1 Output 4 Input 4 10 1 -20 1 -10 -1 0 1 10 -1 Output 1 In the first example, the initial positions and velocities of clouds are illustrated below. The pairs are: - $(1, 3)$, covering the moon at time $2.5$ with $w = -0.4$; - $(1, 4)$, covering the moon at time $3.5$ with $w = -0.6$; - $(1, 5)$, covering the moon at time $4.5$ with $w = -0.7$; - $(2, 5)$, covering the moon at time $2.5$ with $w = -2$. Below is the positions of clouds at time $2.5$ with $w = -0.4$. At this moment, the $1$-st and $3$-rd clouds both cover the moon. In the second example, the only pair is $(1, 4)$, covering the moon at time $15$ with $w = 0$. Note that all the times and wind velocities given above are just examples among infinitely many choices.
Python
seed_129
"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme." "Little Alena got an array as a birthday present..." The array *b* of length *n* is obtained from the array *a* of length *n* and two integers *l* and *r*Β (*l*<=≀<=*r*) using the following procedure: *b*1<==<=*b*2<==<=*b*3<==<=*b*4<==<=0. For all 5<=≀<=*i*<=≀<=*n*: - *b**i*<==<=0 if *a**i*,<=*a**i*<=-<=1,<=*a**i*<=-<=2,<=*a**i*<=-<=3,<=*a**i*<=-<=4<=&gt;<=*r* and *b**i*<=-<=1<==<=*b**i*<=-<=2<==<=*b**i*<=-<=3<==<=*b**i*<=-<=4<==<=1 - *b**i*<==<=1 if *a**i*,<=*a**i*<=-<=1,<=*a**i*<=-<=2,<=*a**i*<=-<=3,<=*a**i*<=-<=4<=&lt;<=*l* and *b**i*<=-<=1<==<=*b**i*<=-<=2<==<=*b**i*<=-<=3<==<=*b**i*<=-<=4<==<=0 - *b**i*<==<=*b**i*<=-<=1 otherwise You are given arrays *a* and *b*' of the same length. Find two integers *l* and *r*Β (*l*<=≀<=*r*), such that applying the algorithm described above will yield an array *b* equal to *b*'. It's guaranteed that the answer exists. Input The first line of input contains a single integer *n* (5<=≀<=*n*<=≀<=105)Β β€” the length of *a* and *b*'. The second line of input contains *n* space separated integers *a*1,<=...,<=*a**n* (<=-<=109<=≀<=*a**i*<=≀<=109)Β β€” the elements of *a*. The third line of input contains a string of *n* characters, consisting of 0 and 1Β β€” the elements of *b*'. Note that they are not separated by spaces. Output Output two integers *l* and *r*Β (<=-<=109<=≀<=*l*<=≀<=*r*<=≀<=109), conforming to the requirements described above. If there are multiple solutions, output any of them. It's guaranteed that the answer exists. Examples Input 5 1 2 3 4 5 00001 Output 6 15 Input 10 -10 -9 -8 -7 -6 6 7 8 9 10 0000111110 Output -5 5 In the first test case any pair of *l* and *r* pair is valid, if 6 ≀ *l* ≀ *r* ≀ 10<sup class="upper-index">9</sup>, in that case *b*<sub class="lower-index">5</sub> = 1, because *a*<sub class="lower-index">1</sub>, ..., *a*<sub class="lower-index">5</sub> &lt; *l*.
Python
seed_130
"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme." "Little Alena got an array as a birthday present..." The array b of length n is obtained from the array a of length n and two integers l and r (l ≀ r) using the following procedure: b1 = b2 = b3 = b4 = 0. For all 5 ≀ i ≀ n: * bi = 0 if ai, ai - 1, ai - 2, ai - 3, ai - 4 > r and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 1 * bi = 1 if ai, ai - 1, ai - 2, ai - 3, ai - 4 < l and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 0 * bi = bi - 1 otherwise You are given arrays a and b' of the same length. Find two integers l and r (l ≀ r), such that applying the algorithm described above will yield an array b equal to b'. It's guaranteed that the answer exists. Input The first line of input contains a single integer n (5 ≀ n ≀ 105) β€” the length of a and b'. The second line of input contains n space separated integers a1, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of a. The third line of input contains a string of n characters, consisting of 0 and 1 β€” the elements of b'. Note that they are not separated by spaces. Output Output two integers l and r ( - 109 ≀ l ≀ r ≀ 109), conforming to the requirements described above. If there are multiple solutions, output any of them. It's guaranteed that the answer exists. Examples Input 5 1 2 3 4 5 00001 Output 6 15 Input 10 -10 -9 -8 -7 -6 6 7 8 9 10 0000111110 Output -5 5 Note In the first test case any pair of l and r pair is valid, if 6 ≀ l ≀ r ≀ 109, in that case b5 = 1, because a1, ..., a5 < l.
Python
seed_131
"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme." "Little Alena got an array as a birthday present..." The array b of length n is obtained from the array a of length n and two integers l and rΒ (l ≀ r) using the following procedure: b1 = b2 = b3 = b4 = 0. For all 5 ≀ i ≀ n: - bi = 0 if ai, ai - 1, ai - 2, ai - 3, ai - 4 > r and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 1 - bi = 1 if ai, ai - 1, ai - 2, ai - 3, ai - 4 < l and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 0 - bi = bi - 1 otherwise You are given arrays a and b' of the same length. Find two integers l and rΒ (l ≀ r), such that applying the algorithm described above will yield an array b equal to b'. It's guaranteed that the answer exists. Input The first line of input contains a single integer n (5 ≀ n ≀ 105)Β β€” the length of a and b'. The second line of input contains n space separated integers a1, ..., an ( - 109 ≀ ai ≀ 109)Β β€” the elements of a. The third line of input contains a string of n characters, consisting of 0 and 1Β β€” the elements of b'. Note that they are not separated by spaces. Output Output two integers l and rΒ ( - 109 ≀ l ≀ r ≀ 109), conforming to the requirements described above. If there are multiple solutions, output any of them. It's guaranteed that the answer exists. Examples Input 5 1 2 3 4 5 00001 Output 6 15 Input 10 -10 -9 -8 -7 -6 6 7 8 9 10 0000111110 Output -5 5 Note In the first test case any pair of l and r pair is valid, if 6 ≀ l ≀ r ≀ 109, in that case b5 = 1, because a1, ..., a5 < l.
Python
seed_132
"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme." "Little Alena got an array as a birthday present..." The array b of length n is obtained from the array a of length n and two integers l and rΒ (l ≀ r) using the following procedure: b_1 = b_2 = b_3 = b_4 = 0. For all 5 ≀ i ≀ n: b_{i} = 0 if a_{i}, a_{i} - 1, a_{i} - 2, a_{i} - 3, a_{i} - 4 > r and b_{i} - 1 = b_{i} - 2 = b_{i} - 3 = b_{i} - 4 = 1 b_{i} = 1 if a_{i}, a_{i} - 1, a_{i} - 2, a_{i} - 3, a_{i} - 4 < l and b_{i} - 1 = b_{i} - 2 = b_{i} - 3 = b_{i} - 4 = 0 b_{i} = b_{i} - 1 otherwise You are given arrays a and b' of the same length. Find two integers l and rΒ (l ≀ r), such that applying the algorithm described above will yield an array b equal to b'. It's guaranteed that the answer exists. -----Input----- The first line of input contains a single integer n (5 ≀ n ≀ 10^5)Β β€” the length of a and b'. The second line of input contains n space separated integers a_1, ..., a_{n} ( - 10^9 ≀ a_{i} ≀ 10^9)Β β€” the elements of a. The third line of input contains a string of n characters, consisting of 0 and 1Β β€” the elements of b'. Note that they are not separated by spaces. -----Output----- Output two integers l and rΒ ( - 10^9 ≀ l ≀ r ≀ 10^9), conforming to the requirements described above. If there are multiple solutions, output any of them. It's guaranteed that the answer exists. -----Examples----- Input 5 1 2 3 4 5 00001 Output 6 15 Input 10 -10 -9 -8 -7 -6 6 7 8 9 10 0000111110 Output -5 5 -----Note----- In the first test case any pair of l and r pair is valid, if 6 ≀ l ≀ r ≀ 10^9, in that case b_5 = 1, because a_1, ..., a_5 < l.
Python
seed_133
"What are your shoe sizes?" Suddenly, the doctor asked me when I met him for the first time. "It's 23.5" "Oh, that's a really nice number. It's 2 to the 4th power plus 2 to the 2nd power, 2 to the 1st power, 2 to the 0th power, and 2 to the 1st power." Then the doctor asked. "You, how tall are you?" "Yes, it's 158.1." He folded his arms and closed his eyes. After a while of silence, I opened my mouth. "Nah ~" After that, during the time I spent together, I gradually became able to understand the behavior of the doctor. First, I say the real number at the request of the doctor. If the real number is represented by a binary number with no more than 8 digits for the integer part and no more than 4 digits for the decimal part, he is happy to say the result of the conversion to binary. If not, it will sadly yell "Nah ~". This repeats until I say a negative real number. By the way, as he got older, it became more and more difficult to make long calculations. Therefore, please make a program for you to input real numbers and convert / output them to binary numbers on your behalf. However, if the binary representation does not fit within the limit number of digits (integer part within 8 digits + decimal part within 4 digits), output NA (half-width alphabetic characters). The input real number shall fit within 8 digits of the integer part and within 4 digits of the decimal part, and the binary representation to be output should be output with 8 digits of the integer part and 4 digits of the decimal part. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single negative real line. One real number n is given to one row for each dataset. The number of datasets does not exceed 1200. Output Outputs the conversion result to binary number for each input data set. Example Input 23.5 158.1 -1.0 Output 00010111.1000 NA
Python
seed_134
"What do you know about happiness?" β€” Yoda Chef is happy only if three conditions hold: - Chef finished cooking a delicious meal - Chef got AC for a programming problem with an almost correct code - Chef got a new problem with a sequence of integers Today, all three conditions are satisfied. Chef would like you to feel his happiness and provide him with a solution for this new problem with a sequence of integers. The problem is as follows. You are given a sequence $A_1, A_2, \dots, A_N$. You need to determine if it is possible to choose two indices $i$ and $j$ such that $A_i \neq A_j$, but $A_{A_i}$ = $A_{A_j}$. (If it was possible, Chef would be truly happy.) -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing the string "Truly Happy" if it is possible to choose required indices or "Poor Chef" otherwise. -----Constraints----- - $1 \le T \le 1,000$ - $1 \le N \le 10^5$ - $1 \le A_i \le N$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $2 \cdot 10^5$ -----Subtasks----- Subtask #1 (27 points): $1 \le N \le 1,000$ Subtask #2 (73 points): original constraints -----Example Input----- 4 4 1 1 2 3 4 2 1 3 3 5 5 4 4 3 1 5 3 2 1 1 4 -----Example Output----- Truly Happy Poor Chef Poor Chef Truly Happy -----Explanation----- Example case 1: Chef is truly happy because $A_{A_3} = A_{A_1}$ and $A_3 \neq A_1$. Example case 2: There is no pair of indices which would make Chef truly happy. For instance, $A_{A_3} = A_{A_4}$, but $A_3 = A_4$,
Python
seed_135
"You must lift the dam. With a lever. I will give it to you. You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them. Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task. You are given a positive integer $n$, and an array $a$ of positive integers. The task is to calculate the number of such pairs $(i,j)$ that $i<j$ and $a_i$ $\&$ $a_j \ge a_i \oplus a_j$, where $\&$ denotes the bitwise AND operation, and $\oplus$ denotes the bitwise XOR operation. Danik has solved this task. But can you solve it? -----Input----- Each test contains multiple test cases. The first line contains one positive integer $t$ ($1 \le t \le 10$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $n$ ($1 \le n \le 10^5$)Β β€” length of the array. The second line contains $n$ positive integers $a_i$ ($1 \le a_i \le 10^9$)Β β€” elements of the array. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For every test case print one non-negative integerΒ β€” the answer to the problem. -----Example----- Input 5 5 1 4 3 7 10 3 1 1 1 4 6 2 5 3 2 2 4 1 1 Output 1 3 2 0 0 -----Note----- In the first test case there is only one pair: $(4,7)$: for it $4$ $\&$ $7 = 4$, and $4 \oplus 7 = 3$. In the second test case all pairs are good. In the third test case there are two pairs: $(6,5)$ and $(2,3)$. In the fourth test case there are no good pairs.
Python
seed_139
# A History Lesson Soundex is an interesting phonetic algorithm developed nearly 100 years ago for indexing names as they are pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling. Reference: https://en.wikipedia.org/wiki/Soundex # Preface I first read about Soundex over 30 years ago. At the time it seemed to me almost like A.I. that you could just type in somebody's name the way it sounded and there was still a pretty good chance it could match the correct person record. That was about the same year as the first "Terminator" movie so it was easy for me to put 2 and 2 together and conclude that Arnie must have had some kind of futuristic Soundex chip in his titanium skull helping him to locate ```Serah Coner```... or was it ```Sarh Connor```... or maybe ```Sayra Cunnarr```... :-) # Task In this Kata you will encode strings using a Soundex variation called "American Soundex" using the following (case insensitive) steps: * Save the first letter. Remove all occurrences of ```h``` and ```w``` except first letter. * Replace all consonants (include the first letter) with digits as follows: * ```b```, ```f```, ```p```, ```v``` = 1 * ```c```, ```g```, ```j```, ```k```, ```q```, ```s```, ```x```, ```z``` = 2 * ```d```, ```t``` = 3 * ```l``` = 4 * ```m```, ```n``` = 5 * ```r``` = 6 * Replace all adjacent same digits with one digit. * Remove all occurrences of ```a```, ```e```, ```i```, ```o```, ```u```, ```y``` except first letter. * If first symbol is a digit replace it with letter saved on step 1. * Append 3 zeros if result contains less than 3 digits. Remove all except first letter and 3 digits after it ## Input A space separated string of one or more names. E.g. ```Sarah Connor``` ## Output Space separated string of equivalent Soundex codes (the first character of each code must be uppercase). E.g. ```S600 C560```
Python
seed_141
# A History Lesson The Pony Express was a mail service operating in the US in 1859-60. It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, before it was made obsolete by the transcontinental telegraph. # How it worked There were a number of *stations*, where: * The rider switched to a fresh horse and carried on, or * The mail bag was handed over to the next rider # Kata Task `stations` is a list/array of distances (miles) from one station to the next along the Pony Express route. Implement the `riders` method/function, to return how many riders are necessary to get the mail from one end to the other. ## Missing rider In this version of the Kata a rider may go missing. In practice, this could be for a number of reasons - a lame horse, an accidental fall, foul play... After some time, the rider's absence would be noticed at the **next** station, so the next designated rider from there would have to back-track the mail route to look for his missing colleague. The missing rider is then safely escorted back to the station he last came from, and the mail bags are handed to his rescuer (or another substitute rider if necessary). `stationX` is the number (2..N) of the station where the rider's absence was noticed. # Notes * Each rider travels as far as he can, but never more than 100 miles. # Example GIven * `stations = [43, 23, 40, 13]` * `stationX = 4` So `S1` ... ... 43 ... ... `S2` ... ... 23 ... ... `S3` ... ... 40 ... ... `S4` ... ... 13 ... ... `S5` * Rider 1 gets as far as Station S3 * Rider 2 (at station S3) takes mail bags from Rider 1 * Rider 2 never arrives at station S4 * Rider 3 goes back to find what happened to Rider 2 * Rider 2 and Rider 3 return together back to Station S3 * Rider 3 takes mail bags from Rider 2 * Rider 3 completes the journey to Station S5 **Answer:** 3 riders *Good Luck. DM.* --- See also * The Pony Express * The Pony Express (missing rider)
Python
seed_142
# A History Lesson The Pony Express was a mail service operating in the US in 1859-60. It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, before it was made obsolete by the [transcontinental telegraph](https://en.wikipedia.org/wiki/First_transcontinental_telegraph). # How it worked There were a number of *stations*, where: * The rider switched to a fresh horse and carried on, or * The mail bag was handed over to the next rider # Kata Task `stations` is a list/array of distances (miles) from one station to the next along the Pony Express route. Implement the `riders` method/function, to return how many riders are necessary to get the mail from one end to the other. **NOTE:** Each rider travels as far as he can, but never more than 100 miles. --- *Good Luck. DM.* --- See also * The Pony Express * The Pony Express (missing rider)
Python
seed_143
# A Plus B Borcsa has two arrays, each of them containing $N$ non-negative integers. The numbers in the first array are $A[0], A[1], \ldots, A[N-1]$ and the numbers in the second array are $B[0], B[1], \ldots, B[N-1]$. The numbers in both arrays are in increasing order, that is, * $A[0] \le A[1] \le \ldots \le A[N-1]$, and * $B[0] \le B[1] \le \ldots \le B[N-1]$. Borcsa really likes arithmetical addition, so for each $i$ from $0$ to $N-1$ and for each $j$ from $0$ to $N-1$, inclusive, she computed the sum $A[i] + B[j]$. Let array $C$ contain all $N^2$ sums computed by Borcsa, sorted in increasing order. Your task is to find the first $N$ values in $C$. ## Implementation Details You should implement the following procedure: ``` int[] smallest_sums(int N, int[] A, int[] B) ``` * $N$: the number of elements in each array. * $A$, $B$: arrays of length $N$ containing non-negative integers sorted in increasing order. * This procedure should return an array of length $N$ containing the $N$ smallest sums obtained by adding an element from $A$ and an element from $B$. The array should contain the sums in increasing order. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` smallest_sums(2, [0, 2], [1, 4]) ``` In this case, $N = 2$. There are $N^2 = 4$ sums computed by Borcsa: * $0 + 1 = 1$ * $0 + 4 = 4$ * $2 + 1 = 3$ * $2 + 4 = 6$ Array $C$ contains these sums sorted in increasing order, that is, $C = [1, 3, 4, 6]$. The $N = 2$ smallest elements in $C$ are $1$ and $3$. Therefore, the procedure should return the array $[1, 3]$. ### Example 2 Consider the following call: ``` smallest_sums(3, [0, 2, 2], [3, 5, 6]) ``` The $9$ pairwise sums (in increasing order) are $3, 5, 5, 5, 6, 7, 7, 8, 8$. The procedure should return the $3$ smallest sums, that is, the array $[3, 5, 5]$. ## Constraints * $1 \le N \le 100\,000$ * $0 \le A[i] \le 10^9$ (for each $i$ such that $0 \le i < N$) * $0 \le B[j] \le 10^9$ (for each $j$ such that $0 \le j < N$) * $A$ and $B$ are sorted in increasing order. ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N$ * line $2$: $A[0] \; A[1] \; \ldots \; A[N-1]$ * line $3$: $B[0] \; B[1] \; \ldots \; B[N-1]$ Let the elements of the array returned by `smallest_sums` be $c[0], c[1], \ldots, c[n-1]$ for some non-negative $n$. The output of the sample grader is in the following format: * line $1$: $c[0] \; c[1] \; \ldots \; c[n-1]$
Python
seed_144
# A Plus B Borcsa has two arrays, each of them containing $N$ non-negative integers. The numbers in the first array are $A[0], A[1], \ldots, A[N-1]$ and the numbers in the second array are $B[0], B[1], \ldots, B[N-1]$. The numbers in both arrays are in increasing order, that is, * $A[0] \le A[1] \le \ldots \le A[N-1]$, and * $B[0] \le B[1] \le \ldots \le B[N-1]$. Borcsa really likes arithmetical addition, so for each $i$ from $0$ to $N-1$ and for each $j$ from $0$ to $N-1$, inclusive, she computed the sum $A[i] + B[j]$. Let array $C$ contain all $N^2$ sums computed by Borcsa, sorted in increasing order. Your task is to find the first $N$ values in $C$. ## Implementation Details You should implement the following procedure: ``` int[] smallest_sums(int N, int[] A, int[] B) ``` * $N$: the number of elements in each array. * $A$, $B$: arrays of length $N$ containing non-negative integers sorted in increasing order. * This procedure should return an array of length $N$ containing the $N$ smallest sums obtained by adding an element from $A$ and an element from $B$. The array should contain the sums in increasing order. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` smallest_sums(2, [0, 2], [1, 4]) ``` In this case, $N = 2$. There are $N^2 = 4$ sums computed by Borcsa: * $0 + 1 = 1$ * $0 + 4 = 4$ * $2 + 1 = 3$ * $2 + 4 = 6$ Array $C$ contains these sums sorted in increasing order, that is, $C = [1, 3, 4, 6]$. The $N = 2$ smallest elements in $C$ are $1$ and $3$. Therefore, the procedure should return the array $[1, 3]$. ### Example 2 Consider the following call: ``` smallest_sums(3, [0, 2, 2], [3, 5, 6]) ``` The $9$ pairwise sums (in increasing order) are $3, 5, 5, 5, 6, 7, 7, 8, 8$. The procedure should return the $3$ smallest sums, that is, the array $[3, 5, 5]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le N \le 100$ * $0 \le A[i] \le 10^9$ (for each $i$ such that $0 \le i < N$) * $0 \le B[j] \le 10^9$ (for each $j$ such that $0 \le j < N$) * $A$ and $B$ are sorted in increasing order. ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N$ * line $2$: $A[0] \; A[1] \; \ldots \; A[N-1]$ * line $3$: $B[0] \; B[1] \; \ldots \; B[N-1]$ Let the elements of the array returned by `smallest_sums` be $c[0], c[1], \ldots, c[n-1]$ for some non-negative $n$. The output of the sample grader is in the following format: * line $1$: $c[0] \; c[1] \; \ldots \; c[n-1]$
Python
seed_146
# A Plus B Borcsa has two arrays, each of them containing $N$ non-negative integers. The numbers in the first array are $A[0], A[1], \ldots, A[N-1]$ and the numbers in the second array are $B[0], B[1], \ldots, B[N-1]$. The numbers in both arrays are in increasing order, that is, * $A[0] \le A[1] \le \ldots \le A[N-1]$, and * $B[0] \le B[1] \le \ldots \le B[N-1]$. Borcsa really likes arithmetical addition, so for each $i$ from $0$ to $N-1$ and for each $j$ from $0$ to $N-1$, inclusive, she computed the sum $A[i] + B[j]$. Let array $C$ contain all $N^2$ sums computed by Borcsa, sorted in increasing order. Your task is to find the first $N$ values in $C$. ## Implementation Details You should implement the following procedure: ``` int[] smallest_sums(int N, int[] A, int[] B) ``` * $N$: the number of elements in each array. * $A$, $B$: arrays of length $N$ containing non-negative integers sorted in increasing order. * This procedure should return an array of length $N$ containing the $N$ smallest sums obtained by adding an element from $A$ and an element from $B$. The array should contain the sums in increasing order. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` smallest_sums(2, [0, 2], [1, 4]) ``` In this case, $N = 2$. There are $N^2 = 4$ sums computed by Borcsa: * $0 + 1 = 1$ * $0 + 4 = 4$ * $2 + 1 = 3$ * $2 + 4 = 6$ Array $C$ contains these sums sorted in increasing order, that is, $C = [1, 3, 4, 6]$. The $N = 2$ smallest elements in $C$ are $1$ and $3$. Therefore, the procedure should return the array $[1, 3]$. ### Example 2 Consider the following call: ``` smallest_sums(3, [0, 2, 2], [3, 5, 6]) ``` The $9$ pairwise sums (in increasing order) are $3, 5, 5, 5, 6, 7, 7, 8, 8$. The procedure should return the $3$ smallest sums, that is, the array $[3, 5, 5]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le N \le 2\,500$ * $0 \le A[i] \le 10^9$ (for each $i$ such that $0 \le i < N$) * $0 \le B[j] \le 10^9$ (for each $j$ such that $0 \le j < N$) * $A$ and $B$ are sorted in increasing order. ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N$ * line $2$: $A[0] \; A[1] \; \ldots \; A[N-1]$ * line $3$: $B[0] \; B[1] \; \ldots \; B[N-1]$ Let the elements of the array returned by `smallest_sums` be $c[0], c[1], \ldots, c[n-1]$ for some non-negative $n$. The output of the sample grader is in the following format: * line $1$: $c[0] \; c[1] \; \ldots \; c[n-1]$
Python
seed_148
# A wolf in sheep's clothing Wolves have been reintroduced to Great Britain. You are a sheep farmer, and are now plagued by wolves which pretend to be sheep. Fortunately, you are good at spotting them. Warn the sheep in front of the wolf that it is about to be eaten. Remember that you are standing **at the front of the queue** which is at the end of the array: ``` [sheep, sheep, sheep, sheep, sheep, wolf, sheep, sheep] (YOU ARE HERE AT THE FRONT OF THE QUEUE) 7 6 5 4 3 2 1 ``` If the wolf is the closest animal to you, return `"Pls go away and stop eating my sheep"`. Otherwise, return `"Oi! Sheep number N! You are about to be eaten by a wolf!"` where `N` is the sheep's position in the queue. **Note:** there will always be exactly one wolf in the array. ## Examples ```python warn_the_sheep(["sheep", "sheep", "sheep", "wolf", "sheep"]) == 'Oi! Sheep number 1! You are about to be eaten by a wolf!' warn_the_sheep(['sheep', 'sheep', 'wolf']) == 'Pls go away and stop eating my sheep' ```
Python
seed_149
# ARCHERY ### **Problem Description** An archery tournament is held according to the following rules. There are **N** targets arranged in a line and numbered from 1 to N inclusive. There are also **2Β·N** archers. At any time, there are two archers on each target. **Each round**: - Two archers on each target compete, winner and loser determined. - Rearrangement: - Winners on targets 2 to N β†’ move to the left (to targets 1 to N-1) - Losers on targets 2 to N + winner on target 1 β†’ stay on the same target - Loser on target 1 β†’ moves to target N The tournament continues for **R** rounds, with `R β‰₯ 2Β·N`. You are the **only archer** to arrive on time; the others have already arranged themselves in line. After inserting yourself, you know the assignment rule (2 archers per target from left to right). Archers are ranked by skill (lower = better). No two archers have the same rank. When two compete, the one with lower rank wins. Your goal: insert yourself into the line in such a way that you **finish** on the **smallest numbered target possible**. If tied, prefer the one starting on a **larger target**. --- ### **Task** Write a program that, given: - Your rank, - The ranks of the other archers (in order), - Total number of targets N, - Number of rounds R, determines on which target you should **start** the tournament to achieve the best final target (as small as possible). --- ### **Constraints** - 1 ≀ N ≀ 200,000 - 2Β·N ≀ R ≀ 1,000,000,000 - 1 ≀ Sk ≀ 2Β·N (ranks, distinct) --- ### **Input Format** ``` N R your_rank rank_1 rank_2 ... rank_(2N - 1) ``` --- ### **Output Format** Single integer: the target number (1 to N) where you should **start**. --- ### **Examples** #### Sample Input 1 ``` 4 8 7 4 2 6 5 8 1 3 ``` #### Output ``` 3 ``` *Explanation:* You are the second worst. Target 3 allows you to beat someone and end up on a better target. --- #### Sample Input 2 ``` 4 9 2 1 5 8 3 4 7 6 ``` #### Output ``` 2 ``` *Explanation:* You are second best. Target 1 will hold the best archer the entire time. You will cycle and must start on target 2. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_151
# Amazing Robots ## Task You are the proud owner of two robots that are located in separate rectangular mazes. Square $(1, 1)$ in a maze is the square in the upper-left corner, which is the north-west corner. Maze $i$ $(i = 1, 2)$ has a set of $G_i \ (0 \leq G_i \leq 10)$ guards trying to capture the robots by patrolling back and forth on a straight patrol path. Your goal is to determine a sequence of commands such that the robots exit the mazes without either robot being captured by a guard. At the beginning of each minute, you broadcast the same command to both robots. Each command is a direction (north, south, east, or west). A robot moves one square in the direction of the command, unless the robot would collide with a wall, in which case the robot does not move for that minute. A robot exits the maze by walking out of it. A robot ignores commands after it has exited its maze. Guards move one square at the beginning of each minute, at the same time as the robots. Each guard begins at a given square facing a given direction and moves forward one square per minute until the guard has moved one fewer square than the number of squares in his patrol path. The guard then turns around instantaneously and walks in the opposite direction back to his starting square, where he turns around again and repeats his patrol path until each robot has exited its maze. A guard’s patrol will not require the guard to walk through walls or exit the maze. Although guard patrols may overlap, no two guards will ever collide: they will never occupy the same square at the end of a minute, and they will not exchange squares with each other during a minute. A guard in a maze will not start in the same square as the robot in that maze. A guard captures a robot if the guard occupies the same square at the end of a minute as the robot, or if the guard and the robot exchange squares with each other during a minute. Given two mazes (each no larger than $20 \times 20$) along with the initial square of each robot and the patrol paths of the guards in each maze, determine a sequence of commands for which the robots exit without being caught by the guards. Minimize the time it takes for the later robot to exit its maze. If the robots exit at different times, the time at which the earlier robot exited does not matter. ## Input: `robots.in` The first set of lines describes the first maze and its occupants. Subsequently, the second set of lines describes the second maze and its occupants. ## Input Format - The first line of input contains two space-separated integers, $R_1$ and $C_1$, the number of rows and columns in maze 1. - The next $R_1$ lines each contain $C_1$ characters specifying the maze layout. The robot's starting square is specified by an `X`. A `.` represents an open space and `#` represents a wall. Each maze will contain exactly one robot. - Following the maze layout is a single line with a single integer $G_1$, the number of guards in the first maze $(0 \leq G_1 \leq 10)$. - Each of the next $G_1$ lines describes a guard’s patrol as three integers and a character, separated by single spaces. The first two integers specify the row and column of the starting square of the guard. The third integer specifies the number of squares $(2 \ldots 4)$ in the guard's patrol path. The character specifies the initial direction the guard is facing: `N`, `S`, `E`, or `W` (north, south, east, and west, respectively). The description of the second maze follows the description of the first, in the same format but with potentially different values. ## Example Input: ``` 5 4 #### #X.# #..# #..# #### 1 1 4 2 W 4 4 #### #.## #X.# #### 0 ``` ## Output: `robots.out` The first line of the output should contain a single integer $K$ $(K \leq 10000)$, the number of commands for both robots to exit the maze without being captured. If such a sequence of commands exists, the shortest sequence will have no more than 10000 commands. The next $K$ lines are the sequence of commands, each containing a single character from the set \{`N`, `S`, `E`, `W`\}. If no such sequence exists, output a single line containing `-1`. Both robots should exit their mazes by the end of the commands. The last command should cause at least one of the robots to exit its maze. If multiple sequences of commands cause the robots to exit in the minimum time, any will be accepted. ## Example Output: ``` 8 E N E S S S S S ``` ## Constraints - **Running time:** 2 seconds of CPU - **Memory:** 64 MB ## Scoring No partial credit will be given on test cases for which no sequence of commands exists. Partial credit for other test cases will be given as described below. ### Correctness: 20% of points The output file for a test case is considered correct if it is correctly formatted, contains no more than 10000 commands, and the sequence of commands causes the robots to exit the mazes, with the last command causing at least one robot to exit its maze. ### Minimality: 80% of points The output file for a test case is considered minimal if it is correct and there is no shorter sequence of commands that is correct. A program whose sequence of commands is not minimal will receive no points for minimality. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_153
# Ancient Books The city of Tehran is home to the National Library of Iran. The main treasure of this library is located in a long hall with a row of \(n\) tables, labeled \(0\) through \(n - 1\) from left to right. On each table there is one ancient handwritten book being displayed. These books are ordered based on their ages, which makes it hard for the visitors to search for books by title. So, the library manager has decided to sort the books in alphabetical order of their titles. Aryan, a librarian, is going to do the job. He has created a list \(p\) of length \(n\), containing different integers from \(0\) to \(n - 1\). This list describes the changes needed to rearrange the books into alphabetical order: for all \(0 \leq i < n\), the book that is currently on table \(i\) should be moved to table \(p[i]\). Aryan starts sorting the books at table \(s\). He wants to return to the same table after finishing the job. Since the books are very valuable, he cannot carry more than one book at any time. While sorting the books Aryan will perform a sequence of actions. Each of those actions has to be one of the following: - If he is not carrying a book and there is a book on the table he is at, he can pick up this book. - If he is carrying a book and there is another book on the table he is at, he can switch the book he is carrying with the one on the table. - If he is carrying a book and he is at an empty table, he can put the book he is carrying on the table. - He can walk to any table. He may carry a single book while he does so. For all \(0 \leq i, j \leq n - 1\), the distance between tables \(i\) and \(j\) is precisely \(|j - i|\) meters. Your task is to compute the minimum total distance Aryan needs to walk in order to sort all the books. ## Implementation details You should implement the following procedure: ``` int64 minimum_walk(int[] p, int s) ``` - \(p\) is an array of length \(n\). The book that is on table \(i\) at the beginning should be taken by Aryan to table \(p[i]\) (for all \(0 \leq i < n\)). - \(s\) is the label of the table where Aryan is at the beginning, and where he should be after sorting the books. - This procedure should return the minimum total distance (in meters) Aryan has to walk in order to sort the books. ## Example ``` minimum_walk([0, 2, 3, 1], 0) ``` In this example, \(n = 4\) and Aryan is at table \(0\) at the beginning. He sorts the books as follows: - He walks to table \(1\) and picks up the book lying on it. This book should be put on table \(2\). - Then, he walks to table \(2\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(3\). - Then, he walks to table \(3\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(1\). - Then, he walks to table \(1\) and puts the book he is carrying on the table. - Finally, he walks back to table \(0\). Note that book on table \(0\) is already in the correct place, table \(0\), so Aryan does not have to pick it up. The total distance he walks in this solution is \(6\) meters. This is the optimal solution; hence, the procedure should return \(6\). ## Constraints - \(1 \leq n \leq 1,000,000\) - \(0 \leq s \leq n - 1\) - Array \(p\) contains \(n\) distinct integers between \(0\) and \(n - 1\), inclusive. ## Sample grader The sample grader reads the input in the following format: - Line 1: \(n \; s\) - Line 2: \(p[0] \; p[1] \; \ldots \; p[n - 1]\) The sample grader prints a single line containing the return value of `minimum_walk`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: n \leq 1000
Python
seed_154
# Ancient Books The city of Tehran is home to the National Library of Iran. The main treasure of this library is located in a long hall with a row of \(n\) tables, labeled \(0\) through \(n - 1\) from left to right. On each table there is one ancient handwritten book being displayed. These books are ordered based on their ages, which makes it hard for the visitors to search for books by title. So, the library manager has decided to sort the books in alphabetical order of their titles. Aryan, a librarian, is going to do the job. He has created a list \(p\) of length \(n\), containing different integers from \(0\) to \(n - 1\). This list describes the changes needed to rearrange the books into alphabetical order: for all \(0 \leq i < n\), the book that is currently on table \(i\) should be moved to table \(p[i]\). Aryan starts sorting the books at table \(s\). He wants to return to the same table after finishing the job. Since the books are very valuable, he cannot carry more than one book at any time. While sorting the books Aryan will perform a sequence of actions. Each of those actions has to be one of the following: - If he is not carrying a book and there is a book on the table he is at, he can pick up this book. - If he is carrying a book and there is another book on the table he is at, he can switch the book he is carrying with the one on the table. - If he is carrying a book and he is at an empty table, he can put the book he is carrying on the table. - He can walk to any table. He may carry a single book while he does so. For all \(0 \leq i, j \leq n - 1\), the distance between tables \(i\) and \(j\) is precisely \(|j - i|\) meters. Your task is to compute the minimum total distance Aryan needs to walk in order to sort all the books. ## Implementation details You should implement the following procedure: ``` int64 minimum_walk(int[] p, int s) ``` - \(p\) is an array of length \(n\). The book that is on table \(i\) at the beginning should be taken by Aryan to table \(p[i]\) (for all \(0 \leq i < n\)). - \(s\) is the label of the table where Aryan is at the beginning, and where he should be after sorting the books. - This procedure should return the minimum total distance (in meters) Aryan has to walk in order to sort the books. ## Example ``` minimum_walk([0, 2, 3, 1], 0) ``` In this example, \(n = 4\) and Aryan is at table \(0\) at the beginning. He sorts the books as follows: - He walks to table \(1\) and picks up the book lying on it. This book should be put on table \(2\). - Then, he walks to table \(2\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(3\). - Then, he walks to table \(3\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(1\). - Then, he walks to table \(1\) and puts the book he is carrying on the table. - Finally, he walks back to table \(0\). Note that book on table \(0\) is already in the correct place, table \(0\), so Aryan does not have to pick it up. The total distance he walks in this solution is \(6\) meters. This is the optimal solution; hence, the procedure should return \(6\). ## Constraints - \(1 \leq n \leq 1,000,000\) - \(0 \leq s \leq n - 1\) - Array \(p\) contains \(n\) distinct integers between \(0\) and \(n - 1\), inclusive. ## Sample grader The sample grader reads the input in the following format: - Line 1: \(n \; s\) - Line 2: \(p[0] \; p[1] \; \ldots \; p[n - 1]\) The sample grader prints a single line containing the return value of `minimum_walk`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: n \leq 1000 and s = 0
Python
seed_156
# Ancient Books The city of Tehran is home to the National Library of Iran. The main treasure of this library is located in a long hall with a row of \(n\) tables, labeled \(0\) through \(n - 1\) from left to right. On each table there is one ancient handwritten book being displayed. These books are ordered based on their ages, which makes it hard for the visitors to search for books by title. So, the library manager has decided to sort the books in alphabetical order of their titles. Aryan, a librarian, is going to do the job. He has created a list \(p\) of length \(n\), containing different integers from \(0\) to \(n - 1\). This list describes the changes needed to rearrange the books into alphabetical order: for all \(0 \leq i < n\), the book that is currently on table \(i\) should be moved to table \(p[i]\). Aryan starts sorting the books at table \(s\). He wants to return to the same table after finishing the job. Since the books are very valuable, he cannot carry more than one book at any time. While sorting the books Aryan will perform a sequence of actions. Each of those actions has to be one of the following: - If he is not carrying a book and there is a book on the table he is at, he can pick up this book. - If he is carrying a book and there is another book on the table he is at, he can switch the book he is carrying with the one on the table. - If he is carrying a book and he is at an empty table, he can put the book he is carrying on the table. - He can walk to any table. He may carry a single book while he does so. For all \(0 \leq i, j \leq n - 1\), the distance between tables \(i\) and \(j\) is precisely \(|j - i|\) meters. Your task is to compute the minimum total distance Aryan needs to walk in order to sort all the books. ## Implementation details You should implement the following procedure: ``` int64 minimum_walk(int[] p, int s) ``` - \(p\) is an array of length \(n\). The book that is on table \(i\) at the beginning should be taken by Aryan to table \(p[i]\) (for all \(0 \leq i < n\)). - \(s\) is the label of the table where Aryan is at the beginning, and where he should be after sorting the books. - This procedure should return the minimum total distance (in meters) Aryan has to walk in order to sort the books. ## Example ``` minimum_walk([0, 2, 3, 1], 0) ``` In this example, \(n = 4\) and Aryan is at table \(0\) at the beginning. He sorts the books as follows: - He walks to table \(1\) and picks up the book lying on it. This book should be put on table \(2\). - Then, he walks to table \(2\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(3\). - Then, he walks to table \(3\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(1\). - Then, he walks to table \(1\) and puts the book he is carrying on the table. - Finally, he walks back to table \(0\). Note that book on table \(0\) is already in the correct place, table \(0\), so Aryan does not have to pick it up. The total distance he walks in this solution is \(6\) meters. This is the optimal solution; hence, the procedure should return \(6\). ## Constraints - \(1 \leq n \leq 1,000,000\) - \(0 \leq s \leq n - 1\) - Array \(p\) contains \(n\) distinct integers between \(0\) and \(n - 1\), inclusive. ## Sample grader The sample grader reads the input in the following format: - Line 1: \(n \; s\) - Line 2: \(p[0] \; p[1] \; \ldots \; p[n - 1]\) The sample grader prints a single line containing the return value of `minimum_walk`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: no additional constraints
Python
seed_157
# Ancient Books The city of Tehran is home to the National Library of Iran. The main treasure of this library is located in a long hall with a row of \(n\) tables, labeled \(0\) through \(n - 1\) from left to right. On each table there is one ancient handwritten book being displayed. These books are ordered based on their ages, which makes it hard for the visitors to search for books by title. So, the library manager has decided to sort the books in alphabetical order of their titles. Aryan, a librarian, is going to do the job. He has created a list \(p\) of length \(n\), containing different integers from \(0\) to \(n - 1\). This list describes the changes needed to rearrange the books into alphabetical order: for all \(0 \leq i < n\), the book that is currently on table \(i\) should be moved to table \(p[i]\). Aryan starts sorting the books at table \(s\). He wants to return to the same table after finishing the job. Since the books are very valuable, he cannot carry more than one book at any time. While sorting the books Aryan will perform a sequence of actions. Each of those actions has to be one of the following: - If he is not carrying a book and there is a book on the table he is at, he can pick up this book. - If he is carrying a book and there is another book on the table he is at, he can switch the book he is carrying with the one on the table. - If he is carrying a book and he is at an empty table, he can put the book he is carrying on the table. - He can walk to any table. He may carry a single book while he does so. For all \(0 \leq i, j \leq n - 1\), the distance between tables \(i\) and \(j\) is precisely \(|j - i|\) meters. Your task is to compute the minimum total distance Aryan needs to walk in order to sort all the books. ## Implementation details You should implement the following procedure: ``` int64 minimum_walk(int[] p, int s) ``` - \(p\) is an array of length \(n\). The book that is on table \(i\) at the beginning should be taken by Aryan to table \(p[i]\) (for all \(0 \leq i < n\)). - \(s\) is the label of the table where Aryan is at the beginning, and where he should be after sorting the books. - This procedure should return the minimum total distance (in meters) Aryan has to walk in order to sort the books. ## Example ``` minimum_walk([0, 2, 3, 1], 0) ``` In this example, \(n = 4\) and Aryan is at table \(0\) at the beginning. He sorts the books as follows: - He walks to table \(1\) and picks up the book lying on it. This book should be put on table \(2\). - Then, he walks to table \(2\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(3\). - Then, he walks to table \(3\) and switches the book he is carrying with the book on the table. The new book he is carrying should be put on table \(1\). - Then, he walks to table \(1\) and puts the book he is carrying on the table. - Finally, he walks back to table \(0\). Note that book on table \(0\) is already in the correct place, table \(0\), so Aryan does not have to pick it up. The total distance he walks in this solution is \(6\) meters. This is the optimal solution; hence, the procedure should return \(6\). ## Constraints - \(1 \leq n \leq 1,000,000\) - \(0 \leq s \leq n - 1\) - Array \(p\) contains \(n\) distinct integers between \(0\) and \(n - 1\), inclusive. ## Sample grader The sample grader reads the input in the following format: - Line 1: \(n \; s\) - Line 2: \(p[0] \; p[1] \; \ldots \; p[n - 1]\) The sample grader prints a single line containing the return value of `minimum_walk`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: s = 0
Python
seed_158
# Arranging Shoes Adnan owns the biggest shoe store in Baku. A box containing $n$ pairs of shoes has just arrived at the store. Each pair consists of two shoes of the same size: a left and a right one. Adnan has put all of the $2n$ shoes in a row consisting of $2n$ positions numbered $0$ through $2n - 1$ from left to right. Adnan wants to rearrange the shoes into a **valid arrangement**. An arrangement is valid if and only if for every $i$ ($0 \leq i \leq n - 1$), the following conditions hold: - The shoes at positions $2i$ and $2i + 1$ are of the same size. - The shoe at position $2i$ is a left shoe. - The shoe at position $2i + 1$ is a right shoe. For this purpose, Adnan can make a series of swaps. In each swap, he selects two shoes that are **adjacent** at that moment and exchanges them (i.e., picks them up and puts each one on the former position of the other shoe). Two shoes are adjacent if their positions differ by one. Determine the minimum number of swaps that Adnan needs to perform in order to obtain a valid arrangement of the shoes. ## Implementation Details You should implement the following procedure: ``` int64 count_swaps(int[] S) ``` - `S`: an array of $2n$ integers. For each $i$ ($0 \leq i \leq 2n - 1$), $|S[i]|$ is a non-zero value equal to the size of the shoe initially placed at position $i$. Here, $|x|$ denotes the absolute value of $x$, which equals $x$ if $x > 0$ and equals $-x$ if $x < 0$. If $S[i] < 0$, the shoe at position $i$ is a left shoe; otherwise, it is a right shoe. - This procedure should return the minimum number of swaps (of adjacent shoes) that need to be performed in order to obtain a valid arrangement. ## Examples ### Example 1 Consider the following call: ``` count_swaps([2, 1, -1, -2]) ``` Adnan can obtain a valid arrangement in 4 swaps. For instance, he can first swap shoes $1$ and $-1$, then $1$ and $-2$, then $-1$ and $-2$, and finally $2$ and $-2$. He would then obtain the following valid arrangement: `[-2, 2, -1, 1]`. It is not possible to obtain any valid arrangement with less than $4$ swaps. Therefore, the procedure should return $4$. ![Example 1 Explanation](<image>) ### Example 2 In the following example, all the shoes have the same size: ``` count_swaps([-2, 2, 2, -2, -2, 2]) ``` Adnan can swap the shoes at positions $2$ and $3$ to obtain the valid arrangement `[-2, 2, -2, 2, -2, 2]`, so the procedure should return $1$. ## Constraints - $1 \leq n \leq 100,000$ - For each $i$ ($0 \leq i \leq 2n - 1$), $1 \leq |S[i]| \leq n$. - A valid arrangement of the shoes can be obtained by performing some sequence of swaps. ## Sample Grader The sample grader reads the input in the following format: - Line 1: $n$ - Line 2: $S[0] \ S[1] \ S[2] \ \ldots \ S[2n-1]$ The sample grader outputs a single line containing the return value of `count_swaps`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: All shoes at positions 0, ..., n-1 are left shoes, and all shoes at positions n, ..., 2n-1 are right shoes. Also, for each i (0 \leq i \leq n-1), the shoes at positions i and i + n are of the same size.
Python
seed_159
# Arranging Shoes Adnan owns the biggest shoe store in Baku. A box containing $n$ pairs of shoes has just arrived at the store. Each pair consists of two shoes of the same size: a left and a right one. Adnan has put all of the $2n$ shoes in a row consisting of $2n$ positions numbered $0$ through $2n - 1$ from left to right. Adnan wants to rearrange the shoes into a **valid arrangement**. An arrangement is valid if and only if for every $i$ ($0 \leq i \leq n - 1$), the following conditions hold: - The shoes at positions $2i$ and $2i + 1$ are of the same size. - The shoe at position $2i$ is a left shoe. - The shoe at position $2i + 1$ is a right shoe. For this purpose, Adnan can make a series of swaps. In each swap, he selects two shoes that are **adjacent** at that moment and exchanges them (i.e., picks them up and puts each one on the former position of the other shoe). Two shoes are adjacent if their positions differ by one. Determine the minimum number of swaps that Adnan needs to perform in order to obtain a valid arrangement of the shoes. ## Implementation Details You should implement the following procedure: ``` int64 count_swaps(int[] S) ``` - `S`: an array of $2n$ integers. For each $i$ ($0 \leq i \leq 2n - 1$), $|S[i]|$ is a non-zero value equal to the size of the shoe initially placed at position $i$. Here, $|x|$ denotes the absolute value of $x$, which equals $x$ if $x > 0$ and equals $-x$ if $x < 0$. If $S[i] < 0$, the shoe at position $i$ is a left shoe; otherwise, it is a right shoe. - This procedure should return the minimum number of swaps (of adjacent shoes) that need to be performed in order to obtain a valid arrangement. ## Examples ### Example 1 Consider the following call: ``` count_swaps([2, 1, -1, -2]) ``` Adnan can obtain a valid arrangement in 4 swaps. For instance, he can first swap shoes $1$ and $-1$, then $1$ and $-2$, then $-1$ and $-2$, and finally $2$ and $-2$. He would then obtain the following valid arrangement: `[-2, 2, -1, 1]`. It is not possible to obtain any valid arrangement with less than $4$ swaps. Therefore, the procedure should return $4$. ![Example 1 Explanation](<image>) ### Example 2 In the following example, all the shoes have the same size: ``` count_swaps([-2, 2, 2, -2, -2, 2]) ``` Adnan can swap the shoes at positions $2$ and $3$ to obtain the valid arrangement `[-2, 2, -2, 2, -2, 2]`, so the procedure should return $1$. ## Constraints - $1 \leq n \leq 100,000$ - For each $i$ ($0 \leq i \leq 2n - 1$), $1 \leq |S[i]| \leq n$. - A valid arrangement of the shoes can be obtained by performing some sequence of swaps. ## Sample Grader The sample grader reads the input in the following format: - Line 1: $n$ - Line 2: $S[0] \ S[1] \ S[2] \ \ldots \ S[2n-1]$ The sample grader outputs a single line containing the return value of `count_swaps`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: All the shoes are of the same size.
Python
seed_160
# Arranging Shoes Adnan owns the biggest shoe store in Baku. A box containing $n$ pairs of shoes has just arrived at the store. Each pair consists of two shoes of the same size: a left and a right one. Adnan has put all of the $2n$ shoes in a row consisting of $2n$ positions numbered $0$ through $2n - 1$ from left to right. Adnan wants to rearrange the shoes into a **valid arrangement**. An arrangement is valid if and only if for every $i$ ($0 \leq i \leq n - 1$), the following conditions hold: - The shoes at positions $2i$ and $2i + 1$ are of the same size. - The shoe at position $2i$ is a left shoe. - The shoe at position $2i + 1$ is a right shoe. For this purpose, Adnan can make a series of swaps. In each swap, he selects two shoes that are **adjacent** at that moment and exchanges them (i.e., picks them up and puts each one on the former position of the other shoe). Two shoes are adjacent if their positions differ by one. Determine the minimum number of swaps that Adnan needs to perform in order to obtain a valid arrangement of the shoes. ## Implementation Details You should implement the following procedure: ``` int64 count_swaps(int[] S) ``` - `S`: an array of $2n$ integers. For each $i$ ($0 \leq i \leq 2n - 1$), $|S[i]|$ is a non-zero value equal to the size of the shoe initially placed at position $i$. Here, $|x|$ denotes the absolute value of $x$, which equals $x$ if $x > 0$ and equals $-x$ if $x < 0$. If $S[i] < 0$, the shoe at position $i$ is a left shoe; otherwise, it is a right shoe. - This procedure should return the minimum number of swaps (of adjacent shoes) that need to be performed in order to obtain a valid arrangement. ## Examples ### Example 1 Consider the following call: ``` count_swaps([2, 1, -1, -2]) ``` Adnan can obtain a valid arrangement in 4 swaps. For instance, he can first swap shoes $1$ and $-1$, then $1$ and $-2$, then $-1$ and $-2$, and finally $2$ and $-2$. He would then obtain the following valid arrangement: `[-2, 2, -1, 1]`. It is not possible to obtain any valid arrangement with less than $4$ swaps. Therefore, the procedure should return $4$. ![Example 1 Explanation](<image>) ### Example 2 In the following example, all the shoes have the same size: ``` count_swaps([-2, 2, 2, -2, -2, 2]) ``` Adnan can swap the shoes at positions $2$ and $3$ to obtain the valid arrangement `[-2, 2, -2, 2, -2, 2]`, so the procedure should return $1$. ## Constraints - $1 \leq n \leq 100,000$ - For each $i$ ($0 \leq i \leq 2n - 1$), $1 \leq |S[i]| \leq n$. - A valid arrangement of the shoes can be obtained by performing some sequence of swaps. ## Sample Grader The sample grader reads the input in the following format: - Line 1: $n$ - Line 2: $S[0] \ S[1] \ S[2] \ \ldots \ S[2n-1]$ The sample grader outputs a single line containing the return value of `count_swaps`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: No additional constraints.
Python
seed_162
# Arranging Shoes Adnan owns the biggest shoe store in Baku. A box containing $n$ pairs of shoes has just arrived at the store. Each pair consists of two shoes of the same size: a left and a right one. Adnan has put all of the $2n$ shoes in a row consisting of $2n$ positions numbered $0$ through $2n - 1$ from left to right. Adnan wants to rearrange the shoes into a **valid arrangement**. An arrangement is valid if and only if for every $i$ ($0 \leq i \leq n - 1$), the following conditions hold: - The shoes at positions $2i$ and $2i + 1$ are of the same size. - The shoe at position $2i$ is a left shoe. - The shoe at position $2i + 1$ is a right shoe. For this purpose, Adnan can make a series of swaps. In each swap, he selects two shoes that are **adjacent** at that moment and exchanges them (i.e., picks them up and puts each one on the former position of the other shoe). Two shoes are adjacent if their positions differ by one. Determine the minimum number of swaps that Adnan needs to perform in order to obtain a valid arrangement of the shoes. ## Implementation Details You should implement the following procedure: ``` int64 count_swaps(int[] S) ``` - `S`: an array of $2n$ integers. For each $i$ ($0 \leq i \leq 2n - 1$), $|S[i]|$ is a non-zero value equal to the size of the shoe initially placed at position $i$. Here, $|x|$ denotes the absolute value of $x$, which equals $x$ if $x > 0$ and equals $-x$ if $x < 0$. If $S[i] < 0$, the shoe at position $i$ is a left shoe; otherwise, it is a right shoe. - This procedure should return the minimum number of swaps (of adjacent shoes) that need to be performed in order to obtain a valid arrangement. ## Examples ### Example 1 Consider the following call: ``` count_swaps([2, 1, -1, -2]) ``` Adnan can obtain a valid arrangement in 4 swaps. For instance, he can first swap shoes $1$ and $-1$, then $1$ and $-2$, then $-1$ and $-2$, and finally $2$ and $-2$. He would then obtain the following valid arrangement: `[-2, 2, -1, 1]`. It is not possible to obtain any valid arrangement with less than $4$ swaps. Therefore, the procedure should return $4$. ![Example 1 Explanation](<image>) ### Example 2 In the following example, all the shoes have the same size: ``` count_swaps([-2, 2, 2, -2, -2, 2]) ``` Adnan can swap the shoes at positions $2$ and $3$ to obtain the valid arrangement `[-2, 2, -2, 2, -2, 2]`, so the procedure should return $1$. ## Constraints - $1 \leq n \leq 100,000$ - For each $i$ ($0 \leq i \leq 2n - 1$), $1 \leq |S[i]| \leq n$. - A valid arrangement of the shoes can be obtained by performing some sequence of swaps. ## Sample Grader The sample grader reads the input in the following format: - Line 1: $n$ - Line 2: $S[0] \ S[1] \ S[2] \ \ldots \ S[2n-1]$ The sample grader outputs a single line containing the return value of `count_swaps`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: n \leq 1000
Python
seed_164
# Artemis ## Problem Zeus gave Artemis, the goddess of the wilderness, a rectangular area for growing a forest. With the left side of the area as a segment of the positive y-axis and the bottom side as a segment of the positive x-axis, and $(0,0)$ the left bottom corner of the area, Zeus told Artemis to plant trees only on integer coordinate points in the area. Artemis liked the forest to look natural, and therefore planted trees in such a way that a line connecting two trees was never parallel to the x-axis or y-axis. At times, Zeus wants Artemis to cut trees for him. The trees are to be cut as follows: 1. Zeus wants at least a given number $T$ of trees to be cut for him. 2. To get a rectangular football pitch for future football success, Artemis is to cut all trees within a rectangular area, and no trees outside of it. 3. The sides of this rectangular area are to be parallel to the x-axis and y-axis. 4. Two opposite corners of the area must be located on trees and therefore those corner trees are also cut. As Artemis likes the trees, she wants to fulfill these conditions whilst cutting as few trees as possible. You are to write a program that, given information on the forest and the minimum number $T$ of trees to be cut, selects an area for cutting trees for Artemis. ## Input The input file name is `artemis.in`. The first line contains one integer $N$: the number of trees in the forest. The second line contains one integer $T$: the minimum number of trees to be cut. The following $N$ lines describe the positions of the $N$ trees. Each of these lines contains two integers $X$ and $Y$: the x-coordinate followed by the y-coordinate of a tree. ## Output The output file name is `artemis.out`. The file is to contain one line with two integers $I$ and $J$ separated by one space: Artemis should use the $I$th tree (with position given on line $I+2$ of the input file) and $J$th tree (with position given on line $J+2$ of the input file) as the corners of the area for cutting trees. The order of these two numbers is irrelevant. There may be several ways to choose these trees and you need to find and output one of them. For all test cases at least one solution exists. ## Example Input and Output ### Input (`artemis.in`) ``` 3 2 1 1 2 3 5 6 ``` ### Output (`artemis.out`) ``` 1 2 ``` ## Constraints In all inputs, $1 \leq N \leq 20000$, $0 \leq X, Y \leq 64000$ and $1 \leq T \leq N$. Additionally, in 50% of the inputs, $1 \leq N < 5000$. <image> Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_165
# Back-Story Every day I travel on the freeway. When I am more bored than usual I sometimes like to play the following counting game I made up: * As I join the freeway my count is ```0``` * Add ```1``` for every car that I overtake * Subtract ```1``` for every car that overtakes me * Stop counting when I reach my exit What an easy game! What fun! # Kata Task You will be given * The distance to my exit (km) * How fast I am going (kph) * Information about a lot of other cars * Their time (relative to me) as I join the freeway. For example, * ```-1.5``` means they already passed my starting point ```1.5``` minutes ago * ```2.2``` means they will pass my starting point ```2.2``` minutes from now * How fast they are going (kph) Find what is my "score" as I exit the freeway! # Notes * Assume all cars travel at a constant speeds Β Safety WarningΒ  If you plan to play this "game" remember that it is not really a game. You are in a **real** car. There may be a temptation to try to beat your previous best score. Please don't do that...
Python
seed_166
# Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type words... # Keyboard The screen "keyboard" layout looks like this #tvkb { width : 400px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { color : orange; background-color : black; text-align : center; border: 3px solid gray; border-collapse: collapse; } abcde123 fghij456 klmno789 pqrst.@0 uvwxyz_/ aASP * `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase * `SP` is the space character * The other blank keys in the bottom row have no function # Kata task How many button presses on my remote are required to type the given `words`? ## Hint This Kata is an extension of the earlier ones in this series. You should complete those first. ## Notes * The cursor always starts on the letter `a` (top left) * The alpha characters are initially lowercase (as shown above) * Remember to also press `OK` to "accept" each letter * Take the shortest route from one letter to the next * The cursor wraps, so as it moves off one edge it will reappear on the opposite edge * Although the blank keys have no function, you may navigate through them if you want to * Spaces may occur anywhere in the `words` string * Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before) # Example words = `Code Wars` * C => `a`-`aA`-OK-`A`-`B`-`C`-OK = 6 * o => `C`-`B`-`A`-`aA`-OK-`u`-`v`-`w`-`x`-`y`-`t`-`o`-OK = 12 * d => `o`-`j`-`e`-`d`-OK = 4 * e => `d`-`e`-OK = 2 * space => `e`-`d`-`c`-`b`-`SP`-OK = 5 * W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6 * a => `W`-`V`-`U`-`aA`-OK-`a`-OK = 6 * r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6 * s => `r`-`s`-OK = 2 Answer = 6 + 12 + 4 + 2 + 5 + 6 + 6 + 6 + 2 = 49 *Good Luck! DM.* Series * TV Remote * TV Remote (shift and space) * TV Remote (wrap) * TV Remote (symbols)
Python
seed_167
# Background A spider web is defined by * "rings" numbered out from the centre as `0`, `1`, `2`, `3`, `4` * "radials" labelled clock-wise from the top as `A`, `B`, `C`, `D`, `E`, `F`, `G`, `H` Here is a picture to help explain: # Web Coordinates As you can see, each point where the rings and the radials intersect can be described by a "web coordinate". So in this example the spider is at `H3` and the fly is at `E2` # Kata Task Our friendly jumping spider is resting and minding his own spidery business at web-coordinate `spider`. An inattentive fly bumbles into the web at web-coordinate `fly` and gets itself stuck. Your task is to calculate and return **the distance** the spider must jump to get to the fly. # Example The solution to the scenario described by the picture is ``4.63522`` # Notes * The centre of the web will always be referred to as `A0` * The rings intersect the radials at **evenly** spaced distances of **1 unit** ____ Good Luck!DM
Python
seed_168
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
Python
seed_169
# Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type "words"... The screen "keyboard" layout looks like this #tvkb { width : 300px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { color : orange; background-color : black; text-align : right; border: 3px solid gray; border-collapse: collapse; } abcde123 fghij456 klmno789 pqrst.@0 uvwxyz_/ # Kata task How many button presses on my remote are required to type a given `word`? ## Notes * The cursor always starts on the letter `a` (top left) * Remember to also press `OK` to "accept" each character. * Take a direct route from one character to the next * The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge) * A "word" (for the purpose of this Kata) is any sequence of characters available on my virtual "keyboard" # Example word = `codewars` * c => `a`-`b`-`c`-OK = 3 * o => `c`-`d`-`e`-`j`-`o`-OK = 5 * d => `o`-`j`-`e`-`d`-OK = 4 * e => `d`-`e`-OK = 2 * w => `e`-`j`-`o`-`t`-`y`-`x`-`w`-OK = 7 * a => `w`-`r`-`m`-`h`-`c`-`b`-`a`-OK = 7 * r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6 * s => `r`-`s`-OK = 2 Answer = 3 + 5 + 4 + 2 + 7 + 7 + 6 + 2 = 36 *Good Luck! DM.* Series * TV Remote * TV Remote (shift and space) * TV Remote (wrap) * TV Remote (symbols)
Python
seed_170
# Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type words... # Keyboard The screen "keyboard" layout looks like this #tvkb { width : 400px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { color : orange; background-color : black; text-align : center; border: 3px solid gray; border-collapse: collapse; } abcde123 fghij456 klmno789 pqrst.@0 uvwxyz_/ aASP * `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase * `SP` is the space character * The other blank keys in the bottom row have no function # Kata task How many button presses on my remote are required to type the given `words`? ## Notes * The cursor always starts on the letter `a` (top left) * The alpha characters are initially lowercase (as shown above) * Remember to also press `OK` to "accept" each letter * Take a direct route from one letter to the next * The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge) * Although the blank keys have no function, you may navigate through them if you want to * Spaces may occur anywhere in the `words` string. * Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before) # Example words = `Code Wars` * C => `a`-`f`-`k`-`p`-`u`-`aA`-OK-`U`-`P`-`K`-`F`-`A`-`B`-`C`-OK = 14 * o => `C`-`H`-`M`-`R`-`W`-`V`-`U`-`aA`-OK-`SP`-`v`-`q`-`l`-`m`-`n`-`o`-OK = 16 * d => `o`-`j`-`e`-`d`-OK = 4 * e => `d`-`e`-OK = 2 * space => `e`-`d`-`c`-`b`-`g`-`l`-`q`-`v`-`SP`-OK = 9 * W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6 * a => `W`-`V`-`U`-`aA`-OK-`u`-`p`-`k`-`f`-`a`-OK = 10 * r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6 * s => `r`-`s`-OK = 2 Answer = 14 + 16 + 4 + 2 + 9 + 6 + 10 + 6 + 2 = 69 *Good Luck! DM.* Series * TV Remote * TV Remote (shift and space) * TV Remote (wrap) * TV Remote (symbols)
Python
seed_171
# Background My pet bridge-maker ants are marching across a terrain from left to right. If they encounter a gap, the first one stops and then next one climbs over him, then the next, and the next, until a bridge is formed across the gap. What clever little things they are! Now all the other ants can walk over the ant-bridge. When the last ant is across, the ant-bridge dismantles itself similar to how it was constructed. This process repeats as many times as necessary (there may be more than one gap to cross) until all the ants reach the right hand side. # Kata Task My little ants are marching across the terrain from left-to-right in the order ```A``` then ```B``` then ```C```... What order do they exit on the right hand side? # Notes * ```-``` = solid ground * ```.``` = a gap * The number of ants may differ but there are always enough ants to bridge the gaps * The terrain never starts or ends with a gap * Ants cannot pass other ants except by going over ant-bridges * If there is ever ambiguity which ant should move, then the ant at the **back** moves first # Example ## Input * ants = ````GFEDCBA```` * terrain = ```------------...-----------``` ## Output * result = ```EDCBAGF``` ## Details Ants moving left to right. GFEDCBA ------------...----------- The first one arrives at a gap. GFEDCB A ------------...----------- They start to bridge over the gap... GFED ABC ------------...----------- ...until the ant-bridge is completed! GF ABCDE ------------...----------- And then the remaining ants can walk across the bridge. F G ABCDE ------------...----------- And when no more ants need to cross... ABCDE GF ------------...----------- ... the bridge dismantles itself one ant at a time.... CDE BAGF ------------...----------- ...until all ants get to the other side EDCBAGF ------------...-----------
Python
seed_172
# Background The famous Collatz Sequence is generated with the following rules: * Start with a positive integer `a[0] = n`. * If `a[i]` is even, `a[i+1] = a[i] / 2`. * Otherwise, `a[i+1] = a[i] * 3 + 1`. However, for the purpose of this Kata, I give a **slightly modified definition**: * If `a[i]` is even, `a[i+1] = a[i] / 2`. This step is a step-down, or `D`. * Otherwise, `a[i+1] = (a[i] * 3 + 1) / 2`. This step is a step-up, or `U`. Also, for any starting number, the sequence is generated indefinitely, not ending at 1. # Problem Description For any given starting number, we can record the types of steps(`D` or `U`) from it. For example, if we start with the number 11, the Collatz steps look like this: ``` a[0] = 11 a[1] = (11 * 3 + 1) / 2 = 17 -> U a[2] = (17 * 3 + 1) / 2 = 26 -> U a[3] = 26 / 2 = 13 -> D a[4] = (13 * 3 + 1) / 2 = 20 -> U a[5] = 20 / 2 = 10 -> D a[6] = 10 / 2 = 5 -> D a[7] = (5 * 3 + 1) / 2 = 8 -> U a[8] = 8 / 2 = 4 -> D a[9] = 4 / 2 = 2 -> D a[10] = 2 / 2 = 1 -> D a[11] = (1 * 3 + 1) / 2 = 2 -> U a[12] = 2 / 2 = 1 -> D ... ``` ``` 11 -> 17 -> 26 -> 13 -> 20 -> 10 -> 5 -> 8 -> 4 -> 2 -> 1 -> 2 -> 1 -> ... U U D U D D U D D D U D ``` Based on the steps shown above, the first four Collatz steps of 11 is `UUDU`. Also, 107 is the smallest number over 100 whose Collatz steps start with `UUDU`, and 1003 is the smallest number over 1000 with the property. A special example is the number 1, which can generate any number of `UD`. Find the smallest integer exceeding or equal to `n` whose Collatz steps start with the given string `steps`. # Constraints `1 <= n <= 10 ** 9` `n` is always a valid integer. `1 <= length(steps) <= 25` The string `steps` will entirely consist of `U`s and `D`s. # Examples ```python collatz_steps(1, 'UUDU') == 11 collatz_steps(100, 'UUDU') == 107 collatz_steps(1000, 'UUDU') == 1003 collatz_steps(1, 'UD') == 1 collatz_steps(1, 'UDUD') == 1 collatz_steps(1, 'UDUDUD') == 1 ``` # Hint If you are completely lost, start by answering the following question: * After applying the given steps (e.g. `UUDU`) to an initial number `x`, what fraction do you get? After that, you might want to study about [modular inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse). # Acknowledgement This problem was inspired by [Project Euler #277: A Modified Collatz sequence](https://projecteuler.net/problem=277). If you enjoyed this Kata, please also have a look at [my other Katas](https://www.codewars.com/users/Bubbler/authored)!
Python
seed_175
# Base64 Numeric Translator Our standard numbering system is (Base 10). That includes 0 through 9. Binary is (Base 2), only 1’s and 0’s. And Hexadecimal is (Base 16) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F). A hexadecimal β€œF” has a (Base 10) value of 15. (Base 64) has 64 individual characters which translate in value in (Base 10) from between 0 to 63. ####Write a method that will convert a string from (Base 64) to it's (Base 10) integer value. The (Base 64) characters from least to greatest will be ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ``` Where 'A' is equal to 0 and '/' is equal to 63. Just as in standard (Base 10) when you get to the highest individual integer 9 the next number adds an additional place and starts at the beginning 10; so also (Base 64) when you get to the 63rd digit '/' and the next number adds an additional place and starts at the beginning "BA". Example: ``` base64_to_base10("/") # => 63 base64_to_base10("BA") # => 64 base64_to_base10("BB") # => 65 base64_to_base10("BC") # => 66 ``` Write a method `base64_to_base10` that will take a string (Base 64) number and output it's (Base 10) value as an integer.
Python
seed_176
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints * $3 \le N \le 200\,000$ * $2 \le M \le 200\,000$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_177
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 200$ * $2 \le M \le 500$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_178
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 200\,000$ * $2 \le M \le 200\,000$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ * Each node other than node $0$ is either connected to node $0$, or is connected to a node which is connected to node $0$. That is, for each $v$ such that $1 \le v \lt N$, either $P[v]=0$ or $P[P[v]]=0$. ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_179
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 200\,000$ * $2 \le M \le 200\,000$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ * For each $c$ such that $1 \le c \le M$, there are at most two edges of color $c$. ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_180
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 200\,000$ * $2 \le M \le 200\,000$ * Edge $i$ connects node $i$ to node $i-1$. That is, for each $i$ such that $1 \le i \lt N$, $P[i] = i-1$. * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_181
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 200\,000$ * $M = 2$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_182
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 2\,000$ * $2 \le M \le 200\,000$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_183
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 2\,000$ * $M = 2$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_184
# Beech Tree Vétyem Woods is a famous woodland with lots of colorful trees. One of the oldest and tallest beech trees is called Ős Vezér. The tree Ős Vezér can be modeled as a set of $N$ **nodes** and $N-1$ **edges**. Nodes are numbered from $0$ to $N-1$ and edges are numbered from $1$ to $N-1$. Each edge connects two distinct nodes of the tree. Specifically, edge $i$ ($1 \le i \lt N$) connects node $i$ to node $P[i]$, where $0 \le P[i] \lt i$. Node $P[i]$ is called the **parent** of node $i$, and node $i$ is called a **child** of node $P[i]$. Each edge has a color. There are $M$ possible edge colors numbered from $1$ to $M$. The color of edge $i$ is $C[i]$. Different edges may have the same color. Note that in the definitions above, the case $i = 0$ does not correspond to an edge of the tree. For convenience, we let $P[0] = -1$ and $C[0] = 0$. For example, suppose that Ős Vezér has $N = 18$ nodes and $M = 3$ possible edge colors, with $17$ edges described by connections $P = [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11]$ and colors $C = [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]$. The tree is displayed in the following figure: ÁrpÑd is a talented forester who likes to study specific parts of the tree called **subtrees**. For each $r$ such that $0 \le r \lt N$, the subtree of node $r$ is the set $T(r)$ of nodes with the following properties: * Node $r$ belongs to $T(r)$. * Whenever a node $x$ belongs to $T(r)$, all children of $x$ also belong to $T(r)$. * No other nodes belong to $T(r)$. The size of the set $T(r)$ is denoted as $|T(r)|$. ÁrpÑd recently discovered a complicated but interesting subtree property. ÁrpÑd's discovery involved a lot of playing with pen and paper, and he suspects you might need to do the same to understand it. He will also show you multiple examples you can then analyze in detail. Suppose we have a fixed $r$ and a permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ of the nodes in the subtree $T(r)$. For each $i$ such that $1 \le i \lt |T(r)|$, let $f(i)$ be the number of times the color $C[v_i]$ appears in the following sequence of $i-1$ colors: $C[v_1], C[v_2], \ldots, C[v_{i-1}]$. (Note that $f(1)$ is always $0$ because the sequence of colors in its definition is empty.) The permutation $v_0, v_1, \ldots, v_{|T(r)|-1}$ is a **beautiful permutation** if and only if all the following properties hold: * $v_0 = r$. * For each $i$ such that $1 \le i \lt |T(r)|$, the parent of node $v_i$ is node $v_{f(i)}$. For any $r$ such that $0 \le r \lt N$, the subtree $T(r)$ is a **beautiful subtree** if and only if there exists a beautiful permutation of the nodes in $T(r)$. Note that according to the definition every subtree which consists of a single node is beautiful. Consider the example tree above. It can be shown that the subtrees $T(0)$ and $T(3)$ of this tree are not beautiful. The subtree $T(14)$ is beautiful, as it consists of a single node. Below, we will show that the subtree $T(1)$ is also beautiful. Consider the sequence of distinct integers $[v_0, v_1, v_2, v_3, v_4, v_5, v_6] = [1, 4, 5, 12, 13, 6, 14]$. This sequence is a permutation of the nodes in $T(1)$. The figure below depicts this permutation. The labels attached to the nodes are the indices at which those nodes appear in the permutation. Clearly, the above sequence is a permutation of the nodes in $T(1)$. We will now verify that it is *beautiful*. * $v_0 = 1$. * $f(1) = 0$ since $C[v_1] = C[4] = 1$ appears $0$ times in the sequence $[]$. * Correspondingly, the parent of $v_1$ is $v_0$. That is, the parent of node $4$ is node $1$. (Formally, $P[4] = 1$.) * $f(2) = 0$ since $C[v_2] = C[5] = 2$ appears $0$ times in the sequence $[1]$. * Correspondingly, the parent of $v_2$ is $v_0$. That is, the parent of $5$ is $1$. * $f(3) = 1$ since $C[v_3] = C[12] = 1$ appears $1$ time in the sequence $[1, 2]$. * Correspondingly, the parent of $v_3$ is $v_1$. That is, the parent of $12$ is $4$. * $f(4) = 1$ since $C[v_4] = C[13] = 2$ appears $1$ time in the sequence $[1, 2, 1]$. * Correspondingly, the parent of $v_4$ is $v_1$. That is, the parent of $13$ is $4$. * $f(5) = 0$ since $C[v_5] = C[6] = 3$ appears $0$ times in the sequence $[1, 2, 1, 2]$. * Correspondingly, the parent of $v_5$ is $v_0$. That is, the parent of $6$ is $1$. * $f(6) = 2$ since $C[v_6] = C[14] = 2$ appears $2$ times in the sequence $[1, 2, 1, 2, 3]$. * Correspondingly, the parent of $v_6$ is $v_2$. That is, the parent of $14$ is $5$. As we could find a beautiful permutation of the nodes in $T(1)$, the subtree $T(1)$ is indeed beautiful. Your task is to help ÁrpÑd decide for every subtree of Ős Vezér whether it is beautiful. ## Implementation Details You should implement the following procedure. ``` int[] beechtree(int N, int M, int[] P, int[] C) ``` * $N$: the number of nodes in the tree. * $M$: the number of possible edge colors. * $P$, $C$: arrays of length $N$ describing the edges of the tree. * This procedure should return an array $b$ of length $N$. For each $r$ such that $0 \le r \lt N$, $b[r]$ should be $1$ if $T(r)$ is beautiful, and $0$ otherwise. * This procedure is called exactly once for each test case. ## Examples ### Example 1 Consider the following call: ``` beechtree(4, 2, [-1, 0, 0, 0], [0, 1, 1, 2]) ``` The tree is displayed in the following figure: $T(1)$, $T(2)$, and $T(3)$ each consist of a single node and are therefore beautiful. $T(0)$ is not beautiful. Therefore, the procedure should return $[0, 1, 1, 1]$. ### Example 2 Consider the following call: ``` beechtree(18, 3, [-1, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 11, 11], [0, 1, 2, 3, 1, 2, 3, 1, 3, 3, 2, 1, 1, 2, 2, 1, 2, 3]) ``` This example is illustrated in the task description above. The procedure should return $[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]$. ### Example 3 Consider the following call: ``` beechtree(7, 2, [-1, 0, 1, 1, 0, 4, 5], [0, 1, 1, 2, 2, 1, 1]) ``` This example is illustrated in the following figure. $T(0)$ is the only subtree that is not beautiful. The procedure should return $[0, 1, 1, 1, 1, 1, 1]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $3 \le N \le 8$ * $2 \le M \le 500$ * $0 \le P[i] \lt i$ (for each $i$ such that $1 \le i \lt N$) * $1 \le C[i] \le M$ (for each $i$ such that $1 \le i \lt N$) * $P[0] = -1$ and $C[0] = 0$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2$: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line $3$: $C[0] \; C[1] \; \ldots \; C[N-1]$ Let $b[0], \; b[1], \; \ldots$ denote the elements of the array returned by `beechtree`. The sample grader prints your answer in a single line, in the following format: * line $1$: $b[0] \; b[1] \; \ldots$
Python
seed_193
# Blackbox IOI'06 ## Day 2 -- Task 3 ## A BLACK BOX GAME ### Introduction The Black Box Game is played with a square-shaped black box lying flat on a table. Each of its four sides has $n$ holes (for a total of $4n$ holes) into which a ball can be thrown. A thrown ball will eventually exit from one of the $4n$ holes, potentially the same hole into which it was thrown. The black box's internals can be envisioned as an $n \times n$ grid. The holes in the sides are the starts and ends of rows and columns. Each of the box's squares is either empty or occupied by a *deflector*. A deflector is a piece of hardware that changes the direction of the ball by $90^\circ$. Consider this example of a $5 \times 5$ box. <center> <image> </center> A ball thrown into the box follows a straight line until it either hits a deflector or exits the box. When a ball hits a deflector, the ball changes direction and the deflector toggles its position (by \"toggle\" we mean rotate $90^\circ$). The examples below show the action of a deflector. <center> <image> </center> 1. **(a)** A ball is thrown through a hole; it hits a deflector and changes direction. 2. **(b)** After the first ball was thrown, the deflector has toggled its position. A new ball is thrown into the same hole, hits the deflector, and is deflected in a direction opposite to that of the first ball. 3. **(c)** The deflector toggles every time it is hit. Whenever a deflector is hit, it makes a beep. The number of times the ball was deflected can be deduced by counting the beeps. It can be proved that the ball always exits the box. The box has a button that resets it to its original state and another button that toggles all of its deflectors. ### Task You will be provided with an interface to 15 black boxes via a library of Pascal or C/C++ functions. You must determine the internals of each one of them as best as possible and submit a file describing each. You will also be provided with a method to define your own black boxes for testing. #### Constraints - $1 \leq n \leq 30$ #### Output You must submit a file containing the following data for each one of the 15 black-boxes: ``` blackboxX.out DESCRIPTION #FILE blackbox K ..... ..../. .\.../ ..?./. ``` - **LINE 1**: The file header. The file header must contain: ``` #FILE blackbox X ``` where $K$ (range 1..15) corresponds to the box being solved. - $n$ **LINES**: Each line describes a row of the box, starting from the topmost row to the bottom row. Each line must contain exactly $n$ characters; each character corresponds to a column (running from left to right). - `.` means that the square is empty. - `/` means the square contains a deflector with initial position `/`. - `\` means the square contains a deflector with initial position `\`. - `?` means that you were unable to determine the initial contents of that square. ### Library You are given a library that provides the following functions: | **Function** | **Description** | |---------------------------|-------------------------------------------------------------------------------------------------------| | `Initialize` | Initializes the library, must be called once at the start of your program. Returns $n$, the number of holes on each side of the box. | | `throwBall` | Throws a ball into the box through a hole; returns the number of deflections. | | `ResetBox` | Resets every deflector in the box to its initial position. | | `ToggleDeflectors` | Toggles every deflector in the box. | | `Finalize` | Gracefully ends the interaction with the box. | ### Sample Interaction A sample interaction for the box in the previous figure could be: ``` FUNCTION CALL VALUE RETURNED BY FUNCTION Initialize(0); 5 throwBall(3,4,holeOut,sideOut); 1 ``` ### Error Messages | **Error Message** | **Meaning** | |-------------------|-------------------------------------------------------------------------------------| | ERR 1 | More than one app running; restart all applications. | | ERR 2 | Invalid box; box number is not in the range 0 to 15. | | ERR 3 | Invalid deflector; deflector in an invalid position. | | ERR 4 | Invalid symbol; file contains an invalid symbol. | | ERR 5 | Invalid size; size of the black box is invalid. | | ERR 6 | Invalid input hole; side or input hole is invalid. | | ERR 7 | ALARM; please call technical staff. | ### Grading For each box, you must submit a text file that describes the internals of the black box as best as possible. The score for each box will be: \[ \text{Score} = \frac{100 \cdot B_s}{B_m} \] where $B_m$ is the maximum number of discovered positions among all correct submissions, and $B_s$ is the number of discovered positions in your submission. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_201
# Bubblesort Algorithm ## Overview The Bubblesort Algorithm is one of many algorithms used to sort a list of similar items (e.g. all numbers or all letters) into either ascending order or descending order. Given a list (e.g.): ```python [9, 7, 5, 3, 1, 2, 4, 6, 8] ``` To sort this list in ascending order using Bubblesort, you first have to compare the first two terms of the list. If the first term is larger than the second term, you perform a swap. The list then becomes: ```python [7, 9, 5, 3, 1, 2, 4, 6, 8] # The "9" and "7" have been swapped because 9 is larger than 7 and thus 9 should be after 7 ``` You then proceed by comparing the 2nd and 3rd terms, performing a swap *when necessary*, and then the 3rd and 4th term, then the 4th and 5th term, etc. etc. When you reach the end of the list, it is said that you have completed **1 complete pass**. ## Task Given an array of integers, your function `bubblesortOnce`/`bubblesort_once`/`BubblesortOnce` (or equivalent, depending on your language's naming conventions) should return a *new* array equivalent to performing exactly **1 complete pass** on the original array. Your function should be pure, i.e. it should **not** mutate the input array.
Python
seed_202
# Bus Terminals ## Problem Yong-In city plans to build a bus network with \( N \) bus stops. Each bus stop is at a street corner. Yong-In is a modern city, so its map is a grid of square blocks of equal size. Two of these bus stops are to be selected as hubs \( H_1 \) and \( H_2 \). The hubs will be connected to each other by a direct bus line and each of the remaining \( N - 2 \) bus stops will be connected directly to either \( H_1 \) or \( H_2 \) (but not to both), but not to any other bus stop. The distance between any two bus stops is the length of the shortest possible route following the streets. That is, if a bus stop is represented as \( (x, y) \) with x-coordinate \( x \) and y-coordinate \( y \), then the distance between two bus stops \( (x_1, y_1) \) and \( (x_2, y_2) \) is \[ |x_1 - x_2| + |y_1 - y_2|. \] If bus stops \( A \) and \( B \) are connected to the same hub \( H_1 \), then the length of the route from \( A \) to \( B \) is the sum of the distances from \( A \) to \( H_1 \) and from \( H_1 \) to \( B \). If bus stops \( A \) and \( B \) are connected to different hubs, e.g., \( A \) to \( H_1 \) and \( B \) to \( H_2 \), then the length of the route from \( A \) to \( B \) is the sum of the distances from \( A \) to \( H_1 \), from \( H_1 \) to \( H_2 \), and from \( H_2 \) to \( B \). The planning authority of Yong-In city would like to make sure that every citizen can reach every point within the city as quickly as possible. Therefore, city planners want to choose two bus stops to be hubs in such a way that in the resulting bus network the length of the longest route between any two bus stops is as short as possible. One choice \( P \) of two hubs and assignments of bus stops to those hubs is better than another choice \( Q \) if the length of the longest bus route is shorter in \( P \) than in \( Q \). Your task is to write a program to compute the length of this longest route for the best choice \( P \). ## Input Your program is to read from standard input. The first line contains one positive integer \( N \), \( 2 \leq N \leq 500 \), the number of bus stops. Each of the remaining \( N \) lines contains the \( x \)-coordinate followed by the \( y \)-coordinate of a bus stop. The \( x \)- and \( y \)-coordinates are positive integers \( \leq 5000 \). No two bus stops are at the same location. ## Output Your program is to write to standard output. The output contains one line with a single positive integer, the minimum length of the longest bus route for the input. ## Example Inputs and Outputs ### Example 1: **Input** ``` 6 1 7 16 6 12 4 4 4 1 1 11 1 ``` **Output** ``` 20 ``` ### Example 2: **Input** ``` 7 7 9 10 9 5 3 1 1 7 2 15 6 17 7 ``` **Output** ``` 25 ``` ## Explanation The following figures show the bus networks for the inputs given above. If in Example 1 bus stops 3 and 4 are selected as hubs, then the longest route is either between bus stops 2 and 5 or between bus stops 2 and 1. There is no better choice for the hubs, and the answer is 20. For the bus network in Example 2, if bus stops 5 and 6 are selected as hubs, then the longest route is obtained between bus stops 2 and 7. There is no better choice for the hubs, and the answer is 25. <center> <image> <image> </center> ## Scoring If your program outputs the correct answer for a test case within the time limit, then you get full points for that test case, and otherwise, you get 0 points for that case. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_203
# Carnival Tickets (tickets) Ringo is at a carnival in Singapore. He has some prize tickets in his bag, which he would like to use at the prize game stall. Each ticket comes in one of n colours and has a non-negative integer printed on it. The integers printed on different tickets might be the same. Due to a quirk in the carnival rules, n is guaranteed to be even. Ringo has m tickets of each colour in his bag, that is a total of n Β· m tickets. The ticket j of the colour i has the integer x[i][j] printed on it (0 ≀ i ≀ n βˆ’ 1 and 0 ≀ j ≀ m βˆ’ 1). The prize game is played in k rounds, numbered from 0 to k βˆ’ 1. Each round is played in the following order: * From his bag, Ringo selects a set of n tickets, one ticket from each colour. He then gives the set to the game master. * The game master notes down the integers a[0], a[1] ... a[n βˆ’ 1] printed on the tickets of the set. The order of these n integers is not important. * The game master pulls out a special card from a lucky draw box and notes down the integer b printed on that card. * The game master calculates the absolute differences between a[i] and b for each i from 0 to n βˆ’ 1. Let S be the sum of these absolute differences. * For this round, the game master gives Ringo a prize with a value equal to S. * The tickets in the set are discarded and cannot be used in future rounds. The remaining tickets in Ringo's bag after k rounds of the game are discarded. By watching closely, Ringo realized that the prize game is rigged! There is actually a printer inside the lucky draw box. In each round, the game master finds an integer b that minimizes the value of the prize of that round. The value chosen by the game master is printed on the special card for that round. Having all this information, Ringo would like to allocate tickets to the rounds of the game. That is, he wants to select the ticket set to use in each round in order to maximize the total value of the prizes. ## Implementation details You should implement the following procedure: ``` int64 find_maximum(int k, int[][] x) ``` * k: the number of rounds. * x: an n Γ— m array describing the integers on each ticket. Tickets of each color are sorted in non-decreasing order of their integers. * This procedure is called exactly once. * This procedure should make exactly one call to allocate_tickets (see below), describing k ticket sets, one for each round. The allocation should maximize the total value of the prizes. * This procedure should return the maximum total value of the prizes. The procedure allocate_tickets is defined as follows: ``` void allocate_tickets(int[][] s) ``` * s: an n Γ— m array. The value of s[i][j] should be r if the ticket j of the colour i is used in the set of round r of the game, or βˆ’1 if it is not used at all. * For each 0 ≀ i ≀ n βˆ’ 1, among s[i][0], s[i][1], . . . , s[i][m βˆ’ 1] each value 0, 1, 2, . . . , k βˆ’ 1 must occur exactly once, and all other entries must be βˆ’1. * If there are multiple allocations resulting in the maximum total prize value, it is allowed to report any of them. ## Examples ### Example 1 Consider the following call: ``` find_maximum(2, [[0, 2, 5],[1, 1, 3]]) ``` This means that: * there are k = 2 rounds; * the integers printed on the tickets of colour 0 are 0, 2 and 5, respectively; * the integers printed on the tickets of colour 1 are 1, 1 and 3, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 0 of colour 0 (with the integer 0) and ticket 2 of colour 1 (with the integer 3). The lowest possible value of the prize in this round is 3. E.g., the game master may choose b = 0: |0 βˆ’ 0| + |3 βˆ’ 0| = 0 + 3 = 3. * In round 1, Ringo picks ticket 2 of colour 0 (with the integer 5) and ticket 1 of colour 1 (with the integer 1). The lowest possible value of the prize in this round is 4. E.g., the game master may choose b = 3: |5 βˆ’ 3| + |1 βˆ’ 3| = 2 + 2 = 4. * Therefore, the total value of the prizes would be 3 + 4 = 7. To report this allocation, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[0, -1, 1], [-1, 1, 0]]) ``` Finally, the procedure find_maximum should return 7. ### Example 2 Consider the following call: ``` find_maximum(1, [[5, 9], [1, 4], [3, 6], [2, 7]]) ``` This means that: * there is only one round, * the integers printed on the tickets of colour 0 are 5 and 9, respectively; * the integers printed on the tickets of colour 1 are 1 and 4, respectively; * the integers printed on the tickets of colour 2 are 3 and 6, respectively; * the integers printed on the tickets of colour 3 are 2 and 7, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 1 of colour 0 (with the integer 9), ticket 0 of colour 1 (with the integer 1), ticket 0 of colour 2 (with the integer 3), and ticket 1 of colour 3 (with the integer 7). The lowest possible value of the prize in this round is 12, when the game master chooses b = 3: |3 βˆ’ 9| + |3 βˆ’ 1| + |3 βˆ’ 3| + |3 βˆ’ 7| = 6 + 2 + 0 + 4 = 12. To report this solution, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[-1, 0], [0, -1], [0, -1], [-1, 0]]) ``` Finally, the procedure find_maximum should return 12. ## Constraints * $2 \le n \le 1500$ and $n$ is even. * $1 \le k \le m \le 1500$ * $0 \le x[i][j] \le 10^9$ (for all $0 \le i \le n - 1$ and $0 \le j \le m - 1$) * $x[i][j - 1] \le x[i][j]$ (for all $0 \le i \le n - 1$ and $1 \le j \le m - 1$) * For each call to count_tastiness, the sum of tastiness values of all biscuits in the pantry does not exceed $10^{18}$. ## Sample grader The sample grader reads the input in the following format: * line 1: n m k * line 2 + i (0 ≀ i ≀ n βˆ’ 1): x[i][0] x[i][1] ... x[i][m βˆ’ 1] The sample grader prints your answer in the following format: * line 1: the return value of find_maximum * line 2 + i (0 ≀ i ≀ n βˆ’ 1): s[i][0] s[i][1] ... s[i][m βˆ’ 1]
Python
seed_204
# Carnival Tickets (tickets) Ringo is at a carnival in Singapore. He has some prize tickets in his bag, which he would like to use at the prize game stall. Each ticket comes in one of n colours and has a non-negative integer printed on it. The integers printed on different tickets might be the same. Due to a quirk in the carnival rules, n is guaranteed to be even. Ringo has m tickets of each colour in his bag, that is a total of n Β· m tickets. The ticket j of the colour i has the integer x[i][j] printed on it (0 ≀ i ≀ n βˆ’ 1 and 0 ≀ j ≀ m βˆ’ 1). The prize game is played in k rounds, numbered from 0 to k βˆ’ 1. Each round is played in the following order: * From his bag, Ringo selects a set of n tickets, one ticket from each colour. He then gives the set to the game master. * The game master notes down the integers a[0], a[1] ... a[n βˆ’ 1] printed on the tickets of the set. The order of these n integers is not important. * The game master pulls out a special card from a lucky draw box and notes down the integer b printed on that card. * The game master calculates the absolute differences between a[i] and b for each i from 0 to n βˆ’ 1. Let S be the sum of these absolute differences. * For this round, the game master gives Ringo a prize with a value equal to S. * The tickets in the set are discarded and cannot be used in future rounds. The remaining tickets in Ringo's bag after k rounds of the game are discarded. By watching closely, Ringo realized that the prize game is rigged! There is actually a printer inside the lucky draw box. In each round, the game master finds an integer b that minimizes the value of the prize of that round. The value chosen by the game master is printed on the special card for that round. Having all this information, Ringo would like to allocate tickets to the rounds of the game. That is, he wants to select the ticket set to use in each round in order to maximize the total value of the prizes. ## Implementation details You should implement the following procedure: ``` int64 find_maximum(int k, int[][] x) ``` * k: the number of rounds. * x: an n Γ— m array describing the integers on each ticket. Tickets of each color are sorted in non-decreasing order of their integers. * This procedure is called exactly once. * This procedure should make exactly one call to allocate_tickets (see below), describing k ticket sets, one for each round. The allocation should maximize the total value of the prizes. * This procedure should return the maximum total value of the prizes. The procedure allocate_tickets is defined as follows: ``` void allocate_tickets(int[][] s) ``` * s: an n Γ— m array. The value of s[i][j] should be r if the ticket j of the colour i is used in the set of round r of the game, or βˆ’1 if it is not used at all. * For each 0 ≀ i ≀ n βˆ’ 1, among s[i][0], s[i][1], . . . , s[i][m βˆ’ 1] each value 0, 1, 2, . . . , k βˆ’ 1 must occur exactly once, and all other entries must be βˆ’1. * If there are multiple allocations resulting in the maximum total prize value, it is allowed to report any of them. ## Examples ### Example 1 Consider the following call: ``` find_maximum(2, [[0, 2, 5],[1, 1, 3]]) ``` This means that: * there are k = 2 rounds; * the integers printed on the tickets of colour 0 are 0, 2 and 5, respectively; * the integers printed on the tickets of colour 1 are 1, 1 and 3, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 0 of colour 0 (with the integer 0) and ticket 2 of colour 1 (with the integer 3). The lowest possible value of the prize in this round is 3. E.g., the game master may choose b = 0: |0 βˆ’ 0| + |3 βˆ’ 0| = 0 + 3 = 3. * In round 1, Ringo picks ticket 2 of colour 0 (with the integer 5) and ticket 1 of colour 1 (with the integer 1). The lowest possible value of the prize in this round is 4. E.g., the game master may choose b = 3: |5 βˆ’ 3| + |1 βˆ’ 3| = 2 + 2 = 4. * Therefore, the total value of the prizes would be 3 + 4 = 7. To report this allocation, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[0, -1, 1], [-1, 1, 0]]) ``` Finally, the procedure find_maximum should return 7. ### Example 2 Consider the following call: ``` find_maximum(1, [[5, 9], [1, 4], [3, 6], [2, 7]]) ``` This means that: * there is only one round, * the integers printed on the tickets of colour 0 are 5 and 9, respectively; * the integers printed on the tickets of colour 1 are 1 and 4, respectively; * the integers printed on the tickets of colour 2 are 3 and 6, respectively; * the integers printed on the tickets of colour 3 are 2 and 7, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 1 of colour 0 (with the integer 9), ticket 0 of colour 1 (with the integer 1), ticket 0 of colour 2 (with the integer 3), and ticket 1 of colour 3 (with the integer 7). The lowest possible value of the prize in this round is 12, when the game master chooses b = 3: |3 βˆ’ 9| + |3 βˆ’ 1| + |3 βˆ’ 3| + |3 βˆ’ 7| = 6 + 2 + 0 + 4 = 12. To report this solution, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[-1, 0], [0, -1], [0, -1], [-1, 0]]) ``` Finally, the procedure find_maximum should return 12. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le n \le 1500$ and $n$ is even. * $1 \le k \le m \le 1500$ * $0 \le x[i][j] \le 10^9$ (for all $0 \le i \le n - 1$ and $0 \le j \le m - 1$) * $x[i][j - 1] \le x[i][j]$ (for all $0 \le i \le n - 1$ and $1 \le j \le m - 1$) * For each call to count_tastiness, the sum of tastiness values of all biscuits in the pantry does not exceed $10^{18}$. * $0 \le x[i][j] \le 1$ (for all $0 \le i \le n - 1$ and $0 \le j \le m - 1$) ## Sample grader The sample grader reads the input in the following format: * line 1: n m k * line 2 + i (0 ≀ i ≀ n βˆ’ 1): x[i][0] x[i][1] ... x[i][m βˆ’ 1] The sample grader prints your answer in the following format: * line 1: the return value of find_maximum * line 2 + i (0 ≀ i ≀ n βˆ’ 1): s[i][0] s[i][1] ... s[i][m βˆ’ 1]
Python
seed_206
# Carnival Tickets (tickets) Ringo is at a carnival in Singapore. He has some prize tickets in his bag, which he would like to use at the prize game stall. Each ticket comes in one of n colours and has a non-negative integer printed on it. The integers printed on different tickets might be the same. Due to a quirk in the carnival rules, n is guaranteed to be even. Ringo has m tickets of each colour in his bag, that is a total of n Β· m tickets. The ticket j of the colour i has the integer x[i][j] printed on it (0 ≀ i ≀ n βˆ’ 1 and 0 ≀ j ≀ m βˆ’ 1). The prize game is played in k rounds, numbered from 0 to k βˆ’ 1. Each round is played in the following order: * From his bag, Ringo selects a set of n tickets, one ticket from each colour. He then gives the set to the game master. * The game master notes down the integers a[0], a[1] ... a[n βˆ’ 1] printed on the tickets of the set. The order of these n integers is not important. * The game master pulls out a special card from a lucky draw box and notes down the integer b printed on that card. * The game master calculates the absolute differences between a[i] and b for each i from 0 to n βˆ’ 1. Let S be the sum of these absolute differences. * For this round, the game master gives Ringo a prize with a value equal to S. * The tickets in the set are discarded and cannot be used in future rounds. The remaining tickets in Ringo's bag after k rounds of the game are discarded. By watching closely, Ringo realized that the prize game is rigged! There is actually a printer inside the lucky draw box. In each round, the game master finds an integer b that minimizes the value of the prize of that round. The value chosen by the game master is printed on the special card for that round. Having all this information, Ringo would like to allocate tickets to the rounds of the game. That is, he wants to select the ticket set to use in each round in order to maximize the total value of the prizes. ## Implementation details You should implement the following procedure: ``` int64 find_maximum(int k, int[][] x) ``` * k: the number of rounds. * x: an n Γ— m array describing the integers on each ticket. Tickets of each color are sorted in non-decreasing order of their integers. * This procedure is called exactly once. * This procedure should make exactly one call to allocate_tickets (see below), describing k ticket sets, one for each round. The allocation should maximize the total value of the prizes. * This procedure should return the maximum total value of the prizes. The procedure allocate_tickets is defined as follows: ``` void allocate_tickets(int[][] s) ``` * s: an n Γ— m array. The value of s[i][j] should be r if the ticket j of the colour i is used in the set of round r of the game, or βˆ’1 if it is not used at all. * For each 0 ≀ i ≀ n βˆ’ 1, among s[i][0], s[i][1], . . . , s[i][m βˆ’ 1] each value 0, 1, 2, . . . , k βˆ’ 1 must occur exactly once, and all other entries must be βˆ’1. * If there are multiple allocations resulting in the maximum total prize value, it is allowed to report any of them. ## Examples ### Example 1 Consider the following call: ``` find_maximum(2, [[0, 2, 5],[1, 1, 3]]) ``` This means that: * there are k = 2 rounds; * the integers printed on the tickets of colour 0 are 0, 2 and 5, respectively; * the integers printed on the tickets of colour 1 are 1, 1 and 3, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 0 of colour 0 (with the integer 0) and ticket 2 of colour 1 (with the integer 3). The lowest possible value of the prize in this round is 3. E.g., the game master may choose b = 0: |0 βˆ’ 0| + |3 βˆ’ 0| = 0 + 3 = 3. * In round 1, Ringo picks ticket 2 of colour 0 (with the integer 5) and ticket 1 of colour 1 (with the integer 1). The lowest possible value of the prize in this round is 4. E.g., the game master may choose b = 3: |5 βˆ’ 3| + |1 βˆ’ 3| = 2 + 2 = 4. * Therefore, the total value of the prizes would be 3 + 4 = 7. To report this allocation, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[0, -1, 1], [-1, 1, 0]]) ``` Finally, the procedure find_maximum should return 7. ### Example 2 Consider the following call: ``` find_maximum(1, [[5, 9], [1, 4], [3, 6], [2, 7]]) ``` This means that: * there is only one round, * the integers printed on the tickets of colour 0 are 5 and 9, respectively; * the integers printed on the tickets of colour 1 are 1 and 4, respectively; * the integers printed on the tickets of colour 2 are 3 and 6, respectively; * the integers printed on the tickets of colour 3 are 2 and 7, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 1 of colour 0 (with the integer 9), ticket 0 of colour 1 (with the integer 1), ticket 0 of colour 2 (with the integer 3), and ticket 1 of colour 3 (with the integer 7). The lowest possible value of the prize in this round is 12, when the game master chooses b = 3: |3 βˆ’ 9| + |3 βˆ’ 1| + |3 βˆ’ 3| + |3 βˆ’ 7| = 6 + 2 + 0 + 4 = 12. To report this solution, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[-1, 0], [0, -1], [0, -1], [-1, 0]]) ``` Finally, the procedure find_maximum should return 12. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le n \le 1500$ and $n$ is even. * $1 \le k \le m \le 1500$ * $0 \le x[i][j] \le 10^9$ (for all $0 \le i \le n - 1$ and $0 \le j \le m - 1$) * $x[i][j - 1] \le x[i][j]$ (for all $0 \le i \le n - 1$ and $1 \le j \le m - 1$) * For each call to count_tastiness, the sum of tastiness values of all biscuits in the pantry does not exceed $10^{18}$. * $k = m$ ## Sample grader The sample grader reads the input in the following format: * line 1: n m k * line 2 + i (0 ≀ i ≀ n βˆ’ 1): x[i][0] x[i][1] ... x[i][m βˆ’ 1] The sample grader prints your answer in the following format: * line 1: the return value of find_maximum * line 2 + i (0 ≀ i ≀ n βˆ’ 1): s[i][0] s[i][1] ... s[i][m βˆ’ 1]
Python
seed_208
# Carnival Tickets (tickets) Ringo is at a carnival in Singapore. He has some prize tickets in his bag, which he would like to use at the prize game stall. Each ticket comes in one of n colours and has a non-negative integer printed on it. The integers printed on different tickets might be the same. Due to a quirk in the carnival rules, n is guaranteed to be even. Ringo has m tickets of each colour in his bag, that is a total of n Β· m tickets. The ticket j of the colour i has the integer x[i][j] printed on it (0 ≀ i ≀ n βˆ’ 1 and 0 ≀ j ≀ m βˆ’ 1). The prize game is played in k rounds, numbered from 0 to k βˆ’ 1. Each round is played in the following order: * From his bag, Ringo selects a set of n tickets, one ticket from each colour. He then gives the set to the game master. * The game master notes down the integers a[0], a[1] ... a[n βˆ’ 1] printed on the tickets of the set. The order of these n integers is not important. * The game master pulls out a special card from a lucky draw box and notes down the integer b printed on that card. * The game master calculates the absolute differences between a[i] and b for each i from 0 to n βˆ’ 1. Let S be the sum of these absolute differences. * For this round, the game master gives Ringo a prize with a value equal to S. * The tickets in the set are discarded and cannot be used in future rounds. The remaining tickets in Ringo's bag after k rounds of the game are discarded. By watching closely, Ringo realized that the prize game is rigged! There is actually a printer inside the lucky draw box. In each round, the game master finds an integer b that minimizes the value of the prize of that round. The value chosen by the game master is printed on the special card for that round. Having all this information, Ringo would like to allocate tickets to the rounds of the game. That is, he wants to select the ticket set to use in each round in order to maximize the total value of the prizes. ## Implementation details You should implement the following procedure: ``` int64 find_maximum(int k, int[][] x) ``` * k: the number of rounds. * x: an n Γ— m array describing the integers on each ticket. Tickets of each color are sorted in non-decreasing order of their integers. * This procedure is called exactly once. * This procedure should make exactly one call to allocate_tickets (see below), describing k ticket sets, one for each round. The allocation should maximize the total value of the prizes. * This procedure should return the maximum total value of the prizes. The procedure allocate_tickets is defined as follows: ``` void allocate_tickets(int[][] s) ``` * s: an n Γ— m array. The value of s[i][j] should be r if the ticket j of the colour i is used in the set of round r of the game, or βˆ’1 if it is not used at all. * For each 0 ≀ i ≀ n βˆ’ 1, among s[i][0], s[i][1], . . . , s[i][m βˆ’ 1] each value 0, 1, 2, . . . , k βˆ’ 1 must occur exactly once, and all other entries must be βˆ’1. * If there are multiple allocations resulting in the maximum total prize value, it is allowed to report any of them. ## Examples ### Example 1 Consider the following call: ``` find_maximum(2, [[0, 2, 5],[1, 1, 3]]) ``` This means that: * there are k = 2 rounds; * the integers printed on the tickets of colour 0 are 0, 2 and 5, respectively; * the integers printed on the tickets of colour 1 are 1, 1 and 3, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 0 of colour 0 (with the integer 0) and ticket 2 of colour 1 (with the integer 3). The lowest possible value of the prize in this round is 3. E.g., the game master may choose b = 0: |0 βˆ’ 0| + |3 βˆ’ 0| = 0 + 3 = 3. * In round 1, Ringo picks ticket 2 of colour 0 (with the integer 5) and ticket 1 of colour 1 (with the integer 1). The lowest possible value of the prize in this round is 4. E.g., the game master may choose b = 3: |5 βˆ’ 3| + |1 βˆ’ 3| = 2 + 2 = 4. * Therefore, the total value of the prizes would be 3 + 4 = 7. To report this allocation, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[0, -1, 1], [-1, 1, 0]]) ``` Finally, the procedure find_maximum should return 7. ### Example 2 Consider the following call: ``` find_maximum(1, [[5, 9], [1, 4], [3, 6], [2, 7]]) ``` This means that: * there is only one round, * the integers printed on the tickets of colour 0 are 5 and 9, respectively; * the integers printed on the tickets of colour 1 are 1 and 4, respectively; * the integers printed on the tickets of colour 2 are 3 and 6, respectively; * the integers printed on the tickets of colour 3 are 2 and 7, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 1 of colour 0 (with the integer 9), ticket 0 of colour 1 (with the integer 1), ticket 0 of colour 2 (with the integer 3), and ticket 1 of colour 3 (with the integer 7). The lowest possible value of the prize in this round is 12, when the game master chooses b = 3: |3 βˆ’ 9| + |3 βˆ’ 1| + |3 βˆ’ 3| + |3 βˆ’ 7| = 6 + 2 + 0 + 4 = 12. To report this solution, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[-1, 0], [0, -1], [0, -1], [-1, 0]]) ``` Finally, the procedure find_maximum should return 12. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le n \le 1500$ and $n$ is even. * $1 \le k \le m \le 1500$ * $0 \le x[i][j] \le 10^9$ (for all $0 \le i \le n - 1$ and $0 \le j \le m - 1$) * $x[i][j - 1] \le x[i][j]$ (for all $0 \le i \le n - 1$ and $1 \le j \le m - 1$) * For each call to count_tastiness, the sum of tastiness values of all biscuits in the pantry does not exceed $10^{18}$. * $n, m \le 300$ ## Sample grader The sample grader reads the input in the following format: * line 1: n m k * line 2 + i (0 ≀ i ≀ n βˆ’ 1): x[i][0] x[i][1] ... x[i][m βˆ’ 1] The sample grader prints your answer in the following format: * line 1: the return value of find_maximum * line 2 + i (0 ≀ i ≀ n βˆ’ 1): s[i][0] s[i][1] ... s[i][m βˆ’ 1]
Python
seed_209
# Carnival Tickets (tickets) Ringo is at a carnival in Singapore. He has some prize tickets in his bag, which he would like to use at the prize game stall. Each ticket comes in one of n colours and has a non-negative integer printed on it. The integers printed on different tickets might be the same. Due to a quirk in the carnival rules, n is guaranteed to be even. Ringo has m tickets of each colour in his bag, that is a total of n Β· m tickets. The ticket j of the colour i has the integer x[i][j] printed on it (0 ≀ i ≀ n βˆ’ 1 and 0 ≀ j ≀ m βˆ’ 1). The prize game is played in k rounds, numbered from 0 to k βˆ’ 1. Each round is played in the following order: * From his bag, Ringo selects a set of n tickets, one ticket from each colour. He then gives the set to the game master. * The game master notes down the integers a[0], a[1] ... a[n βˆ’ 1] printed on the tickets of the set. The order of these n integers is not important. * The game master pulls out a special card from a lucky draw box and notes down the integer b printed on that card. * The game master calculates the absolute differences between a[i] and b for each i from 0 to n βˆ’ 1. Let S be the sum of these absolute differences. * For this round, the game master gives Ringo a prize with a value equal to S. * The tickets in the set are discarded and cannot be used in future rounds. The remaining tickets in Ringo's bag after k rounds of the game are discarded. By watching closely, Ringo realized that the prize game is rigged! There is actually a printer inside the lucky draw box. In each round, the game master finds an integer b that minimizes the value of the prize of that round. The value chosen by the game master is printed on the special card for that round. Having all this information, Ringo would like to allocate tickets to the rounds of the game. That is, he wants to select the ticket set to use in each round in order to maximize the total value of the prizes. ## Implementation details You should implement the following procedure: ``` int64 find_maximum(int k, int[][] x) ``` * k: the number of rounds. * x: an n Γ— m array describing the integers on each ticket. Tickets of each color are sorted in non-decreasing order of their integers. * This procedure is called exactly once. * This procedure should make exactly one call to allocate_tickets (see below), describing k ticket sets, one for each round. The allocation should maximize the total value of the prizes. * This procedure should return the maximum total value of the prizes. The procedure allocate_tickets is defined as follows: ``` void allocate_tickets(int[][] s) ``` * s: an n Γ— m array. The value of s[i][j] should be r if the ticket j of the colour i is used in the set of round r of the game, or βˆ’1 if it is not used at all. * For each 0 ≀ i ≀ n βˆ’ 1, among s[i][0], s[i][1], . . . , s[i][m βˆ’ 1] each value 0, 1, 2, . . . , k βˆ’ 1 must occur exactly once, and all other entries must be βˆ’1. * If there are multiple allocations resulting in the maximum total prize value, it is allowed to report any of them. ## Examples ### Example 1 Consider the following call: ``` find_maximum(2, [[0, 2, 5],[1, 1, 3]]) ``` This means that: * there are k = 2 rounds; * the integers printed on the tickets of colour 0 are 0, 2 and 5, respectively; * the integers printed on the tickets of colour 1 are 1, 1 and 3, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 0 of colour 0 (with the integer 0) and ticket 2 of colour 1 (with the integer 3). The lowest possible value of the prize in this round is 3. E.g., the game master may choose b = 0: |0 βˆ’ 0| + |3 βˆ’ 0| = 0 + 3 = 3. * In round 1, Ringo picks ticket 2 of colour 0 (with the integer 5) and ticket 1 of colour 1 (with the integer 1). The lowest possible value of the prize in this round is 4. E.g., the game master may choose b = 3: |5 βˆ’ 3| + |1 βˆ’ 3| = 2 + 2 = 4. * Therefore, the total value of the prizes would be 3 + 4 = 7. To report this allocation, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[0, -1, 1], [-1, 1, 0]]) ``` Finally, the procedure find_maximum should return 7. ### Example 2 Consider the following call: ``` find_maximum(1, [[5, 9], [1, 4], [3, 6], [2, 7]]) ``` This means that: * there is only one round, * the integers printed on the tickets of colour 0 are 5 and 9, respectively; * the integers printed on the tickets of colour 1 are 1 and 4, respectively; * the integers printed on the tickets of colour 2 are 3 and 6, respectively; * the integers printed on the tickets of colour 3 are 2 and 7, respectively. A possible allocation that gives the maximum total prize value is: * In round 0, Ringo picks ticket 1 of colour 0 (with the integer 9), ticket 0 of colour 1 (with the integer 1), ticket 0 of colour 2 (with the integer 3), and ticket 1 of colour 3 (with the integer 7). The lowest possible value of the prize in this round is 12, when the game master chooses b = 3: |3 βˆ’ 9| + |3 βˆ’ 1| + |3 βˆ’ 3| + |3 βˆ’ 7| = 6 + 2 + 0 + 4 = 12. To report this solution, the procedure find_maximum should make the following call to allocate_tickets: ``` allocate_tickets([[-1, 0], [0, -1], [0, -1], [-1, 0]]) ``` Finally, the procedure find_maximum should return 12. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le n \le 1500$ and $n$ is even. * $1 \le k \le m \le 1500$ * $0 \le x[i][j] \le 10^9$ (for all $0 \le i \le n - 1$ and $0 \le j \le m - 1$) * $x[i][j - 1] \le x[i][j]$ (for all $0 \le i \le n - 1$ and $1 \le j \le m - 1$) * For each call to count_tastiness, the sum of tastiness values of all biscuits in the pantry does not exceed $10^{18}$. * $n, m \le 80$ ## Sample grader The sample grader reads the input in the following format: * line 1: n m k * line 2 + i (0 ≀ i ≀ n βˆ’ 1): x[i][0] x[i][1] ... x[i][m βˆ’ 1] The sample grader prints your answer in the following format: * line 1: the return value of find_maximum * line 2 + i (0 ≀ i ≀ n βˆ’ 1): s[i][0] s[i][1] ... s[i][m βˆ’ 1]
Python
seed_211
# Catfish Farm Bu Dengklek owns a catfish farm. The catfish farm is a pond consisting of a $N \times N$ grid of cells. Each cell is a square of the same size. The columns of the grid are numbered from $0$ to $N - 1$ from west to east and the rows are numbered from $0$ to $N - 1$ from south to north. We refer to the cell located at column $c$ and row $r$ of the grid ($0 \le c \le N - 1$, $0 \le r \le N - 1$) as cell $(c, r)$. In the pond, there are $M$ catfish, numbered from $0$ to $M - 1$, located at **distinct** cells. For each $i$ such that $0 \le i \le M - 1$, catfish $i$ is located at cell $(X[i], Y[i])$, and weighs $W[i]$ grams. Bu Dengklek wants to build some piers to catch the catfish. A pier in column $c$ of length $k$ (for any $0 \le c \le N - 1$ and $1 \le k \le N$) is a rectangle extending from row $0$ to row $k - 1$, covering cells $(c, 0), (c, 1), \ldots, (c, k - 1)$. For each column, Bu Dengklek can choose either to build a pier of some length of her choice or to not build a pier. Catfish $i$ (for each $i$ such that $0 \le i \le M - 1$) can be caught if there is a pier directly to the west or east of it, and there is no pier covering its cell; that is, if * **at least one** of the cells $(X[i] - 1, Y[i])$ or $(X[i] + 1, Y[i])$ is covered by a pier, and * there is no pier covering cell $(X[i], Y[i])$. For example, consider a pond of size $N = 5$ with $M = 4$ catfish: * Catfish $0$ is located at cell $(0, 2)$ and weighs $5$ grams. * Catfish $1$ is located at cell $(1, 1)$ and weighs $2$ grams. * Catfish $2$ is located at cell $(4, 4)$ and weighs $1$ gram. * Catfish $3$ is located at cell $(3, 3)$ and weighs $3$ grams. One way Bu Dengklek can build the piers is as follows: Before the piers are built | After the piers are built :---------------------------:|:---------------------------: | The number at a cell denotes the weight of the catfish located at the cell. The shaded cells are covered by piers. In this case, catfish $0$ (at cell $(0, 2)$) and catfish $3$ (at cell $(3, 3)$) can be caught. Catfish $1$ (at cell $(1, 1)$) cannot be caught, as there is a pier covering its location, while catfish $2$ (at cell $(4, 4)$) can not be caught as there is no pier directly to the west nor east of it. Bu Dengklek would like to build piers so that the total weight of catfish she can catch is as large as possible. Your task is to find the maximum total weight of catfish that Bu Dengklek can catch after building piers. ## Implementation Details You should implement the following procedure: ``` int64 max_weights(int N, int M, int[] X, int[] Y, int[] W) ``` * $N$: the size of the pond. * $M$: the number of catfish. * $X$, $Y$: arrays of length $M$ describing catfish locations. * $W$: array of length $M$ describing catfish weights. * This procedure should return an integer representing the maximum total weight of catfish that Bu Dengklek can catch after building piers. * This procedure is called exactly once. ## Example Consider the following call: ``` max_weights(5, 4, [0, 1, 4, 3], [2, 1, 4, 3], [5, 2, 1, 3]) ``` This example is illustrated in the task description above. After building piers as described, Bu Dengklek can catch catfish $0$ and $3$, whose total weight is $5 + 3 = 8$ grams. As there is no way to build piers to catch catfish with a total weight of more than $8$ grams, the procedure should return $8$. ## Constraints * $2 \le N \le 100\,000$ * $1 \le M \le 300\,000$ * $0 \le X[i] \le N - 1$, $0 \le Y[i] \le N - 1$ (for each $i$ such that $0 \le i \le M - 1$) * $1 \le W[i] \le 10^9$ (for each $i$ such that $0 \le i \le M - 1$) * No two catfish share the same cell. In other words, $X[i] \neq X[j]$ or $Y[i] \neq Y[j]$ (for each $i$ and $j$ such that $0 \le i \lt j \le M - 1$). ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2 + i$ ($0 \le i \le M - 1$): $X[i] \; Y[i] \; W[i]$ The sample grader prints your answer in the following format: * line $1$: the return value of `max_weights`
Python
seed_212
# Catfish Farm Bu Dengklek owns a catfish farm. The catfish farm is a pond consisting of a $N \times N$ grid of cells. Each cell is a square of the same size. The columns of the grid are numbered from $0$ to $N - 1$ from west to east and the rows are numbered from $0$ to $N - 1$ from south to north. We refer to the cell located at column $c$ and row $r$ of the grid ($0 \le c \le N - 1$, $0 \le r \le N - 1$) as cell $(c, r)$. In the pond, there are $M$ catfish, numbered from $0$ to $M - 1$, located at **distinct** cells. For each $i$ such that $0 \le i \le M - 1$, catfish $i$ is located at cell $(X[i], Y[i])$, and weighs $W[i]$ grams. Bu Dengklek wants to build some piers to catch the catfish. A pier in column $c$ of length $k$ (for any $0 \le c \le N - 1$ and $1 \le k \le N$) is a rectangle extending from row $0$ to row $k - 1$, covering cells $(c, 0), (c, 1), \ldots, (c, k - 1)$. For each column, Bu Dengklek can choose either to build a pier of some length of her choice or to not build a pier. Catfish $i$ (for each $i$ such that $0 \le i \le M - 1$) can be caught if there is a pier directly to the west or east of it, and there is no pier covering its cell; that is, if * **at least one** of the cells $(X[i] - 1, Y[i])$ or $(X[i] + 1, Y[i])$ is covered by a pier, and * there is no pier covering cell $(X[i], Y[i])$. For example, consider a pond of size $N = 5$ with $M = 4$ catfish: * Catfish $0$ is located at cell $(0, 2)$ and weighs $5$ grams. * Catfish $1$ is located at cell $(1, 1)$ and weighs $2$ grams. * Catfish $2$ is located at cell $(4, 4)$ and weighs $1$ gram. * Catfish $3$ is located at cell $(3, 3)$ and weighs $3$ grams. One way Bu Dengklek can build the piers is as follows: Before the piers are built | After the piers are built :---------------------------:|:---------------------------: | The number at a cell denotes the weight of the catfish located at the cell. The shaded cells are covered by piers. In this case, catfish $0$ (at cell $(0, 2)$) and catfish $3$ (at cell $(3, 3)$) can be caught. Catfish $1$ (at cell $(1, 1)$) cannot be caught, as there is a pier covering its location, while catfish $2$ (at cell $(4, 4)$) can not be caught as there is no pier directly to the west nor east of it. Bu Dengklek would like to build piers so that the total weight of catfish she can catch is as large as possible. Your task is to find the maximum total weight of catfish that Bu Dengklek can catch after building piers. ## Implementation Details You should implement the following procedure: ``` int64 max_weights(int N, int M, int[] X, int[] Y, int[] W) ``` * $N$: the size of the pond. * $M$: the number of catfish. * $X$, $Y$: arrays of length $M$ describing catfish locations. * $W$: array of length $M$ describing catfish weights. * This procedure should return an integer representing the maximum total weight of catfish that Bu Dengklek can catch after building piers. * This procedure is called exactly once. ## Example Consider the following call: ``` max_weights(5, 4, [0, 1, 4, 3], [2, 1, 4, 3], [5, 2, 1, 3]) ``` This example is illustrated in the task description above. After building piers as described, Bu Dengklek can catch catfish $0$ and $3$, whose total weight is $5 + 3 = 8$ grams. As there is no way to build piers to catch catfish with a total weight of more than $8$ grams, the procedure should return $8$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $N \le 300$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2 + i$ ($0 \le i \le M - 1$): $X[i] \; Y[i] \; W[i]$ The sample grader prints your answer in the following format: * line $1$: the return value of `max_weights`
Python
seed_213
# Catfish Farm Bu Dengklek owns a catfish farm. The catfish farm is a pond consisting of a $N \times N$ grid of cells. Each cell is a square of the same size. The columns of the grid are numbered from $0$ to $N - 1$ from west to east and the rows are numbered from $0$ to $N - 1$ from south to north. We refer to the cell located at column $c$ and row $r$ of the grid ($0 \le c \le N - 1$, $0 \le r \le N - 1$) as cell $(c, r)$. In the pond, there are $M$ catfish, numbered from $0$ to $M - 1$, located at **distinct** cells. For each $i$ such that $0 \le i \le M - 1$, catfish $i$ is located at cell $(X[i], Y[i])$, and weighs $W[i]$ grams. Bu Dengklek wants to build some piers to catch the catfish. A pier in column $c$ of length $k$ (for any $0 \le c \le N - 1$ and $1 \le k \le N$) is a rectangle extending from row $0$ to row $k - 1$, covering cells $(c, 0), (c, 1), \ldots, (c, k - 1)$. For each column, Bu Dengklek can choose either to build a pier of some length of her choice or to not build a pier. Catfish $i$ (for each $i$ such that $0 \le i \le M - 1$) can be caught if there is a pier directly to the west or east of it, and there is no pier covering its cell; that is, if * **at least one** of the cells $(X[i] - 1, Y[i])$ or $(X[i] + 1, Y[i])$ is covered by a pier, and * there is no pier covering cell $(X[i], Y[i])$. For example, consider a pond of size $N = 5$ with $M = 4$ catfish: * Catfish $0$ is located at cell $(0, 2)$ and weighs $5$ grams. * Catfish $1$ is located at cell $(1, 1)$ and weighs $2$ grams. * Catfish $2$ is located at cell $(4, 4)$ and weighs $1$ gram. * Catfish $3$ is located at cell $(3, 3)$ and weighs $3$ grams. One way Bu Dengklek can build the piers is as follows: Before the piers are built | After the piers are built :---------------------------:|:---------------------------: | The number at a cell denotes the weight of the catfish located at the cell. The shaded cells are covered by piers. In this case, catfish $0$ (at cell $(0, 2)$) and catfish $3$ (at cell $(3, 3)$) can be caught. Catfish $1$ (at cell $(1, 1)$) cannot be caught, as there is a pier covering its location, while catfish $2$ (at cell $(4, 4)$) can not be caught as there is no pier directly to the west nor east of it. Bu Dengklek would like to build piers so that the total weight of catfish she can catch is as large as possible. Your task is to find the maximum total weight of catfish that Bu Dengklek can catch after building piers. ## Implementation Details You should implement the following procedure: ``` int64 max_weights(int N, int M, int[] X, int[] Y, int[] W) ``` * $N$: the size of the pond. * $M$: the number of catfish. * $X$, $Y$: arrays of length $M$ describing catfish locations. * $W$: array of length $M$ describing catfish weights. * This procedure should return an integer representing the maximum total weight of catfish that Bu Dengklek can catch after building piers. * This procedure is called exactly once. ## Example Consider the following call: ``` max_weights(5, 4, [0, 1, 4, 3], [2, 1, 4, 3], [5, 2, 1, 3]) ``` This example is illustrated in the task description above. After building piers as described, Bu Dengklek can catch catfish $0$ and $3$, whose total weight is $5 + 3 = 8$ grams. As there is no way to build piers to catch catfish with a total weight of more than $8$ grams, the procedure should return $8$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $N \le 300$ * $Y[i] \le 8$ (for each $i$ such that $0 \le i \le M - 1$) ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2 + i$ ($0 \le i \le M - 1$): $X[i] \; Y[i] \; W[i]$ The sample grader prints your answer in the following format: * line $1$: the return value of `max_weights`
Python
seed_214
# Catfish Farm Bu Dengklek owns a catfish farm. The catfish farm is a pond consisting of a $N \times N$ grid of cells. Each cell is a square of the same size. The columns of the grid are numbered from $0$ to $N - 1$ from west to east and the rows are numbered from $0$ to $N - 1$ from south to north. We refer to the cell located at column $c$ and row $r$ of the grid ($0 \le c \le N - 1$, $0 \le r \le N - 1$) as cell $(c, r)$. In the pond, there are $M$ catfish, numbered from $0$ to $M - 1$, located at **distinct** cells. For each $i$ such that $0 \le i \le M - 1$, catfish $i$ is located at cell $(X[i], Y[i])$, and weighs $W[i]$ grams. Bu Dengklek wants to build some piers to catch the catfish. A pier in column $c$ of length $k$ (for any $0 \le c \le N - 1$ and $1 \le k \le N$) is a rectangle extending from row $0$ to row $k - 1$, covering cells $(c, 0), (c, 1), \ldots, (c, k - 1)$. For each column, Bu Dengklek can choose either to build a pier of some length of her choice or to not build a pier. Catfish $i$ (for each $i$ such that $0 \le i \le M - 1$) can be caught if there is a pier directly to the west or east of it, and there is no pier covering its cell; that is, if * **at least one** of the cells $(X[i] - 1, Y[i])$ or $(X[i] + 1, Y[i])$ is covered by a pier, and * there is no pier covering cell $(X[i], Y[i])$. For example, consider a pond of size $N = 5$ with $M = 4$ catfish: * Catfish $0$ is located at cell $(0, 2)$ and weighs $5$ grams. * Catfish $1$ is located at cell $(1, 1)$ and weighs $2$ grams. * Catfish $2$ is located at cell $(4, 4)$ and weighs $1$ gram. * Catfish $3$ is located at cell $(3, 3)$ and weighs $3$ grams. One way Bu Dengklek can build the piers is as follows: Before the piers are built | After the piers are built :---------------------------:|:---------------------------: | The number at a cell denotes the weight of the catfish located at the cell. The shaded cells are covered by piers. In this case, catfish $0$ (at cell $(0, 2)$) and catfish $3$ (at cell $(3, 3)$) can be caught. Catfish $1$ (at cell $(1, 1)$) cannot be caught, as there is a pier covering its location, while catfish $2$ (at cell $(4, 4)$) can not be caught as there is no pier directly to the west nor east of it. Bu Dengklek would like to build piers so that the total weight of catfish she can catch is as large as possible. Your task is to find the maximum total weight of catfish that Bu Dengklek can catch after building piers. ## Implementation Details You should implement the following procedure: ``` int64 max_weights(int N, int M, int[] X, int[] Y, int[] W) ``` * $N$: the size of the pond. * $M$: the number of catfish. * $X$, $Y$: arrays of length $M$ describing catfish locations. * $W$: array of length $M$ describing catfish weights. * This procedure should return an integer representing the maximum total weight of catfish that Bu Dengklek can catch after building piers. * This procedure is called exactly once. ## Example Consider the following call: ``` max_weights(5, 4, [0, 1, 4, 3], [2, 1, 4, 3], [5, 2, 1, 3]) ``` This example is illustrated in the task description above. After building piers as described, Bu Dengklek can catch catfish $0$ and $3$, whose total weight is $5 + 3 = 8$ grams. As there is no way to build piers to catch catfish with a total weight of more than $8$ grams, the procedure should return $8$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $N \le 3000$ ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2 + i$ ($0 \le i \le M - 1$): $X[i] \; Y[i] \; W[i]$ The sample grader prints your answer in the following format: * line $1$: the return value of `max_weights`
Python
seed_215
# Catfish Farm Bu Dengklek owns a catfish farm. The catfish farm is a pond consisting of a $N \times N$ grid of cells. Each cell is a square of the same size. The columns of the grid are numbered from $0$ to $N - 1$ from west to east and the rows are numbered from $0$ to $N - 1$ from south to north. We refer to the cell located at column $c$ and row $r$ of the grid ($0 \le c \le N - 1$, $0 \le r \le N - 1$) as cell $(c, r)$. In the pond, there are $M$ catfish, numbered from $0$ to $M - 1$, located at **distinct** cells. For each $i$ such that $0 \le i \le M - 1$, catfish $i$ is located at cell $(X[i], Y[i])$, and weighs $W[i]$ grams. Bu Dengklek wants to build some piers to catch the catfish. A pier in column $c$ of length $k$ (for any $0 \le c \le N - 1$ and $1 \le k \le N$) is a rectangle extending from row $0$ to row $k - 1$, covering cells $(c, 0), (c, 1), \ldots, (c, k - 1)$. For each column, Bu Dengklek can choose either to build a pier of some length of her choice or to not build a pier. Catfish $i$ (for each $i$ such that $0 \le i \le M - 1$) can be caught if there is a pier directly to the west or east of it, and there is no pier covering its cell; that is, if * **at least one** of the cells $(X[i] - 1, Y[i])$ or $(X[i] + 1, Y[i])$ is covered by a pier, and * there is no pier covering cell $(X[i], Y[i])$. For example, consider a pond of size $N = 5$ with $M = 4$ catfish: * Catfish $0$ is located at cell $(0, 2)$ and weighs $5$ grams. * Catfish $1$ is located at cell $(1, 1)$ and weighs $2$ grams. * Catfish $2$ is located at cell $(4, 4)$ and weighs $1$ gram. * Catfish $3$ is located at cell $(3, 3)$ and weighs $3$ grams. One way Bu Dengklek can build the piers is as follows: Before the piers are built | After the piers are built :---------------------------:|:---------------------------: | The number at a cell denotes the weight of the catfish located at the cell. The shaded cells are covered by piers. In this case, catfish $0$ (at cell $(0, 2)$) and catfish $3$ (at cell $(3, 3)$) can be caught. Catfish $1$ (at cell $(1, 1)$) cannot be caught, as there is a pier covering its location, while catfish $2$ (at cell $(4, 4)$) can not be caught as there is no pier directly to the west nor east of it. Bu Dengklek would like to build piers so that the total weight of catfish she can catch is as large as possible. Your task is to find the maximum total weight of catfish that Bu Dengklek can catch after building piers. ## Implementation Details You should implement the following procedure: ``` int64 max_weights(int N, int M, int[] X, int[] Y, int[] W) ``` * $N$: the size of the pond. * $M$: the number of catfish. * $X$, $Y$: arrays of length $M$ describing catfish locations. * $W$: array of length $M$ describing catfish weights. * This procedure should return an integer representing the maximum total weight of catfish that Bu Dengklek can catch after building piers. * This procedure is called exactly once. ## Example Consider the following call: ``` max_weights(5, 4, [0, 1, 4, 3], [2, 1, 4, 3], [5, 2, 1, 3]) ``` This example is illustrated in the task description above. After building piers as described, Bu Dengklek can catch catfish $0$ and $3$, whose total weight is $5 + 3 = 8$ grams. As there is no way to build piers to catch catfish with a total weight of more than $8$ grams, the procedure should return $8$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $X[i] \le 1$ (for each $i$ such that $0 \le i \le M - 1$) ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2 + i$ ($0 \le i \le M - 1$): $X[i] \; Y[i] \; W[i]$ The sample grader prints your answer in the following format: * line $1$: the return value of `max_weights`
Python
seed_217
# Catfish Farm Bu Dengklek owns a catfish farm. The catfish farm is a pond consisting of a $N \times N$ grid of cells. Each cell is a square of the same size. The columns of the grid are numbered from $0$ to $N - 1$ from west to east and the rows are numbered from $0$ to $N - 1$ from south to north. We refer to the cell located at column $c$ and row $r$ of the grid ($0 \le c \le N - 1$, $0 \le r \le N - 1$) as cell $(c, r)$. In the pond, there are $M$ catfish, numbered from $0$ to $M - 1$, located at **distinct** cells. For each $i$ such that $0 \le i \le M - 1$, catfish $i$ is located at cell $(X[i], Y[i])$, and weighs $W[i]$ grams. Bu Dengklek wants to build some piers to catch the catfish. A pier in column $c$ of length $k$ (for any $0 \le c \le N - 1$ and $1 \le k \le N$) is a rectangle extending from row $0$ to row $k - 1$, covering cells $(c, 0), (c, 1), \ldots, (c, k - 1)$. For each column, Bu Dengklek can choose either to build a pier of some length of her choice or to not build a pier. Catfish $i$ (for each $i$ such that $0 \le i \le M - 1$) can be caught if there is a pier directly to the west or east of it, and there is no pier covering its cell; that is, if * **at least one** of the cells $(X[i] - 1, Y[i])$ or $(X[i] + 1, Y[i])$ is covered by a pier, and * there is no pier covering cell $(X[i], Y[i])$. For example, consider a pond of size $N = 5$ with $M = 4$ catfish: * Catfish $0$ is located at cell $(0, 2)$ and weighs $5$ grams. * Catfish $1$ is located at cell $(1, 1)$ and weighs $2$ grams. * Catfish $2$ is located at cell $(4, 4)$ and weighs $1$ gram. * Catfish $3$ is located at cell $(3, 3)$ and weighs $3$ grams. One way Bu Dengklek can build the piers is as follows: Before the piers are built | After the piers are built :---------------------------:|:---------------------------: | The number at a cell denotes the weight of the catfish located at the cell. The shaded cells are covered by piers. In this case, catfish $0$ (at cell $(0, 2)$) and catfish $3$ (at cell $(3, 3)$) can be caught. Catfish $1$ (at cell $(1, 1)$) cannot be caught, as there is a pier covering its location, while catfish $2$ (at cell $(4, 4)$) can not be caught as there is no pier directly to the west nor east of it. Bu Dengklek would like to build piers so that the total weight of catfish she can catch is as large as possible. Your task is to find the maximum total weight of catfish that Bu Dengklek can catch after building piers. ## Implementation Details You should implement the following procedure: ``` int64 max_weights(int N, int M, int[] X, int[] Y, int[] W) ``` * $N$: the size of the pond. * $M$: the number of catfish. * $X$, $Y$: arrays of length $M$ describing catfish locations. * $W$: array of length $M$ describing catfish weights. * This procedure should return an integer representing the maximum total weight of catfish that Bu Dengklek can catch after building piers. * This procedure is called exactly once. ## Example Consider the following call: ``` max_weights(5, 4, [0, 1, 4, 3], [2, 1, 4, 3], [5, 2, 1, 3]) ``` This example is illustrated in the task description above. After building piers as described, Bu Dengklek can catch catfish $0$ and $3$, whose total weight is $5 + 3 = 8$ grams. As there is no way to build piers to catch catfish with a total weight of more than $8$ grams, the procedure should return $8$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $Y[i] = 0$ (for each $i$ such that $0 \le i \le M - 1$) ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2 + i$ ($0 \le i \le M - 1$): $X[i] \; Y[i] \; W[i]$ The sample grader prints your answer in the following format: * line $1$: the return value of `max_weights`
Python
seed_218
# Catfish Farm Bu Dengklek owns a catfish farm. The catfish farm is a pond consisting of a $N \times N$ grid of cells. Each cell is a square of the same size. The columns of the grid are numbered from $0$ to $N - 1$ from west to east and the rows are numbered from $0$ to $N - 1$ from south to north. We refer to the cell located at column $c$ and row $r$ of the grid ($0 \le c \le N - 1$, $0 \le r \le N - 1$) as cell $(c, r)$. In the pond, there are $M$ catfish, numbered from $0$ to $M - 1$, located at **distinct** cells. For each $i$ such that $0 \le i \le M - 1$, catfish $i$ is located at cell $(X[i], Y[i])$, and weighs $W[i]$ grams. Bu Dengklek wants to build some piers to catch the catfish. A pier in column $c$ of length $k$ (for any $0 \le c \le N - 1$ and $1 \le k \le N$) is a rectangle extending from row $0$ to row $k - 1$, covering cells $(c, 0), (c, 1), \ldots, (c, k - 1)$. For each column, Bu Dengklek can choose either to build a pier of some length of her choice or to not build a pier. Catfish $i$ (for each $i$ such that $0 \le i \le M - 1$) can be caught if there is a pier directly to the west or east of it, and there is no pier covering its cell; that is, if * **at least one** of the cells $(X[i] - 1, Y[i])$ or $(X[i] + 1, Y[i])$ is covered by a pier, and * there is no pier covering cell $(X[i], Y[i])$. For example, consider a pond of size $N = 5$ with $M = 4$ catfish: * Catfish $0$ is located at cell $(0, 2)$ and weighs $5$ grams. * Catfish $1$ is located at cell $(1, 1)$ and weighs $2$ grams. * Catfish $2$ is located at cell $(4, 4)$ and weighs $1$ gram. * Catfish $3$ is located at cell $(3, 3)$ and weighs $3$ grams. One way Bu Dengklek can build the piers is as follows: Before the piers are built | After the piers are built :---------------------------:|:---------------------------: | The number at a cell denotes the weight of the catfish located at the cell. The shaded cells are covered by piers. In this case, catfish $0$ (at cell $(0, 2)$) and catfish $3$ (at cell $(3, 3)$) can be caught. Catfish $1$ (at cell $(1, 1)$) cannot be caught, as there is a pier covering its location, while catfish $2$ (at cell $(4, 4)$) can not be caught as there is no pier directly to the west nor east of it. Bu Dengklek would like to build piers so that the total weight of catfish she can catch is as large as possible. Your task is to find the maximum total weight of catfish that Bu Dengklek can catch after building piers. ## Implementation Details You should implement the following procedure: ``` int64 max_weights(int N, int M, int[] X, int[] Y, int[] W) ``` * $N$: the size of the pond. * $M$: the number of catfish. * $X$, $Y$: arrays of length $M$ describing catfish locations. * $W$: array of length $M$ describing catfish weights. * This procedure should return an integer representing the maximum total weight of catfish that Bu Dengklek can catch after building piers. * This procedure is called exactly once. ## Example Consider the following call: ``` max_weights(5, 4, [0, 1, 4, 3], [2, 1, 4, 3], [5, 2, 1, 3]) ``` This example is illustrated in the task description above. After building piers as described, Bu Dengklek can catch catfish $0$ and $3$, whose total weight is $5 + 3 = 8$ grams. As there is no way to build piers to catch catfish with a total weight of more than $8$ grams, the procedure should return $8$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * There are at most $2$ catfish in each column. ## Sample Grader The sample grader reads the input in the following format: * line $1$: $N \; M$ * line $2 + i$ ($0 \le i \le M - 1$): $X[i] \; Y[i] \; W[i]$ The sample grader prints your answer in the following format: * line $1$: the return value of `max_weights`
Python
seed_221
# Choreography The Hungarian National Dance Ensemble is practicing a new choreography. There are $N$ dancers in the ensemble, numbered from $0$ to $N-1$, where $N$ is an **even** number. At the practice sessions, the choreographer first lines up the dancers. The positions in the line are numbered from $0$ to $N-1$, and position $i$ is occupied by dancer $P[i]$ at the start. After the dancers line up, the choreographer asks them to perform a sequence of **moves**. Each move must be completed before they begin performing the next one. The dancers are practicing 4 types of moves: 1. Every dancer moves $K$ positions to the right cyclically, where $0 \le K < N$. That is, * for each $i$ from $0$ to $N-K-1$, inclusive, the dancer currently standing at position $i$ moves to position $i+K$, and * for each $i$ from $N-K$ to $N-1$, inclusive, the dancer currently standing at position $i$ moves to position $i+K-N$. 2. Every dancer moves $K$ positions to the left cyclically, where $0 \le K < N$. That is, * for each $i$ from $K$ to $N-1$, inclusive, the dancer currently standing at position $i$ moves to position $i-K$, and * for each $i$ from $0$ to $K-1$, inclusive, the dancer currently standing at position $i$ moves to position $i-K+N$. 3. For each $i$ from $0$ to $ rac{N}{2}-1$, inclusive, dancers at positions $2i$ and $2i+1$ swap places. 4. Suppose that position $i$ ($0 \le i < N$) is occupied by dancer $r_i$ before performing this move. For each $j$ from $0$ to $N-1$, inclusive, dancer $j$ moves to position $r_j$. Note that the positions of the dancers are distinct at the end of each move. Before the next session, the choreographer plans a sequence of $M$ moves for the ensemble to practice. He adds the moves to the sequence one by one. Sometimes, before adding the next move, he wonders which positions certain dancers will occupy right after performing every move that has been added to the sequence. Your task is to simulate the dance moves planned by the choreographer and answer his questions about the positions of the dancers. ## Implementation Details You should implement the following procedures: ``` void init(int N, int[] P) ``` * $N$: the number of dancers. * $P$: array of length $N$ describing the initial order of the dancers. * This procedure is called exactly once, before any other function calls. ``` void move_right(int K) ``` * $K$: the number of positions each dancer moves to the right. * This procedure adds a move of type 1 to the sequence of moves. ``` void move_left(int K) ``` * $K$: the number of positions each dancer moves to the left. * This procedure adds a move of type 2 to the sequence of moves. ``` void swap_places() ``` * This procedure adds a move of type 3 to the sequence of moves. ``` void move_around() ``` * This procedure adds a move of type 4 to the sequence of moves. Procedures `move_right`, `move_left`, `swap_places`, and `move_around` are called for a total of $M$ times. ``` int get_position(int D) ``` * $D$: an integer representing a dancer. * This procedure should return the position of dancer $D$ after performing every move added to the sequence of moves before this call. * This procedure is called $Q$ times. ## Example Consider the following sequence of calls: ``` init(6, [5, 1, 4, 2, 0, 3]) ``` There are 6 dancers, and the initial order of the dancers is given by the array [5, 1, 4, 2, 0, 3], that is, position 0 is occupied by dancer 5, position 1 is occupied by dancer 1, position 2 is occupied by dancer 4, and so on. ``` move_left(2) ``` Each dancer moves two places to the left cyclically. After the move, the order of the dancers becomes [4, 2, 0, 3, 5, 1]. ``` get_position(0) ``` This call asks the position of dancer 0 after performing the first move. Dancer 0 is standing at position 2. Therefore, the procedure should return 2. ``` swap_places() ``` After this move, the order of the dancers becomes [2, 4, 3, 0, 1, 5]. ``` move_around() ``` The new position of each dancer is determined as follows. * Dancer 0: position 0 is occupied by dancer 2, so dancer 0 moves to position 2. * Dancer 1: position 1 is occupied by dancer 4, so dancer 1 stays at position 4. * Dancer 2: position 2 is occupied by dancer 3, so dancer 2 moves to position 3. * Dancer 3: position 3 is occupied by dancer 0, so dancer 3 moves to position 0. * Dancer 4: position 4 is occupied by dancer 1, so dancer 4 stays at position 1. * Dancer 5: position 5 is occupied by dancer 5, so dancer 5 stays at position 5. After this move, the order of the dancers becomes [3, 4, 0, 2, 1, 5]. ``` get_position(3) ``` Dancer 3 is at position 0 after performing every move so far. The procedure should return 0. ## Constraints * $1 \le N \le 100\,000$ * $0 \le P[i] < N$ (for each $i$ such that $0 \le i < N$) * $P[i] \ne P[j]$ (for each $i$ and $j$ such that $0 \le i < j < N$) * $0 \le M \le 100\,000$ * $1 \le Q \le 200\,000$ * $0 \le K < N$ * $0 \le D < N$ ## Sample Grader The sample grader reads the input in the following format: * line 1: $N \; M \; Q$ * line 2: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line 3 + $l$ ($0 \le l < M + Q$): * To perform a move of type 1: $1 \; K$ * To perform a move of type 2: $2 \; K$ * To perform a move of type 3: $3$ * To perform a move of type 4: $4$ * To ask the position of a dancer: $5 \; D$ The sample grader prints your answers in the following format: * line 1 + $q$ ($0 \le q < Q$): the values returned by `get_position`
Python
seed_225
# Choreography The Hungarian National Dance Ensemble is practicing a new choreography. There are $N$ dancers in the ensemble, numbered from $0$ to $N-1$, where $N$ is an **even** number. At the practice sessions, the choreographer first lines up the dancers. The positions in the line are numbered from $0$ to $N-1$, and position $i$ is occupied by dancer $P[i]$ at the start. After the dancers line up, the choreographer asks them to perform a sequence of **moves**. Each move must be completed before they begin performing the next one. The dancers are practicing 4 types of moves: 1. Every dancer moves $K$ positions to the right cyclically, where $0 \le K < N$. That is, * for each $i$ from $0$ to $N-K-1$, inclusive, the dancer currently standing at position $i$ moves to position $i+K$, and * for each $i$ from $N-K$ to $N-1$, inclusive, the dancer currently standing at position $i$ moves to position $i+K-N$. 2. Every dancer moves $K$ positions to the left cyclically, where $0 \le K < N$. That is, * for each $i$ from $K$ to $N-1$, inclusive, the dancer currently standing at position $i$ moves to position $i-K$, and * for each $i$ from $0$ to $K-1$, inclusive, the dancer currently standing at position $i$ moves to position $i-K+N$. 3. For each $i$ from $0$ to $ rac{N}{2}-1$, inclusive, dancers at positions $2i$ and $2i+1$ swap places. 4. Suppose that position $i$ ($0 \le i < N$) is occupied by dancer $r_i$ before performing this move. For each $j$ from $0$ to $N-1$, inclusive, dancer $j$ moves to position $r_j$. Note that the positions of the dancers are distinct at the end of each move. Before the next session, the choreographer plans a sequence of $M$ moves for the ensemble to practice. He adds the moves to the sequence one by one. Sometimes, before adding the next move, he wonders which positions certain dancers will occupy right after performing every move that has been added to the sequence. Your task is to simulate the dance moves planned by the choreographer and answer his questions about the positions of the dancers. ## Implementation Details You should implement the following procedures: ``` void init(int N, int[] P) ``` * $N$: the number of dancers. * $P$: array of length $N$ describing the initial order of the dancers. * This procedure is called exactly once, before any other function calls. ``` void move_right(int K) ``` * $K$: the number of positions each dancer moves to the right. * This procedure adds a move of type 1 to the sequence of moves. ``` void move_left(int K) ``` * $K$: the number of positions each dancer moves to the left. * This procedure adds a move of type 2 to the sequence of moves. ``` void swap_places() ``` * This procedure adds a move of type 3 to the sequence of moves. ``` void move_around() ``` * This procedure adds a move of type 4 to the sequence of moves. Procedures `move_right`, `move_left`, `swap_places`, and `move_around` are called for a total of $M$ times. ``` int get_position(int D) ``` * $D$: an integer representing a dancer. * This procedure should return the position of dancer $D$ after performing every move added to the sequence of moves before this call. * This procedure is called $Q$ times. ## Example Consider the following sequence of calls: ``` init(6, [5, 1, 4, 2, 0, 3]) ``` There are 6 dancers, and the initial order of the dancers is given by the array [5, 1, 4, 2, 0, 3], that is, position 0 is occupied by dancer 5, position 1 is occupied by dancer 1, position 2 is occupied by dancer 4, and so on. ``` move_left(2) ``` Each dancer moves two places to the left cyclically. After the move, the order of the dancers becomes [4, 2, 0, 3, 5, 1]. ``` get_position(0) ``` This call asks the position of dancer 0 after performing the first move. Dancer 0 is standing at position 2. Therefore, the procedure should return 2. ``` swap_places() ``` After this move, the order of the dancers becomes [2, 4, 3, 0, 1, 5]. ``` move_around() ``` The new position of each dancer is determined as follows. * Dancer 0: position 0 is occupied by dancer 2, so dancer 0 moves to position 2. * Dancer 1: position 1 is occupied by dancer 4, so dancer 1 stays at position 4. * Dancer 2: position 2 is occupied by dancer 3, so dancer 2 moves to position 3. * Dancer 3: position 3 is occupied by dancer 0, so dancer 3 moves to position 0. * Dancer 4: position 4 is occupied by dancer 1, so dancer 4 stays at position 1. * Dancer 5: position 5 is occupied by dancer 5, so dancer 5 stays at position 5. After this move, the order of the dancers becomes [3, 4, 0, 2, 1, 5]. ``` get_position(3) ``` Dancer 3 is at position 0 after performing every move so far. The procedure should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le N \le 100\,000$ * $0 \le P[i] < N$ (for each $i$ such that $0 \le i < N$) * $P[i] \ne P[j]$ (for each $i$ and $j$ such that $0 \le i < j < N$) * $0 \le M \le 100\,000$ * $1 \le Q \le 200\,000$ * $0 \le K < N$ * $0 \le D < N$ * Only moves of types 1, 2, and 4 are performed. ## Sample Grader The sample grader reads the input in the following format: * line 1: $N \; M \; Q$ * line 2: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line 3 + $l$ ($0 \le l < M + Q$): * To perform a move of type 1: $1 \; K$ * To perform a move of type 2: $2 \; K$ * To perform a move of type 3: $3$ * To perform a move of type 4: $4$ * To ask the position of a dancer: $5 \; D$ The sample grader prints your answers in the following format: * line 1 + $q$ ($0 \le q < Q$): the values returned by `get_position`
Python
seed_226
# Choreography The Hungarian National Dance Ensemble is practicing a new choreography. There are $N$ dancers in the ensemble, numbered from $0$ to $N-1$, where $N$ is an **even** number. At the practice sessions, the choreographer first lines up the dancers. The positions in the line are numbered from $0$ to $N-1$, and position $i$ is occupied by dancer $P[i]$ at the start. After the dancers line up, the choreographer asks them to perform a sequence of **moves**. Each move must be completed before they begin performing the next one. The dancers are practicing 4 types of moves: 1. Every dancer moves $K$ positions to the right cyclically, where $0 \le K < N$. That is, * for each $i$ from $0$ to $N-K-1$, inclusive, the dancer currently standing at position $i$ moves to position $i+K$, and * for each $i$ from $N-K$ to $N-1$, inclusive, the dancer currently standing at position $i$ moves to position $i+K-N$. 2. Every dancer moves $K$ positions to the left cyclically, where $0 \le K < N$. That is, * for each $i$ from $K$ to $N-1$, inclusive, the dancer currently standing at position $i$ moves to position $i-K$, and * for each $i$ from $0$ to $K-1$, inclusive, the dancer currently standing at position $i$ moves to position $i-K+N$. 3. For each $i$ from $0$ to $ rac{N}{2}-1$, inclusive, dancers at positions $2i$ and $2i+1$ swap places. 4. Suppose that position $i$ ($0 \le i < N$) is occupied by dancer $r_i$ before performing this move. For each $j$ from $0$ to $N-1$, inclusive, dancer $j$ moves to position $r_j$. Note that the positions of the dancers are distinct at the end of each move. Before the next session, the choreographer plans a sequence of $M$ moves for the ensemble to practice. He adds the moves to the sequence one by one. Sometimes, before adding the next move, he wonders which positions certain dancers will occupy right after performing every move that has been added to the sequence. Your task is to simulate the dance moves planned by the choreographer and answer his questions about the positions of the dancers. ## Implementation Details You should implement the following procedures: ``` void init(int N, int[] P) ``` * $N$: the number of dancers. * $P$: array of length $N$ describing the initial order of the dancers. * This procedure is called exactly once, before any other function calls. ``` void move_right(int K) ``` * $K$: the number of positions each dancer moves to the right. * This procedure adds a move of type 1 to the sequence of moves. ``` void move_left(int K) ``` * $K$: the number of positions each dancer moves to the left. * This procedure adds a move of type 2 to the sequence of moves. ``` void swap_places() ``` * This procedure adds a move of type 3 to the sequence of moves. ``` void move_around() ``` * This procedure adds a move of type 4 to the sequence of moves. Procedures `move_right`, `move_left`, `swap_places`, and `move_around` are called for a total of $M$ times. ``` int get_position(int D) ``` * $D$: an integer representing a dancer. * This procedure should return the position of dancer $D$ after performing every move added to the sequence of moves before this call. * This procedure is called $Q$ times. ## Example Consider the following sequence of calls: ``` init(6, [5, 1, 4, 2, 0, 3]) ``` There are 6 dancers, and the initial order of the dancers is given by the array [5, 1, 4, 2, 0, 3], that is, position 0 is occupied by dancer 5, position 1 is occupied by dancer 1, position 2 is occupied by dancer 4, and so on. ``` move_left(2) ``` Each dancer moves two places to the left cyclically. After the move, the order of the dancers becomes [4, 2, 0, 3, 5, 1]. ``` get_position(0) ``` This call asks the position of dancer 0 after performing the first move. Dancer 0 is standing at position 2. Therefore, the procedure should return 2. ``` swap_places() ``` After this move, the order of the dancers becomes [2, 4, 3, 0, 1, 5]. ``` move_around() ``` The new position of each dancer is determined as follows. * Dancer 0: position 0 is occupied by dancer 2, so dancer 0 moves to position 2. * Dancer 1: position 1 is occupied by dancer 4, so dancer 1 stays at position 4. * Dancer 2: position 2 is occupied by dancer 3, so dancer 2 moves to position 3. * Dancer 3: position 3 is occupied by dancer 0, so dancer 3 moves to position 0. * Dancer 4: position 4 is occupied by dancer 1, so dancer 4 stays at position 1. * Dancer 5: position 5 is occupied by dancer 5, so dancer 5 stays at position 5. After this move, the order of the dancers becomes [3, 4, 0, 2, 1, 5]. ``` get_position(3) ``` Dancer 3 is at position 0 after performing every move so far. The procedure should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le N \le 100\,000$ * $0 \le P[i] < N$ (for each $i$ such that $0 \le i < N$) * $P[i] \ne P[j]$ (for each $i$ and $j$ such that $0 \le i < j < N$) * $0 \le M \le 100\,000$ * $1 \le Q \le 200\,000$ * $0 \le K < N$ * $0 \le D < N$ * Only moves of types 3 and 4 are performed. ## Sample Grader The sample grader reads the input in the following format: * line 1: $N \; M \; Q$ * line 2: $P[0] \; P[1] \; \ldots \; P[N-1]$ * line 3 + $l$ ($0 \le l < M + Q$): * To perform a move of type 1: $1 \; K$ * To perform a move of type 2: $2 \; K$ * To perform a move of type 3: $3$ * To perform a move of type 4: $4$ * To ask the position of a dancer: $5 \; D$ The sample grader prints your answers in the following format: * line 1 + $q$ ($0 \le q < Q$): the values returned by `get_position`
Python
seed_228
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 200\,000$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_229
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 100$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_230
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 20$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_232
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 3\,000$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_233
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 3\,000$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. * The road network is linear. Road $i$ connects cities $i$ and $i + 1$ (for each $i$ such that $0 \le i \le N - 2$). ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_234
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 50$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. * The road network is linear. Road $i$ connects cities $i$ and $i + 1$ (for each $i$ such that $0 \le i \le N - 2$). ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_235
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 500$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_236
# Closing Time Hungary is a country with $N$ cities, numbered from $0$ to $N - 1$. The cities are connected by $N - 1$ *bidirectional* roads, numbered from $0$ to $N - 2$. For each $j$ such that $0 \le j \le N - 2$, road $j$ connects city $U[j]$ and city $V[j]$ and has length $W[j]$, that is, it allows one to travel between the cities in $W[j]$ units of time. Each road connects two different cities, and each pair of cities is connected by at most one road. A **path** between two distinct cities $a$ and $b$ is a sequence $p_0, p_1, \ldots, p_t$ of distinct cities, such that: * $p_0 = a$, * $p_t = b$, * for each $i$ ($0 \le i \lt t$), there is a road connecting cities $p_i$ and $p_{i + 1}$. It is possible to travel from any city to any other city by using the roads, that is, there exists a path between every two distinct cities. It can be shown that this path is unique for each pair of distinct cities. The **length** of a path $p_0, p_1, \ldots, p_t$ is the sum of the lengths of the $t$ roads connecting consecutive cities along the path. In Hungary, many people travel to attend the Foundation Day festivities in two major cities. Once the celebrations are over, they return to their homes. The government wants to prevent the crowd from disturbing the locals, so they plan to lock down all cities at certain times. Each city will be assigned a non-negative **closing time** by the government. The government has decided that the sum of all closing times must not be more than $K$. More precisely, for every $i$ between $0$ and $N - 1$, inclusive, the closing time assigned to city $i$ is a nonnegative integer $c[i]$. The sum of all $c[i]$ must not be greater than $K$. Consider a city $a$ and some assignment of closing times. We say that a city $b$ is **reachable** from city $a$ if and only if either $b = a$, or the path $p_0, \ldots, p_t$ between these two cities (so in particular $p_0 = a$ and $p_t = b$) satisfies the following conditions: * the length of the path $p_0, p_1$ is at most $c[p_1]$, and * the length of the path $p_0, p_1, p_2$ is at most $c[p_2]$, and * $\ldots$ * the length of the path $p_0, p_1, p_2, \ldots, p_t$ is at most $c[p_t]$. This year, the two main festival sites are located in city $X$ and city $Y$. For each assignment of closing times, the **convenience score** is defined as the sum of the following two numbers: - The number of cities reachable from city $X$. - The number of cities reachable from city $Y$. Note that if a city is reachable from city $X$ and reachable from city $Y$, it counts *twice* towards the convenience score. Your task is to compute the maximum convenience score that can be achieved by some assignment of closing times. ## Implementation Details You should implement the following procedure. ``` int max_score(int N, int X, int Y, int64 K, int[] U, int[] V, int[] W) ``` * $N$: the number of cities. * $X$, $Y$: the cities with main festival sites. * $K$: the upper bound on the sum of closing times. * $U$, $V$: arrays of length $N - 1$ describing road connections. * $W$: array of length $N - 1$ describing road lengths. * This procedure should return the maximum convenience score that can be achieved by some assignment of closing times. * This procedure may be called **multiple times** in each test case. ## Example Consider the following call: ``` max_score(7, 0, 2, 10, [0, 0, 1, 2, 2, 5], [1, 3, 2, 4, 5, 6], [2, 3, 4, 2, 5, 3]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | $4$ | $5$ | $6$ | |:----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $4$ | $0$ | $3$ | $2$ | $0$ | $0$ | Note that the sum of all closing times is $9$, which is not more than $K = 10$. Cities $0$, $1$, and $3$ are reachable from city $X$ ($X = 0$), while cities $1$, $2$, and $4$ are reachable from city $Y$ ($Y = 2$). Therefore, the convenience score is $3 + 3 = 6$. There is no assignment of closing times with convenience score more than $6$, so the procedure should return $6$. Also consider the following call: ``` max_score(4, 0, 3, 20, [0, 1, 2], [1, 2, 3], [18, 1, 19]) ``` This corresponds to the following road network: Suppose the closing times are assigned as follows: | **City** | $0$ | $1$ | $2$ | $3$ | |:----------------:|:---:|:---:|:---:|:---:| | **Closing time** | $0$ | $1$ | $19$| $0$ | City $0$ is reachable from city $X$ ($X = 0$), while cities $2$ and $3$ are reachable from city $Y$ ($Y = 3$). Therefore, the convenience score is $1 + 2 = 3$. There is no assignment of closing times with convenience score more than $3$, so the procedure should return $3$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 200\,000$ * $0 \le X \lt Y \lt N$ * $0 \le K \le 10^{18}$ * $0 \le U[j] \lt V[j] \lt N$ (for each $j$ such that $0 \le j \le N - 2$) * $1 \le W[j] \le 10^6$ (for each $j$ such that $0 \le j \le N - 2$) * It is possible to travel from any city to any other city by using the roads. * $S_N \le 500$, where $S_N$ is the sum of $N$ over all calls to `max_score` in each test case. * The road network is linear. Road $i$ connects cities $i$ and $i + 1$ (for each $i$ such that $0 \le i \le N - 2$). ## Sample Grader Let $C$ denote the number of scenarios, that is, the number of calls to `max_score`. The sample grader reads the input in the following format: * line $1$: $C$ The descriptions of $C$ scenarios follow. The sample grader reads the description of each scenario in the following format: * line $1$: $N \; X \; Y \; K$ * line $2 + j$ ($0 \le j \le N - 2$): $U[j] \; V[j] \; W[j]$ The sample grader prints a single line for each scenario, in the following format: * line $1$: the return value of `max_score`
Python
seed_238
# Combo You are playing an action video game. The game controller has 4 buttons, A, B, X, and Y. In this game, you can get coins with combo moves. You can make a combo move by pressing buttons in sequence. This game has a secret sequence of buttons, which can be represented as a string `S` of those 4 characters. You don't know the string `S`, but you know its length `N`. **You also know that the first character of `S` never reappears in it.** For example, `S` can be \"ABXYY\" or \"XYYAA\", but cannot be \"AAAAA\" or \"BXYBX\". You can press a sequence of up to `4N` buttons for a combo move. Let `p` be the string which represents the sequence of the buttons you pressed. The number of coins you get for this move is calculated as the length of the longest prefix of `S` which is also a substring of `p`. A substring of a string `t` is a contiguous (possibly empty) sequence of characters within `t`. A prefix of `t` is a substring of `t` that is empty or contains the first character of `t`. For example, if `S` is \"ABXYY\" and `p` is \"XYYYABYABXAY\", you will get 3 coins because \"ABX\" is the longest prefix of `S` that is also a substring of `p`. Your task is to determine the secret string `S` using few combo moves. ## Implementation details You should implement the following function: ```plaintext string guess_sequence(int N) ``` - `N`: the length of string `S`. - This function is called exactly once for each test case. - This function should return the string `S`. Your program can call the following function: ```plaintext int press(string p) ``` - `p`: a sequence of buttons you press. - `p` must be a string of length between 0 and `4N`, inclusive. Each character of `p` must be A, B, X, or Y. - You cannot call this function more than 8,000 times for each test case. - This function returns the number of coins you get when you press the sequence of buttons represented by `p`. If some of the above conditions are not satisfied, your program is judged as **Wrong Answer**. Otherwise, your program is judged as **Accepted** and your score is calculated by the number of calls to `press`. ## Example Let `S` be \"ABXYY\". The grader calls `guess_sequence(5)`. An example of communication is shown below. | Call | Return | |------------------------------|--------| | `press("XYYYABYABXAY")` | 3 | | `press("ABXYY")` | 5 | | `press("ABXYYABXYY")` | 5 | | `press("")` | 0 | | `press("X")` | 0 | | `press("BXY")` | 0 | | `press("YYXBA")` | 1 | | `press("AY")` | 1 | For the first call to `press`, \"ABX\" appears in \"XYYYABYABXAY\" as a substring but \"ABXY\" does not, so 3 is returned. For the third call to `press`, \"ABXYY\" itself appears in \"ABXYYABXYY\" as a substring, so 5 is returned. For the sixth call to `press`, no prefix of \"ABXYY\" but the empty string appears in \"BXY\" as a substring, so 0 is returned. Finally, `guess_sequence(5)` should return \"ABXYY\". The file `sample-01-in.txt` in the zipped attachment package corresponds to this example. ## Constraints - `1 ≀ N ≀ 2000` - Each character of the string `S` is A, B, X, or Y. ## Sample grader The sample grader reads the input in the following format: - line 1: `S` If your program is judged as **Accepted**, the sample grader prints `Accepted: q` with `q` being the number of calls to the function `press`. If your program is judged as **Wrong Answer**, it prints `Wrong Answer: MSG`. The meaning of `MSG` is as follows: - `invalid press`: A value of `p` given to `press` is invalid. Namely, the length of `p` is not between 0 and `4N`, inclusive, or some character of `p` is not A, B, X, or Y. - `too many moves`: The function `press` is called more than 8,000 times. - `wrong guess`: The return value of `guess_sequence` is not `S`. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: - `1 ≀ N ≀ 2000` - Each character of the string `S` is A, B, X, or Y.
Python
seed_240
# Comparing Code ## TASK Racine Business Networks (RBN) has taken the Heuristic Algorithm Languages (HAL) company to court, claiming that HAL has taken source code from RBN UNIXβ„’ and contributed it to the open-source operating system HALnix. RBN and HAL both use a programming language with one statement per line, each of the form: ``` STOREA = STOREB + STOREC ``` where `STOREA`, `STOREB`, and `STOREC` are variable names. In particular, the first variable name starts in the first column and is followed by a space, an equals sign, a space, a second variable name, a space, the addition symbol, a space, and a third variable name. The same variable name might appear more than one time on a single line. Variable names consist of 1–8 uppercase ASCII letters (`A`–`Z`). RBN claims that HAL copied a consecutive sequence of lines directly from RBN's source code, making only minor modifications: - RBN claims that HAL changed some of the variable names in order to disguise their crime. That is, HAL took a series of lines from RBN's program and, for each variable in it, changed all occurrences of that variable to a new variable name, although the new variable name might be the same as the original. Of course, no two variables were changed to the same new variable name. - RBN also claims HAL might have changed the order of the right-hand side of some lines: ``` STOREA = STOREB + STOREC might have been changed to STOREA = STOREC + STOREB. ``` - RBN claims that HAL did not change the order of the lines of RBN's source code. Given source code for programs from RBN and HAL, find the longest consecutive sequence of lines from HAL's program that could have come from a consecutive sequence of lines from RBN's program using the modifications above. Note that the sequences of lines from the two programs do not have to start at the same line number in both files. ## Input: `code.in` - The first line of input contains two space-separated integers `R` and `H` (`1 ≀ R, H ≀ 1000`). `R` is the number of lines of source code in RBN's program; `H` is the number of lines of source code in HAL's program. - The next `R` lines contain RBN's program. - The next `H` lines contain HAL's program. ## Output: `code.out` The output file should contain a single line with a single integer that is the length of the longest consecutive sequence of lines that HAL might have copied from RBN and transformed. ## Example input: ``` 4 3 RA = RB + RC RC = RD + RE RF = RF + RJ RE = RF + RE HD = HE + HF HM = HN + D HN = HA + HB ``` ## Example output: ``` 2 ``` Lines 1–2 of RBN's program are the same as lines 2–3 of HAL's program, if the following variable name substitutions are performed on RBN's program: `RA β†’ HM`, `RB β†’ D`, `RC β†’ HN`, `D β†’ HA`, `RE β†’ HB`. There is no matching with three or more lines. ## CONSTRAINTS - **Running time:** 2 seconds of CPU - **Memory:** 64 MB ## SCORING You will receive full points on each test case for which your program produces a correct output file. No partial credit will be given on any test case. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_241
# Comparing Plants (plants) Hazel the botanist visited a special exhibition in the Singapore Botanical Gardens. In this exhibition, n plants of **distinct heights** are placed in a circle. These plants are labelled from 0 to n βˆ’ 1 in clockwise order, with plant n βˆ’ 1 beside plant 0. For each plant i (0 ≀ i < n βˆ’ 1), Hazel compared plant i to each of the next k βˆ’ 1 plants in clockwise order, and wrote down the number r[i] denoting how many of these k βˆ’ 1 plants are taller than plant i. Thus, each value r[i] depends on the relative heights of some k consecutive plants. For example, suppose n = 5, k = 3 and i = 3. The next k βˆ’ 1 = 2 plants in clockwise order from plant i = 3 would be plant 4 and plant 0. If plant 4 was taller than plant 3 and plant 0 was shorter than plant 3, Hazel would write down r[3] = 1. You may assume that Hazel recorded the values r[i] correctly. Thus, there is at least one configuration of distinct heights of plants consistent with these values. You were asked to compare the heights of pairs of plants. Sadly, you do not have access to the exhibition. Your only source of information is Hazel's notebook with the value k and the sequence of values r[0], . . . , r[n βˆ’ 1]. For each pair of different plants x and y that need to be compared, determine which of the three following situations occurs: * Plant x is definitely taller than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] > h[y]. * Plant x is definitely shorter than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] < h[y]. * The comparison is inconclusive: neither of the previous two cases applies. ## Implementation details You should implement the following procedures: ``` void init(int k, int[] r) ``` * k: the number of consecutive plants whose heights determine each individual value r[i]. * r: an array of size n, where r[i] is the number of plants taller than plant i among the next k βˆ’ 1 plants in clockwise order. * This procedure is called exactly once, before any calls to compare_plants. ``` int compare_plants(int x, int y) ``` * x, y: labels of the plants to be compared. * This procedure should return: * 1 if plant x is definitely taller than plant y, * -1 if plant x is definitely shorter than plant y, * 0 if the comparison is inconclusive. * This procedure is called exactly q times. ## Examples ### Example 1 Consider the following call: ``` init(3, [0, 1, 1, 2]) ``` Let's say the grader calls `compare_plants(0, 2)`. Since r[0] = 0 we can immediately infer that plant 2 is not taller than plant 0. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 2)` next. For all possible configurations of heights that fit the constraints above, plant 1 is shorter than plant 2. Therefore, the call should return -1. ### Example 2 Consider the following call: ``` init(2, [0, 1, 0, 1]) ``` Let's say the grader calls `compare_plants(0, 3)`. Since r[3] = 1, we know that plant 0 is taller than plant 3. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 3)` next. Two configurations of heights [3, 1, 4, 2] and [3, 2, 4, 1] are both consistent with Hazel's measurements. Since plant 1 is shorter than plant 3 in one configuration and taller than plant 3 in the other, this call should return 0. ## Constraints * $2 \le k \le n \le 200\,000$ * $1 \le q \le 200\,000$ * $0 \le r[i] \le k - 1$ (for all $0 \le i \le n - 1$) * $0 \le x < y \le n - 1$ * There exists one or more configurations of distinct heights of plants consistent with the array $r$. ## Sample grader The sample grader reads the input in the following format: * line 1: n k q * line 2: r[0] r[1] ... r[n-1] * line 3 + i (0 ≀ i ≀ q βˆ’ 1): x y for the i-th call to compare_plants The sample grader prints your answers in the following format: * line 1 + i (0 ≀ i ≀ q βˆ’ 1): return value of the i-th call to compare_plants.
Python
seed_242
# Comparing Plants (plants) Hazel the botanist visited a special exhibition in the Singapore Botanical Gardens. In this exhibition, n plants of **distinct heights** are placed in a circle. These plants are labelled from 0 to n βˆ’ 1 in clockwise order, with plant n βˆ’ 1 beside plant 0. For each plant i (0 ≀ i < n βˆ’ 1), Hazel compared plant i to each of the next k βˆ’ 1 plants in clockwise order, and wrote down the number r[i] denoting how many of these k βˆ’ 1 plants are taller than plant i. Thus, each value r[i] depends on the relative heights of some k consecutive plants. For example, suppose n = 5, k = 3 and i = 3. The next k βˆ’ 1 = 2 plants in clockwise order from plant i = 3 would be plant 4 and plant 0. If plant 4 was taller than plant 3 and plant 0 was shorter than plant 3, Hazel would write down r[3] = 1. You may assume that Hazel recorded the values r[i] correctly. Thus, there is at least one configuration of distinct heights of plants consistent with these values. You were asked to compare the heights of pairs of plants. Sadly, you do not have access to the exhibition. Your only source of information is Hazel's notebook with the value k and the sequence of values r[0], . . . , r[n βˆ’ 1]. For each pair of different plants x and y that need to be compared, determine which of the three following situations occurs: * Plant x is definitely taller than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] > h[y]. * Plant x is definitely shorter than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] < h[y]. * The comparison is inconclusive: neither of the previous two cases applies. ## Implementation details You should implement the following procedures: ``` void init(int k, int[] r) ``` * k: the number of consecutive plants whose heights determine each individual value r[i]. * r: an array of size n, where r[i] is the number of plants taller than plant i among the next k βˆ’ 1 plants in clockwise order. * This procedure is called exactly once, before any calls to compare_plants. ``` int compare_plants(int x, int y) ``` * x, y: labels of the plants to be compared. * This procedure should return: * 1 if plant x is definitely taller than plant y, * -1 if plant x is definitely shorter than plant y, * 0 if the comparison is inconclusive. * This procedure is called exactly q times. ## Examples ### Example 1 Consider the following call: ``` init(3, [0, 1, 1, 2]) ``` Let's say the grader calls `compare_plants(0, 2)`. Since r[0] = 0 we can immediately infer that plant 2 is not taller than plant 0. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 2)` next. For all possible configurations of heights that fit the constraints above, plant 1 is shorter than plant 2. Therefore, the call should return -1. ### Example 2 Consider the following call: ``` init(2, [0, 1, 0, 1]) ``` Let's say the grader calls `compare_plants(0, 3)`. Since r[3] = 1, we know that plant 0 is taller than plant 3. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 3)` next. Two configurations of heights [3, 1, 4, 2] and [3, 2, 4, 1] are both consistent with Hazel's measurements. Since plant 1 is shorter than plant 3 in one configuration and taller than plant 3 in the other, this call should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le k \le n \le 200\,000$ * $1 \le q \le 200\,000$ * $0 \le r[i] \le k - 1$ (for all $0 \le i \le n - 1$) * $0 \le x < y \le n - 1$ * There exists one or more configurations of distinct heights of plants consistent with the array $r$. * $2 \cdot k > n$ ## Sample grader The sample grader reads the input in the following format: * line 1: n k q * line 2: r[0] r[1] ... r[n-1] * line 3 + i (0 ≀ i ≀ q βˆ’ 1): x y for the i-th call to compare_plants The sample grader prints your answers in the following format: * line 1 + i (0 ≀ i ≀ q βˆ’ 1): return value of the i-th call to compare_plants.
Python
seed_243
# Comparing Plants (plants) Hazel the botanist visited a special exhibition in the Singapore Botanical Gardens. In this exhibition, n plants of **distinct heights** are placed in a circle. These plants are labelled from 0 to n βˆ’ 1 in clockwise order, with plant n βˆ’ 1 beside plant 0. For each plant i (0 ≀ i < n βˆ’ 1), Hazel compared plant i to each of the next k βˆ’ 1 plants in clockwise order, and wrote down the number r[i] denoting how many of these k βˆ’ 1 plants are taller than plant i. Thus, each value r[i] depends on the relative heights of some k consecutive plants. For example, suppose n = 5, k = 3 and i = 3. The next k βˆ’ 1 = 2 plants in clockwise order from plant i = 3 would be plant 4 and plant 0. If plant 4 was taller than plant 3 and plant 0 was shorter than plant 3, Hazel would write down r[3] = 1. You may assume that Hazel recorded the values r[i] correctly. Thus, there is at least one configuration of distinct heights of plants consistent with these values. You were asked to compare the heights of pairs of plants. Sadly, you do not have access to the exhibition. Your only source of information is Hazel's notebook with the value k and the sequence of values r[0], . . . , r[n βˆ’ 1]. For each pair of different plants x and y that need to be compared, determine which of the three following situations occurs: * Plant x is definitely taller than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] > h[y]. * Plant x is definitely shorter than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] < h[y]. * The comparison is inconclusive: neither of the previous two cases applies. ## Implementation details You should implement the following procedures: ``` void init(int k, int[] r) ``` * k: the number of consecutive plants whose heights determine each individual value r[i]. * r: an array of size n, where r[i] is the number of plants taller than plant i among the next k βˆ’ 1 plants in clockwise order. * This procedure is called exactly once, before any calls to compare_plants. ``` int compare_plants(int x, int y) ``` * x, y: labels of the plants to be compared. * This procedure should return: * 1 if plant x is definitely taller than plant y, * -1 if plant x is definitely shorter than plant y, * 0 if the comparison is inconclusive. * This procedure is called exactly q times. ## Examples ### Example 1 Consider the following call: ``` init(3, [0, 1, 1, 2]) ``` Let's say the grader calls `compare_plants(0, 2)`. Since r[0] = 0 we can immediately infer that plant 2 is not taller than plant 0. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 2)` next. For all possible configurations of heights that fit the constraints above, plant 1 is shorter than plant 2. Therefore, the call should return -1. ### Example 2 Consider the following call: ``` init(2, [0, 1, 0, 1]) ``` Let's say the grader calls `compare_plants(0, 3)`. Since r[3] = 1, we know that plant 0 is taller than plant 3. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 3)` next. Two configurations of heights [3, 1, 4, 2] and [3, 2, 4, 1] are both consistent with Hazel's measurements. Since plant 1 is shorter than plant 3 in one configuration and taller than plant 3 in the other, this call should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le k \le n \le 200\,000$ * $1 \le q \le 200\,000$ * $0 \le r[i] \le k - 1$ (for all $0 \le i \le n - 1$) * $0 \le x < y \le n - 1$ * There exists one or more configurations of distinct heights of plants consistent with the array $r$. * $k = 2$ ## Sample grader The sample grader reads the input in the following format: * line 1: n k q * line 2: r[0] r[1] ... r[n-1] * line 3 + i (0 ≀ i ≀ q βˆ’ 1): x y for the i-th call to compare_plants The sample grader prints your answers in the following format: * line 1 + i (0 ≀ i ≀ q βˆ’ 1): return value of the i-th call to compare_plants.
Python
seed_244
# Comparing Plants (plants) Hazel the botanist visited a special exhibition in the Singapore Botanical Gardens. In this exhibition, n plants of **distinct heights** are placed in a circle. These plants are labelled from 0 to n βˆ’ 1 in clockwise order, with plant n βˆ’ 1 beside plant 0. For each plant i (0 ≀ i < n βˆ’ 1), Hazel compared plant i to each of the next k βˆ’ 1 plants in clockwise order, and wrote down the number r[i] denoting how many of these k βˆ’ 1 plants are taller than plant i. Thus, each value r[i] depends on the relative heights of some k consecutive plants. For example, suppose n = 5, k = 3 and i = 3. The next k βˆ’ 1 = 2 plants in clockwise order from plant i = 3 would be plant 4 and plant 0. If plant 4 was taller than plant 3 and plant 0 was shorter than plant 3, Hazel would write down r[3] = 1. You may assume that Hazel recorded the values r[i] correctly. Thus, there is at least one configuration of distinct heights of plants consistent with these values. You were asked to compare the heights of pairs of plants. Sadly, you do not have access to the exhibition. Your only source of information is Hazel's notebook with the value k and the sequence of values r[0], . . . , r[n βˆ’ 1]. For each pair of different plants x and y that need to be compared, determine which of the three following situations occurs: * Plant x is definitely taller than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] > h[y]. * Plant x is definitely shorter than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] < h[y]. * The comparison is inconclusive: neither of the previous two cases applies. ## Implementation details You should implement the following procedures: ``` void init(int k, int[] r) ``` * k: the number of consecutive plants whose heights determine each individual value r[i]. * r: an array of size n, where r[i] is the number of plants taller than plant i among the next k βˆ’ 1 plants in clockwise order. * This procedure is called exactly once, before any calls to compare_plants. ``` int compare_plants(int x, int y) ``` * x, y: labels of the plants to be compared. * This procedure should return: * 1 if plant x is definitely taller than plant y, * -1 if plant x is definitely shorter than plant y, * 0 if the comparison is inconclusive. * This procedure is called exactly q times. ## Examples ### Example 1 Consider the following call: ``` init(3, [0, 1, 1, 2]) ``` Let's say the grader calls `compare_plants(0, 2)`. Since r[0] = 0 we can immediately infer that plant 2 is not taller than plant 0. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 2)` next. For all possible configurations of heights that fit the constraints above, plant 1 is shorter than plant 2. Therefore, the call should return -1. ### Example 2 Consider the following call: ``` init(2, [0, 1, 0, 1]) ``` Let's say the grader calls `compare_plants(0, 3)`. Since r[3] = 1, we know that plant 0 is taller than plant 3. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 3)` next. Two configurations of heights [3, 1, 4, 2] and [3, 2, 4, 1] are both consistent with Hazel's measurements. Since plant 1 is shorter than plant 3 in one configuration and taller than plant 3 in the other, this call should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le k \le n \le 200\,000$ * $1 \le q \le 200\,000$ * $0 \le r[i] \le k - 1$ (for all $0 \le i \le n - 1$) * $0 \le x < y \le n - 1$ * There exists one or more configurations of distinct heights of plants consistent with the array $r$. * $n \le 300$, $q \le n \cdot (n-1)/2$ ## Sample grader The sample grader reads the input in the following format: * line 1: n k q * line 2: r[0] r[1] ... r[n-1] * line 3 + i (0 ≀ i ≀ q βˆ’ 1): x y for the i-th call to compare_plants The sample grader prints your answers in the following format: * line 1 + i (0 ≀ i ≀ q βˆ’ 1): return value of the i-th call to compare_plants.
Python
seed_245
# Comparing Plants (plants) Hazel the botanist visited a special exhibition in the Singapore Botanical Gardens. In this exhibition, n plants of **distinct heights** are placed in a circle. These plants are labelled from 0 to n βˆ’ 1 in clockwise order, with plant n βˆ’ 1 beside plant 0. For each plant i (0 ≀ i < n βˆ’ 1), Hazel compared plant i to each of the next k βˆ’ 1 plants in clockwise order, and wrote down the number r[i] denoting how many of these k βˆ’ 1 plants are taller than plant i. Thus, each value r[i] depends on the relative heights of some k consecutive plants. For example, suppose n = 5, k = 3 and i = 3. The next k βˆ’ 1 = 2 plants in clockwise order from plant i = 3 would be plant 4 and plant 0. If plant 4 was taller than plant 3 and plant 0 was shorter than plant 3, Hazel would write down r[3] = 1. You may assume that Hazel recorded the values r[i] correctly. Thus, there is at least one configuration of distinct heights of plants consistent with these values. You were asked to compare the heights of pairs of plants. Sadly, you do not have access to the exhibition. Your only source of information is Hazel's notebook with the value k and the sequence of values r[0], . . . , r[n βˆ’ 1]. For each pair of different plants x and y that need to be compared, determine which of the three following situations occurs: * Plant x is definitely taller than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] > h[y]. * Plant x is definitely shorter than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] < h[y]. * The comparison is inconclusive: neither of the previous two cases applies. ## Implementation details You should implement the following procedures: ``` void init(int k, int[] r) ``` * k: the number of consecutive plants whose heights determine each individual value r[i]. * r: an array of size n, where r[i] is the number of plants taller than plant i among the next k βˆ’ 1 plants in clockwise order. * This procedure is called exactly once, before any calls to compare_plants. ``` int compare_plants(int x, int y) ``` * x, y: labels of the plants to be compared. * This procedure should return: * 1 if plant x is definitely taller than plant y, * -1 if plant x is definitely shorter than plant y, * 0 if the comparison is inconclusive. * This procedure is called exactly q times. ## Examples ### Example 1 Consider the following call: ``` init(3, [0, 1, 1, 2]) ``` Let's say the grader calls `compare_plants(0, 2)`. Since r[0] = 0 we can immediately infer that plant 2 is not taller than plant 0. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 2)` next. For all possible configurations of heights that fit the constraints above, plant 1 is shorter than plant 2. Therefore, the call should return -1. ### Example 2 Consider the following call: ``` init(2, [0, 1, 0, 1]) ``` Let's say the grader calls `compare_plants(0, 3)`. Since r[3] = 1, we know that plant 0 is taller than plant 3. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 3)` next. Two configurations of heights [3, 1, 4, 2] and [3, 2, 4, 1] are both consistent with Hazel's measurements. Since plant 1 is shorter than plant 3 in one configuration and taller than plant 3 in the other, this call should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le k \le n \le 200\,000$ * $1 \le q \le 200\,000$ * $0 \le r[i] \le k - 1$ (for all $0 \le i \le n - 1$) * $0 \le x < y \le n - 1$ * There exists one or more configurations of distinct heights of plants consistent with the array $r$. * $n \le 5000$, $2 \cdot k > n$ ## Sample grader The sample grader reads the input in the following format: * line 1: n k q * line 2: r[0] r[1] ... r[n-1] * line 3 + i (0 ≀ i ≀ q βˆ’ 1): x y for the i-th call to compare_plants The sample grader prints your answers in the following format: * line 1 + i (0 ≀ i ≀ q βˆ’ 1): return value of the i-th call to compare_plants.
Python
seed_246
# Comparing Plants (plants) Hazel the botanist visited a special exhibition in the Singapore Botanical Gardens. In this exhibition, n plants of **distinct heights** are placed in a circle. These plants are labelled from 0 to n βˆ’ 1 in clockwise order, with plant n βˆ’ 1 beside plant 0. For each plant i (0 ≀ i < n βˆ’ 1), Hazel compared plant i to each of the next k βˆ’ 1 plants in clockwise order, and wrote down the number r[i] denoting how many of these k βˆ’ 1 plants are taller than plant i. Thus, each value r[i] depends on the relative heights of some k consecutive plants. For example, suppose n = 5, k = 3 and i = 3. The next k βˆ’ 1 = 2 plants in clockwise order from plant i = 3 would be plant 4 and plant 0. If plant 4 was taller than plant 3 and plant 0 was shorter than plant 3, Hazel would write down r[3] = 1. You may assume that Hazel recorded the values r[i] correctly. Thus, there is at least one configuration of distinct heights of plants consistent with these values. You were asked to compare the heights of pairs of plants. Sadly, you do not have access to the exhibition. Your only source of information is Hazel's notebook with the value k and the sequence of values r[0], . . . , r[n βˆ’ 1]. For each pair of different plants x and y that need to be compared, determine which of the three following situations occurs: * Plant x is definitely taller than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] > h[y]. * Plant x is definitely shorter than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] < h[y]. * The comparison is inconclusive: neither of the previous two cases applies. ## Implementation details You should implement the following procedures: ``` void init(int k, int[] r) ``` * k: the number of consecutive plants whose heights determine each individual value r[i]. * r: an array of size n, where r[i] is the number of plants taller than plant i among the next k βˆ’ 1 plants in clockwise order. * This procedure is called exactly once, before any calls to compare_plants. ``` int compare_plants(int x, int y) ``` * x, y: labels of the plants to be compared. * This procedure should return: * 1 if plant x is definitely taller than plant y, * -1 if plant x is definitely shorter than plant y, * 0 if the comparison is inconclusive. * This procedure is called exactly q times. ## Examples ### Example 1 Consider the following call: ``` init(3, [0, 1, 1, 2]) ``` Let's say the grader calls `compare_plants(0, 2)`. Since r[0] = 0 we can immediately infer that plant 2 is not taller than plant 0. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 2)` next. For all possible configurations of heights that fit the constraints above, plant 1 is shorter than plant 2. Therefore, the call should return -1. ### Example 2 Consider the following call: ``` init(2, [0, 1, 0, 1]) ``` Let's say the grader calls `compare_plants(0, 3)`. Since r[3] = 1, we know that plant 0 is taller than plant 3. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 3)` next. Two configurations of heights [3, 1, 4, 2] and [3, 2, 4, 1] are both consistent with Hazel's measurements. Since plant 1 is shorter than plant 3 in one configuration and taller than plant 3 in the other, this call should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le k \le n \le 200\,000$ * $1 \le q \le 200\,000$ * $0 \le r[i] \le k - 1$ (for all $0 \le i \le n - 1$) * $0 \le x < y \le n - 1$ * There exists one or more configurations of distinct heights of plants consistent with the array $r$. * $x = 0$ for each call of compare_plants. ## Sample grader The sample grader reads the input in the following format: * line 1: n k q * line 2: r[0] r[1] ... r[n-1] * line 3 + i (0 ≀ i ≀ q βˆ’ 1): x y for the i-th call to compare_plants The sample grader prints your answers in the following format: * line 1 + i (0 ≀ i ≀ q βˆ’ 1): return value of the i-th call to compare_plants.
Python
seed_247
# Comparing Plants (plants) Hazel the botanist visited a special exhibition in the Singapore Botanical Gardens. In this exhibition, n plants of **distinct heights** are placed in a circle. These plants are labelled from 0 to n βˆ’ 1 in clockwise order, with plant n βˆ’ 1 beside plant 0. For each plant i (0 ≀ i < n βˆ’ 1), Hazel compared plant i to each of the next k βˆ’ 1 plants in clockwise order, and wrote down the number r[i] denoting how many of these k βˆ’ 1 plants are taller than plant i. Thus, each value r[i] depends on the relative heights of some k consecutive plants. For example, suppose n = 5, k = 3 and i = 3. The next k βˆ’ 1 = 2 plants in clockwise order from plant i = 3 would be plant 4 and plant 0. If plant 4 was taller than plant 3 and plant 0 was shorter than plant 3, Hazel would write down r[3] = 1. You may assume that Hazel recorded the values r[i] correctly. Thus, there is at least one configuration of distinct heights of plants consistent with these values. You were asked to compare the heights of pairs of plants. Sadly, you do not have access to the exhibition. Your only source of information is Hazel's notebook with the value k and the sequence of values r[0], . . . , r[n βˆ’ 1]. For each pair of different plants x and y that need to be compared, determine which of the three following situations occurs: * Plant x is definitely taller than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] > h[y]. * Plant x is definitely shorter than plant y: in any configuration of distinct heights h[0], . . . , h[n βˆ’ 1] consistent with the array r we have h[x] < h[y]. * The comparison is inconclusive: neither of the previous two cases applies. ## Implementation details You should implement the following procedures: ``` void init(int k, int[] r) ``` * k: the number of consecutive plants whose heights determine each individual value r[i]. * r: an array of size n, where r[i] is the number of plants taller than plant i among the next k βˆ’ 1 plants in clockwise order. * This procedure is called exactly once, before any calls to compare_plants. ``` int compare_plants(int x, int y) ``` * x, y: labels of the plants to be compared. * This procedure should return: * 1 if plant x is definitely taller than plant y, * -1 if plant x is definitely shorter than plant y, * 0 if the comparison is inconclusive. * This procedure is called exactly q times. ## Examples ### Example 1 Consider the following call: ``` init(3, [0, 1, 1, 2]) ``` Let's say the grader calls `compare_plants(0, 2)`. Since r[0] = 0 we can immediately infer that plant 2 is not taller than plant 0. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 2)` next. For all possible configurations of heights that fit the constraints above, plant 1 is shorter than plant 2. Therefore, the call should return -1. ### Example 2 Consider the following call: ``` init(2, [0, 1, 0, 1]) ``` Let's say the grader calls `compare_plants(0, 3)`. Since r[3] = 1, we know that plant 0 is taller than plant 3. Therefore, the call should return 1. Let's say the grader calls `compare_plants(1, 3)` next. Two configurations of heights [3, 1, 4, 2] and [3, 2, 4, 1] are both consistent with Hazel's measurements. Since plant 1 is shorter than plant 3 in one configuration and taller than plant 3 in the other, this call should return 0. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le k \le n \le 200\,000$ * $1 \le q \le 200\,000$ * $0 \le r[i] \le k - 1$ (for all $0 \le i \le n - 1$) * $0 \le x < y \le n - 1$ * There exists one or more configurations of distinct heights of plants consistent with the array $r$. * The correct answer to each call of compare_plants is 1 or $-1$. ## Sample grader The sample grader reads the input in the following format: * line 1: n k q * line 2: r[0] r[1] ... r[n-1] * line 3 + i (0 ≀ i ≀ q βˆ’ 1): x y for the i-th call to compare_plants The sample grader prints your answers in the following format: * line 1 + i (0 ≀ i ≀ q βˆ’ 1): return value of the i-th call to compare_plants.
Python
seed_249
# Competition Day One **August 18, 2003** **Reverse (output-only task)** ## Task Consider a Two-Operation Machine (TOM for short) with nine registers, numbered 1...9. Each register stores a non-negative integer in the range `0 ... 1000`. The machine has two operations: ``` S i j - Store one plus the value of register i into register j. Note that i may equal j. P i - Print the value of register i. ``` A TOM program includes a set of initial values for the registers and a sequence of operations. Given an integer `N` (`0 <= N <= 255`), generate a TOM program that prints the decreasing sequence of integers `N, N-1, N-2, ..., 0`. The maximum number of consecutive `S`-operations should be as small as possible. ### Example of a TOM program and its execution for `N = 2`: | **Operation** | **New Register Values** | **Printed Value** | |---------------|--------------------------|-------------------| | | 1 2 3 4 5 6 7 8 9 | | | **Initial values** | 0 2 0 0 0 0 0 0 0 | | | `P 2` | 0 2 0 0 0 0 0 0 0 | 2 | | `S 1 3` | 0 2 1 0 0 0 0 0 0 | | | `P 3` | 0 2 1 0 0 0 0 0 0 | 1 | | `P 1` | 0 2 1 0 0 0 0 0 0 | 0 | Input cases are numbered `1` through `16` and are available via the contest server. ## Input - The first line of the input file contains `K`, an integer specifying the input case number. - The second line of input contains `N`. ### Example input: ``` 1 2 ``` ## Output - The first line of output should be the string `FILE reverse K`, where `K` is the case number. - The second line of output should contain nine space-separated values representing the desired initial values of the registers, in order (register `1`, then register `2`, etc.). The rest of the output file should contain the ordered list of operations to be performed, one per line. Thus, the third line contains the first operation to perform, and so on. The last line of the file should be the one that prints `0`. Each line should be a valid operation. The instructions should be formatted as in the example output. ### Example output #1 (partial points): ``` FILE reverse 1 0 2 0 0 0 0 0 0 0 P 2 P 3 P 1 ``` ### Example output #2 (full points): ``` FILE reverse 1 0 2 1 0 0 0 0 0 0 P 2 P 3 P 1 ``` ## Scoring Scoring of each test case will be based on correctness and optimality of the TOM program given. ### Correctness: 20% A TOM program is correct if it performs no more than `131` consecutive `S`-operations and the sequence of values printed by it is correct (contains exactly `N+1` integers, starting at `N` and ending at `0`). If any `S`-operation causes a register to overflow, the TOM program is considered incorrect. ### Optimality: 80% Optimality of a correct TOM program is measured by the maximum number of consecutive `S`-operations in the program, which should be as small as possible. Scoring will be based on the difference between your TOM program and the best known TOM program. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_250
# Competition Day One **August 18, 2003** **Task Description** **Trail Maintenance** **(interactive task)** ## TASK Farmer John's cows wish to travel freely among the $N \ (1 \leq N \leq 200)$ fields (numbered $1 \dots N$) on the farm, even though the fields are separated by forest. The cows wish to maintain trails between pairs of fields so that they can travel from any field to any other field using the maintained trails. Cows may travel along a maintained trail in either direction. The cows do not build trails. Instead, they maintain wild animal trails that they have discovered. On any week, they can choose to maintain any or all of the wild animal trails they know about. Always curious, the cows discover one new wild animal trail at the beginning of each week. They must then decide the set of trails to maintain for that week so that they can travel from any field to any other field. Cows can only use trails which they are currently maintaining. The cows always want to minimize the total length of trail they must maintain. The cows can choose to maintain any subset of the wild animal trails they know about, regardless of which trails were maintained the previous week. Wild animal trails (even when maintained) are never straight. Two trails that connect the same two fields might have different lengths. While two trails might cross, cows are so focused, they refuse to switch trails except when they are in a field. At the beginning of each week, the cows will describe the wild animal trail they discovered. Your program must then output the minimum total length of trail the cows must maintain that week so that they can travel from any field to any other field. If no set of trails allows the cows to travel from any field to any other field, output `-1`. ### Input: standard input - The first line of input contains two space-separated integers, $N$ and $W$. $W$ is the number of weeks the program will cover $(1 \leq W \leq 6000)$. - For each week, read a single line containing the wild animal trail that was discovered. This line contains three space-separated integers: the endpoints (field numbers) and the integer length of that trail $(1 \dots 10000)$. No wild animal trail has the same field as both of its endpoints. ### Output: standard output Immediately after your program learns about the newly discovered wild animal trail, it should output a single line with the minimum total length of trail the cows must maintain so that they can travel from any field to any other field. If no set of trails allows the cows to travel from any field to any other field, output `-1`. Your program must exit after outputting the answer for the last week. ### Example exchange: | **Input** | **Output** | **Explanation** | |-----------|------------|-----------------| | 4 6 | | | | 1 2 10 | | | | 1 3 8 | -1 | No trail connects 4 to the rest of the fields. | | 3 2 3 | -1 | No trail connects 4 to the rest of the fields. | | 1 4 3 | -1 | No trail connects 4 to the rest of the fields. | | 1 3 6 | 14 | Maintain 1 4 3, 1 3 8, and 3 2 3. | | 2 1 2 | 12 | Maintain 1 4 3, 1 3 6, and 3 2 3. | | | 8 | Maintain 1 4 3, 2 1 2, and 3 2 3. | ### CONSTRAINTS - **Running time:** 1 second of CPU - **Memory:** 64 MB ### SCORING You will receive full points on each test case for which your program produces the correct output. No partial credit will be given on any test case. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_251
# Competition Day Two ## August 20, 2003 ### Task Description ### Seeing the Boundary ## TASK Farmer Don watches the fence that surrounds his $N$ meter by $N$ meter square, flat field ($2 \leq N \leq 500,000$). One fence corner is at the origin $(0, 0)$ and the opposite corner is at $(N, N)$; the sides of Farmer Don's fence are parallel to the $X$ and $Y$ axes. Fence posts appear at all four corners and also at every meter along each side of the fence, for a total of $4N$ fence posts. The fence posts are vertical and are considered to have no radius. Farmer Don wants to determine how many of his fence posts he can watch when he stands at a given location within his fence. Farmer Don’s field contains $R$ ($1 \leq R \leq 30,000$) huge rocks that obscure his view of some fence posts, as he is not tall enough to look over any of these rocks. The base of each rock is a convex polygon with nonzero area whose vertices are at integer coordinates. The rocks stand completely vertical. Rocks do not overlap, do not touch other rocks, and do not touch Farmer Don or the fence. Farmer Don does not touch the fence, does not stand within a rock, and does not stand on a rock. Given the size of Farmer Don's fence, the locations and shapes of the rocks within it, and the location where Farmer Don stands, compute the number of fence posts that Farmer Don can see. If a vertex of a rock lines up perfectly with a fence post from Farmer Don's location, he is not able to see that fence post. ### Input: `boundary.in` - The first line of input contains two space-separated integers: $N$ and $R$. - The next line of input contains two space-separated integers that specify the $X$ and $Y$ coordinates of Farmer Don's location inside the fence. - The rest of the input file describes the $R$ rocks: - Rock $i$’s description starts with a line containing a single integer $p_i$ ($3 \leq p_i \leq 20$), the number of vertices in the rock's base. - Each of the next $p_i$ lines contains a space-separated pair of integers that are the $X$ and $Y$ coordinates of a vertex. The vertices of a rock’s base are distinct and given in counterclockwise order. ### Output: `boundary.out` The output file should contain a single line with a single integer, the number of fence posts visible to Farmer Don. ### Example input: ``` 100 1 60 50 5 70 40 75 40 80 40 80 50 70 60 ``` Note that the base of rock 1 has three collinear vertices: $(70,40)$, $(75,40)$, and $(80,40)$. ### Example output: ``` 319 ``` ## CONSTRAINTS - **Running time:** 1 second of CPU - **Memory:** 64 MB ## SCORING You will receive full points on each test case for which your program produces a correct output file. No partial credit will be given on any test case. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints:
Python
seed_253
# Connected Towns Pak Dengklek lives in Indonesia, a country consisting of $N$ towns numbered from $0$ to $N - 1$. For every pair of towns, there is a one-way road going from one town to the other. Pak Dengklek has no information on the direction of the roads, but Pak Chanek has offered to help him. Pak Dengklek is allowed to ask Pak Chanek at most $40\;000$ questions. For each question in turn, Pak Dengklek chooses a pair of towns and Pak Chanek tells him the direction of the road connecting those two towns. Pak Dengklek wants to know a town number with at most one outgoing road, or report if there is no such town. If there is more than one such town, Pak Dengklek only needs to know any of such town numbers. ## Implementation Details You should implement the following procedure: ``` int find_town(int N) ``` * $N$: the number of towns in Indonesia. * This procedure should return any town number with at most one outgoing road, or $-1$ if there is no such town. * This procedure is called exactly once. The above procedure can make calls to the following procedure: ``` bool check_road(int A, int B) ``` * $A, B$: a pair of town numbers to be asked to Pak Chanek. * $A$ and $B$ must be **distinct** integers from $0$ to $N - 1$ inclusive. * The procedure returns `true` if there is a road going from town $A$ to town $B$ and returns `false` if there is a road going from town $B$ to town $A$. * This procedure can be called at most $40\;000$ times. ## Example ### Example 1 Consider a scenario in which there are $3$ towns and the roads connecting the towns are illustrated by the following image: The procedure `find_town` is called in the following way: ``` find_town(3) ``` This procedure may call `check_road(0, 1)`, which (in this scenario) returns `true`. At this point, there is sufficient information to conclude that town $1$ has at most one outgoing road. Therefore, the procedure may return $1$. Additionally, this procedure may call `check_road(2, 1)`, which (in this scenario) returns `false`. At this point, there is sufficient information to conclude that town $2$ has at most one outgoing road. Therefore, the procedure may also return $2$. ### Example 2 Consider a scenario in which there are $5$ towns and the roads connecting the towns are illustrated by the following image: The procedure `find_town` is called in the following way: ``` find_town(5) ``` In this scenario, there is no town with at most one outgoing road. Therefore, the procedure should return $-1$. ## Constraints * $3 \le N \le 2000$ In this subtask you can obtain a partial score. Let $Q$ be the maximum number of calls to the procedure `check_road` across all test cases in this subtask. Your score for this subtask is calculated according to the following table: | Condition | Points | | --------------------------- | --------------------------------------- | | $20\,000 \lt Q \le 40\,000$ | $20$ | | $8000 \lt Q \le 20\,000$ | $90 - 70 \sqrt{\frac{Q - 8000}{12000}}$ | | $Q \le 8000$ | $90$ | ## Grading In some test cases, the behaviour of the grader is adaptive. This means that in these test cases the grader does not have a fixed configuration of road directions. Instead, the answers given by the grader may depend on the questions asked by your solution. It is guaranteed that the grader answers in such a way that after each answer there is at least one configuration of road directions consistent with all the answers given so far. ## Sample Grader The sample grader reads an array $R$ of $N$ strings with $N$ characters representing the roads in Indonesia. For each $i$ and $j$ such that $0 \le i, j \le N - 1$ ($i \ne j$), $R[i][j]$ is `1` if there is a road going from town $i$ to town $j$ and $R[i][j]$ is `0` if there is a road going from town $j$ to town $i$. For each $i$ such that $0 \le i \le N - 1$, $R[i][i]$ should be `0`. The sample grader reads input in the following format: * line $1$: $N$ * line $2 + i$ ($0 \le i \le N - 1$): $R[i]$ If the sample grader detects a protocol violation, the output of the sample grader is `Protocol Violation: <MSG>`, where `<MSG>` is one of the following: * `too many questions`: `check_road` is called more than $40\;000$ times. * `invalid parameters`: `check_road` is called with $A$ and $B$ are not distinct integers from $0$ to $N - 1$ inclusive. Otherwise, the output of the sample grader is in the following format: * line $1$: the return value of `find_town`. * line $2$: the number of calls to `check_road`. Note that the sample grader is not adaptive.
Python
seed_254
# Connected Towns Pak Dengklek lives in Indonesia, a country consisting of $N$ towns numbered from $0$ to $N - 1$. For every pair of towns, there is a one-way road going from one town to the other. Pak Dengklek has no information on the direction of the roads, but Pak Chanek has offered to help him. Pak Dengklek is allowed to ask Pak Chanek at most $40\;000$ questions. For each question in turn, Pak Dengklek chooses a pair of towns and Pak Chanek tells him the direction of the road connecting those two towns. Pak Dengklek wants to know a town number with at most one outgoing road, or report if there is no such town. If there is more than one such town, Pak Dengklek only needs to know any of such town numbers. ## Implementation Details You should implement the following procedure: ``` int find_town(int N) ``` * $N$: the number of towns in Indonesia. * This procedure should return any town number with at most one outgoing road, or $-1$ if there is no such town. * This procedure is called exactly once. The above procedure can make calls to the following procedure: ``` bool check_road(int A, int B) ``` * $A, B$: a pair of town numbers to be asked to Pak Chanek. * $A$ and $B$ must be **distinct** integers from $0$ to $N - 1$ inclusive. * The procedure returns `true` if there is a road going from town $A$ to town $B$ and returns `false` if there is a road going from town $B$ to town $A$. * This procedure can be called at most $40\;000$ times. ## Example ### Example 1 Consider a scenario in which there are $3$ towns and the roads connecting the towns are illustrated by the following image: The procedure `find_town` is called in the following way: ``` find_town(3) ``` This procedure may call `check_road(0, 1)`, which (in this scenario) returns `true`. At this point, there is sufficient information to conclude that town $1$ has at most one outgoing road. Therefore, the procedure may return $1$. Additionally, this procedure may call `check_road(2, 1)`, which (in this scenario) returns `false`. At this point, there is sufficient information to conclude that town $2$ has at most one outgoing road. Therefore, the procedure may also return $2$. ### Example 2 Consider a scenario in which there are $5$ towns and the roads connecting the towns are illustrated by the following image: The procedure `find_town` is called in the following way: ``` find_town(5) ``` In this scenario, there is no town with at most one outgoing road. Therefore, the procedure should return $-1$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $N \le 250$ ## Grading In some test cases, the behaviour of the grader is adaptive. This means that in these test cases the grader does not have a fixed configuration of road directions. Instead, the answers given by the grader may depend on the questions asked by your solution. It is guaranteed that the grader answers in such a way that after each answer there is at least one configuration of road directions consistent with all the answers given so far. ## Sample Grader The sample grader reads an array $R$ of $N$ strings with $N$ characters representing the roads in Indonesia. For each $i$ and $j$ such that $0 \le i, j \le N - 1$ ($i \ne j$), $R[i][j]$ is `1` if there is a road going from town $i$ to town $j$ and $R[i][j]$ is `0` if there is a road going from town $j$ to town $i$. For each $i$ such that $0 \le i \le N - 1$, $R[i][i]$ should be `0`. The sample grader reads input in the following format: * line $1$: $N$ * line $2 + i$ ($0 \le i \le N - 1$): $R[i]$ If the sample grader detects a protocol violation, the output of the sample grader is `Protocol Violation: <MSG>`, where `<MSG>` is one of the following: * `too many questions`: `check_road` is called more than $40\;000$ times. * `invalid parameters`: `check_road` is called with $A$ and $B$ are not distinct integers from $0$ to $N - 1$ inclusive. Otherwise, the output of the sample grader is in the following format: * line $1$: the return value of `find_town`. * line $2$: the number of calls to `check_road`. Note that the sample grader is not adaptive.
Python
seed_256
# Connecting Supertrees (supertrees) Gardens by the Bay is a large nature park in Singapore. In the park there are n towers, known as supertrees. These towers are labelled 0 to n βˆ’ 1. We would like to construct a set of zero or more bridges. Each bridge connects a pair of distinct towers and may be traversed in either direction. No two bridges should connect the same pair of towers. A path from tower x to tower y is a sequence of one or more towers such that: * the first element of the sequence is x, * the last element of the sequence is y, * all elements of the sequence are distinct, and * each two consecutive elements (towers) in the sequence are connected by a bridge. Note that by definition there is exactly one path from a tower to itself and the number of different paths from tower i to tower j is the same as the number of different paths from tower j to tower i. The lead architect in charge of the design wishes for the bridges to be built such that for all 0 ≀ i, j ≀ n βˆ’ 1 there are exactly p[i][j] different paths from tower i to tower j, where 0 ≀ p[i][j] ≀ 3. Construct a set of bridges that satisfy the architect's requirements, or determine that it is impossible. ## Implementation details You should implement the following procedure: ``` int construct(int[][] p) ``` * p: an n Γ— n array representing the architect's requirements. * If a construction is possible, this procedure should make exactly one call to build (see below) to report the construction, following which it should return 1. * Otherwise, the procedure should return 0 without making any calls to build. * This procedure is called exactly once. The procedure build is defined as follows: ``` void build(int[][] b) ``` * b: an n Γ— n array, with b[i][j] = 1 if there is a bridge connecting tower i and tower j, or b[i][j] = 0 otherwise. * Note that the array must satisfy b[i][j] = b[j][i] for all 0 ≀ i, j ≀ n βˆ’ 1 and b[i][i] = 0 for all 0 ≀ i ≀ n βˆ’ 1. ## Examples ### Example 1 Consider the following call: ``` construct([[1, 1, 2, 2], [1, 1, 2, 2], [2, 2, 1, 2], [2, 2, 2, 1]]) ``` This means that there should be exactly one path from tower 0 to tower 1. For all other pairs of towers (i, y), such that 0 ≀ i < y ≀ 3, there should be exactly two paths from tower i to tower y. This can be achieved with 4 bridges, connecting pairs of towers (0, 1), (1, 2), (1, 3) and (2, 3). To report this solution, the construct procedure should make the following call: ``` build([[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]) ``` It should then return 1. In this case, there are multiple constructions that fit the requirements, all of which would be considered correct. ### Example 2 Consider the following call: ``` construct([[1, 0], [0, 1]]) ``` This means that there should be no way to travel between the two towers. This can only be satisfied by having no bridges. Therefore, the construct procedure should make the following call: ``` build([[0, 0], [0, 0]]) ``` After which, the construct procedure should return 1. ### Example 3 Consider the following call: ``` construct([[1, 3], [3, 1]]) ``` This means that there should be exactly 3 paths from tower 0 to tower 1. This set of requirements cannot be satisfied. As such, the construct procedure should return 0 without making any call to build. ## Constraints * $1 \le n \le 1000$ * $p[i][i] = 1$ (for all $0 \le i \le n - 1$) * $p[i][j] = p[j][i]$ (for all $0 \le i, j \le n - 1$) * $0 \le p[i][j] \le 3$ (for all $0 \le i, j \le n - 1$) ## Sample grader The sample grader reads the input in the following format: * line 1: n * line 2 + i (0 ≀ i ≀ n βˆ’ 1): p[i][0] p[i][1] ... p[i][n-1] The output of the sample grader is in the following format: * line 1: the return value of construct. * If the return value of construct is 1, the sample grader additionally prints: * line 2 + i (0 ≀ i ≀ n βˆ’ 1): b[i][0] b[i][1] ... b[i][n-1]
Python
seed_257
# Connecting Supertrees (supertrees) Gardens by the Bay is a large nature park in Singapore. In the park there are n towers, known as supertrees. These towers are labelled 0 to n βˆ’ 1. We would like to construct a set of zero or more bridges. Each bridge connects a pair of distinct towers and may be traversed in either direction. No two bridges should connect the same pair of towers. A path from tower x to tower y is a sequence of one or more towers such that: * the first element of the sequence is x, * the last element of the sequence is y, * all elements of the sequence are distinct, and * each two consecutive elements (towers) in the sequence are connected by a bridge. Note that by definition there is exactly one path from a tower to itself and the number of different paths from tower i to tower j is the same as the number of different paths from tower j to tower i. The lead architect in charge of the design wishes for the bridges to be built such that for all 0 ≀ i, j ≀ n βˆ’ 1 there are exactly p[i][j] different paths from tower i to tower j, where 0 ≀ p[i][j] ≀ 3. Construct a set of bridges that satisfy the architect's requirements, or determine that it is impossible. ## Implementation details You should implement the following procedure: ``` int construct(int[][] p) ``` * p: an n Γ— n array representing the architect's requirements. * If a construction is possible, this procedure should make exactly one call to build (see below) to report the construction, following which it should return 1. * Otherwise, the procedure should return 0 without making any calls to build. * This procedure is called exactly once. The procedure build is defined as follows: ``` void build(int[][] b) ``` * b: an n Γ— n array, with b[i][j] = 1 if there is a bridge connecting tower i and tower j, or b[i][j] = 0 otherwise. * Note that the array must satisfy b[i][j] = b[j][i] for all 0 ≀ i, j ≀ n βˆ’ 1 and b[i][i] = 0 for all 0 ≀ i ≀ n βˆ’ 1. ## Examples ### Example 1 Consider the following call: ``` construct([[1, 1, 2, 2], [1, 1, 2, 2], [2, 2, 1, 2], [2, 2, 2, 1]]) ``` This means that there should be exactly one path from tower 0 to tower 1. For all other pairs of towers (i, y), such that 0 ≀ i < y ≀ 3, there should be exactly two paths from tower i to tower y. This can be achieved with 4 bridges, connecting pairs of towers (0, 1), (1, 2), (1, 3) and (2, 3). To report this solution, the construct procedure should make the following call: ``` build([[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]) ``` It should then return 1. In this case, there are multiple constructions that fit the requirements, all of which would be considered correct. ### Example 2 Consider the following call: ``` construct([[1, 0], [0, 1]]) ``` This means that there should be no way to travel between the two towers. This can only be satisfied by having no bridges. Therefore, the construct procedure should make the following call: ``` build([[0, 0], [0, 0]]) ``` After which, the construct procedure should return 1. ### Example 3 Consider the following call: ``` construct([[1, 3], [3, 1]]) ``` This means that there should be exactly 3 paths from tower 0 to tower 1. This set of requirements cannot be satisfied. As such, the construct procedure should return 0 without making any call to build. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le n \le 1000$ * $p[i][i] = 1$ (for all $0 \le i \le n - 1$) * $p[i][j] = p[j][i]$ (for all $0 \le i, j \le n - 1$) * $0 \le p[i][j] \le 3$ (for all $0 \le i, j \le n - 1$) * $0 \le p[i][j] \le 2$ (for all $0 \le i, j \le n - 1$) ## Sample grader The sample grader reads the input in the following format: * line 1: n * line 2 + i (0 ≀ i ≀ n βˆ’ 1): p[i][0] p[i][1] ... p[i][n-1] The output of the sample grader is in the following format: * line 1: the return value of construct. * If the return value of construct is 1, the sample grader additionally prints: * line 2 + i (0 ≀ i ≀ n βˆ’ 1): b[i][0] b[i][1] ... b[i][n-1]
Python
seed_258
# Connecting Supertrees (supertrees) Gardens by the Bay is a large nature park in Singapore. In the park there are n towers, known as supertrees. These towers are labelled 0 to n βˆ’ 1. We would like to construct a set of zero or more bridges. Each bridge connects a pair of distinct towers and may be traversed in either direction. No two bridges should connect the same pair of towers. A path from tower x to tower y is a sequence of one or more towers such that: * the first element of the sequence is x, * the last element of the sequence is y, * all elements of the sequence are distinct, and * each two consecutive elements (towers) in the sequence are connected by a bridge. Note that by definition there is exactly one path from a tower to itself and the number of different paths from tower i to tower j is the same as the number of different paths from tower j to tower i. The lead architect in charge of the design wishes for the bridges to be built such that for all 0 ≀ i, j ≀ n βˆ’ 1 there are exactly p[i][j] different paths from tower i to tower j, where 0 ≀ p[i][j] ≀ 3. Construct a set of bridges that satisfy the architect's requirements, or determine that it is impossible. ## Implementation details You should implement the following procedure: ``` int construct(int[][] p) ``` * p: an n Γ— n array representing the architect's requirements. * If a construction is possible, this procedure should make exactly one call to build (see below) to report the construction, following which it should return 1. * Otherwise, the procedure should return 0 without making any calls to build. * This procedure is called exactly once. The procedure build is defined as follows: ``` void build(int[][] b) ``` * b: an n Γ— n array, with b[i][j] = 1 if there is a bridge connecting tower i and tower j, or b[i][j] = 0 otherwise. * Note that the array must satisfy b[i][j] = b[j][i] for all 0 ≀ i, j ≀ n βˆ’ 1 and b[i][i] = 0 for all 0 ≀ i ≀ n βˆ’ 1. ## Examples ### Example 1 Consider the following call: ``` construct([[1, 1, 2, 2], [1, 1, 2, 2], [2, 2, 1, 2], [2, 2, 2, 1]]) ``` This means that there should be exactly one path from tower 0 to tower 1. For all other pairs of towers (i, y), such that 0 ≀ i < y ≀ 3, there should be exactly two paths from tower i to tower y. This can be achieved with 4 bridges, connecting pairs of towers (0, 1), (1, 2), (1, 3) and (2, 3). To report this solution, the construct procedure should make the following call: ``` build([[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]) ``` It should then return 1. In this case, there are multiple constructions that fit the requirements, all of which would be considered correct. ### Example 2 Consider the following call: ``` construct([[1, 0], [0, 1]]) ``` This means that there should be no way to travel between the two towers. This can only be satisfied by having no bridges. Therefore, the construct procedure should make the following call: ``` build([[0, 0], [0, 0]]) ``` After which, the construct procedure should return 1. ### Example 3 Consider the following call: ``` construct([[1, 3], [3, 1]]) ``` This means that there should be exactly 3 paths from tower 0 to tower 1. This set of requirements cannot be satisfied. As such, the construct procedure should return 0 without making any call to build. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le n \le 1000$ * $p[i][i] = 1$ (for all $0 \le i \le n - 1$) * $p[i][j] = p[j][i]$ (for all $0 \le i, j \le n - 1$) * $0 \le p[i][j] \le 3$ (for all $0 \le i, j \le n - 1$) * $0 \le p[i][j] \le 2$ (for all $0 \le i, j \le n - 1$) and there is at least one construction satisfying the requirements. ## Sample grader The sample grader reads the input in the following format: * line 1: n * line 2 + i (0 ≀ i ≀ n βˆ’ 1): p[i][0] p[i][1] ... p[i][n-1] The output of the sample grader is in the following format: * line 1: the return value of construct. * If the return value of construct is 1, the sample grader additionally prints: * line 2 + i (0 ≀ i ≀ n βˆ’ 1): b[i][0] b[i][1] ... b[i][n-1]
Python
seed_259
# Connecting Supertrees (supertrees) Gardens by the Bay is a large nature park in Singapore. In the park there are n towers, known as supertrees. These towers are labelled 0 to n βˆ’ 1. We would like to construct a set of zero or more bridges. Each bridge connects a pair of distinct towers and may be traversed in either direction. No two bridges should connect the same pair of towers. A path from tower x to tower y is a sequence of one or more towers such that: * the first element of the sequence is x, * the last element of the sequence is y, * all elements of the sequence are distinct, and * each two consecutive elements (towers) in the sequence are connected by a bridge. Note that by definition there is exactly one path from a tower to itself and the number of different paths from tower i to tower j is the same as the number of different paths from tower j to tower i. The lead architect in charge of the design wishes for the bridges to be built such that for all 0 ≀ i, j ≀ n βˆ’ 1 there are exactly p[i][j] different paths from tower i to tower j, where 0 ≀ p[i][j] ≀ 3. Construct a set of bridges that satisfy the architect's requirements, or determine that it is impossible. ## Implementation details You should implement the following procedure: ``` int construct(int[][] p) ``` * p: an n Γ— n array representing the architect's requirements. * If a construction is possible, this procedure should make exactly one call to build (see below) to report the construction, following which it should return 1. * Otherwise, the procedure should return 0 without making any calls to build. * This procedure is called exactly once. The procedure build is defined as follows: ``` void build(int[][] b) ``` * b: an n Γ— n array, with b[i][j] = 1 if there is a bridge connecting tower i and tower j, or b[i][j] = 0 otherwise. * Note that the array must satisfy b[i][j] = b[j][i] for all 0 ≀ i, j ≀ n βˆ’ 1 and b[i][i] = 0 for all 0 ≀ i ≀ n βˆ’ 1. ## Examples ### Example 1 Consider the following call: ``` construct([[1, 1, 2, 2], [1, 1, 2, 2], [2, 2, 1, 2], [2, 2, 2, 1]]) ``` This means that there should be exactly one path from tower 0 to tower 1. For all other pairs of towers (i, y), such that 0 ≀ i < y ≀ 3, there should be exactly two paths from tower i to tower y. This can be achieved with 4 bridges, connecting pairs of towers (0, 1), (1, 2), (1, 3) and (2, 3). To report this solution, the construct procedure should make the following call: ``` build([[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]) ``` It should then return 1. In this case, there are multiple constructions that fit the requirements, all of which would be considered correct. ### Example 2 Consider the following call: ``` construct([[1, 0], [0, 1]]) ``` This means that there should be no way to travel between the two towers. This can only be satisfied by having no bridges. Therefore, the construct procedure should make the following call: ``` build([[0, 0], [0, 0]]) ``` After which, the construct procedure should return 1. ### Example 3 Consider the following call: ``` construct([[1, 3], [3, 1]]) ``` This means that there should be exactly 3 paths from tower 0 to tower 1. This set of requirements cannot be satisfied. As such, the construct procedure should return 0 without making any call to build. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le n \le 1000$ * $p[i][i] = 1$ (for all $0 \le i \le n - 1$) * $p[i][j] = p[j][i]$ (for all $0 \le i, j \le n - 1$) * $0 \le p[i][j] \le 3$ (for all $0 \le i, j \le n - 1$) * $p[i][j] = 0$ or $1$ (for all $0 \le i, j \le n - 1$) ## Sample grader The sample grader reads the input in the following format: * line 1: n * line 2 + i (0 ≀ i ≀ n βˆ’ 1): p[i][0] p[i][1] ... p[i][n-1] The output of the sample grader is in the following format: * line 1: the return value of construct. * If the return value of construct is 1, the sample grader additionally prints: * line 2 + i (0 ≀ i ≀ n βˆ’ 1): b[i][0] b[i][1] ... b[i][n-1]
Python
seed_260
# Connecting Supertrees (supertrees) Gardens by the Bay is a large nature park in Singapore. In the park there are n towers, known as supertrees. These towers are labelled 0 to n βˆ’ 1. We would like to construct a set of zero or more bridges. Each bridge connects a pair of distinct towers and may be traversed in either direction. No two bridges should connect the same pair of towers. A path from tower x to tower y is a sequence of one or more towers such that: * the first element of the sequence is x, * the last element of the sequence is y, * all elements of the sequence are distinct, and * each two consecutive elements (towers) in the sequence are connected by a bridge. Note that by definition there is exactly one path from a tower to itself and the number of different paths from tower i to tower j is the same as the number of different paths from tower j to tower i. The lead architect in charge of the design wishes for the bridges to be built such that for all 0 ≀ i, j ≀ n βˆ’ 1 there are exactly p[i][j] different paths from tower i to tower j, where 0 ≀ p[i][j] ≀ 3. Construct a set of bridges that satisfy the architect's requirements, or determine that it is impossible. ## Implementation details You should implement the following procedure: ``` int construct(int[][] p) ``` * p: an n Γ— n array representing the architect's requirements. * If a construction is possible, this procedure should make exactly one call to build (see below) to report the construction, following which it should return 1. * Otherwise, the procedure should return 0 without making any calls to build. * This procedure is called exactly once. The procedure build is defined as follows: ``` void build(int[][] b) ``` * b: an n Γ— n array, with b[i][j] = 1 if there is a bridge connecting tower i and tower j, or b[i][j] = 0 otherwise. * Note that the array must satisfy b[i][j] = b[j][i] for all 0 ≀ i, j ≀ n βˆ’ 1 and b[i][i] = 0 for all 0 ≀ i ≀ n βˆ’ 1. ## Examples ### Example 1 Consider the following call: ``` construct([[1, 1, 2, 2], [1, 1, 2, 2], [2, 2, 1, 2], [2, 2, 2, 1]]) ``` This means that there should be exactly one path from tower 0 to tower 1. For all other pairs of towers (i, y), such that 0 ≀ i < y ≀ 3, there should be exactly two paths from tower i to tower y. This can be achieved with 4 bridges, connecting pairs of towers (0, 1), (1, 2), (1, 3) and (2, 3). To report this solution, the construct procedure should make the following call: ``` build([[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]) ``` It should then return 1. In this case, there are multiple constructions that fit the requirements, all of which would be considered correct. ### Example 2 Consider the following call: ``` construct([[1, 0], [0, 1]]) ``` This means that there should be no way to travel between the two towers. This can only be satisfied by having no bridges. Therefore, the construct procedure should make the following call: ``` build([[0, 0], [0, 0]]) ``` After which, the construct procedure should return 1. ### Example 3 Consider the following call: ``` construct([[1, 3], [3, 1]]) ``` This means that there should be exactly 3 paths from tower 0 to tower 1. This set of requirements cannot be satisfied. As such, the construct procedure should return 0 without making any call to build. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $1 \le n \le 1000$ * $p[i][i] = 1$ (for all $0 \le i \le n - 1$) * $p[i][j] = p[j][i]$ (for all $0 \le i, j \le n - 1$) * $0 \le p[i][j] \le 3$ (for all $0 \le i, j \le n - 1$) * $p[i][j] = 0$ or $2$ (for all $i \neq j$, $0 \le i, j \le n - 1$) ## Sample grader The sample grader reads the input in the following format: * line 1: n * line 2 + i (0 ≀ i ≀ n βˆ’ 1): p[i][0] p[i][1] ... p[i][n-1] The output of the sample grader is in the following format: * line 1: the return value of construct. * If the return value of construct is 1, the sample grader additionally prints: * line 2 + i (0 ≀ i ≀ n βˆ’ 1): b[i][0] b[i][1] ... b[i][n-1]
Python
seed_264
# Convergents of e The square root of 2 can be written as an infinite continued fraction. ![img](http://img0.ph.126.net/x1Hyc4iHQg0Jz2EInmT3ag==/6597639313681841979.png) The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, √23 = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for √2. ![img](http://img1.ph.126.net/xme9gNBQdA7bvQkwIftznQ==/6597819633588793645.png) Hence the sequence of the first ten convergents for √2 are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, … What is most surprising is that the important mathematical constant, e = [2; 1,2,1, 1,4,1, 1,6,1 , … , 1,2k,1, …]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, … The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17. Find the sum of digits in the numerator of the mth convergent of the continued fraction for e. - Powered by [Project Euler](https://projecteuler.net/problem=65)
Python
seed_265
# Convert Improper Fraction to Mixed Number You will need to convert an [improper fraction](https://www.mathplacementreview.com/arithmetic/fractions.php#improper-fractions) to a [mixed number](https://www.mathplacementreview.com/arithmetic/fractions.php#mixed-number). For example: ```python get_mixed_num('18/11') # Should return '1 7/11' get_mixed_num('13/5') # Should return '2 3/5' get_mixed_num('75/10') # Should return '7 5/10' ``` NOTE: All fractions will be greater than 0.
Python
seed_267
# Convert number to reversed array of digits Given a random non-negative number, you have to return the digits of this number within an array in reverse order. ## Example: ``` 348597 => [7,9,5,8,4,3] ```
Python
seed_268
# Coreputer Coreputer, the brand new computing machine has $N$ cores numbered from $0$ to $N-1$. Recent maintenance revealed that some of the cores are malfunctioning. It is unknown which specific cores are malfunctioning, but there is *at least one* malfunctioning core. To find the malfunctioning cores, Coreputer can run **diagnostic scans**. In each scan, the user tags a (possibly empty) group of *distinct* cores $T[0], \ldots, T[l-1]$ for some $0 \le l \le N$. The rest of the cores are untagged. Coreputer then benchmarks the tagged cores and the untagged ones. Finally, it reports which of the two groups contains a greater number of malfunctioning cores, or that the two groups contain an equal number of malfunctioning cores. Note that an empty group contains $0$ malfunctioning cores. Your task is to find the malfunctioning cores by running diagnostic scans on Coreputer. ## Implementation Details You should implement the following procedure. ``` int[] malfunctioning_cores(int N) ``` * $N$: the number of cores. * This procedure should return an array $c = [c[0], c[1], \ldots, c[N-1]]$, where for each $i$ from $0$ to $N-1$, inclusive, $c[i] = 1$ if core $i$ is malfunctioning, and $c[i] = 0$ otherwise. * This procedure is called exactly once for each test case. The above procedure can make calls to the following procedure: ``` int run_diagnostic(int[] T) ``` * $T$: an array of distinct cores. * This procedure returns * $1$ if there are more tagged cores than untagged cores which are malfunctioning; * $0$ if the number of tagged and untagged malfunctioning cores are equal; * $-1$ if there are fewer tagged cores than untagged cores which are malfunctioning. * This procedure can be called at most 32 times in each test case. The grader is **not adaptive**, meaning that the set of malfunctioning cores is fixed before a call to `malfunctioning_cores` is made. ## Example Consider a scenario when there are $N = 4$ cores, and only core 2 is malfunctioning. Procedure `malfunctioning_cores` is called the following way: ``` malfunctioning_cores(4) ``` The procedure may call `run_diagnostic` as follows. | Call | Tagged cores | Untagged cores | Return value | |------|--------------|----------------|--------------| | `run_diagnostic([0])` | 0 | 1,2,3 | $-1$ | | `run_diagnostic([1, 2])` | 1, 2 | 0, 3 | 1 | | `run_diagnostic([2])` | 2 | 0, 1, 3 | 1 | In the first call, there are no malfunctioning tagged cores, and one untagged core is malfunctioning, so the procedure returns $-1$. After the third call returns 1, it is clear that at least one tagged core (that is, core 2) is malfunctioning. But then, the number of untagged malfunctioning cores must be zero, so we conclude that no other core is malfunctioning. Therefore, the procedure `malfunctioning_cores` should return $[0, 0, 1, 0]$. ## Constraints * $2 \le N \le 16$ In this subtask, you can obtain a partial score based on the number of calls to `run_diagnostic`: * 50% of points if $24 < q \le 32$ calls * 75% of points if $18 < q \le 24$ calls * 100% of points if $q \le 18$ calls If the calls to the procedure `run_diagnostic` do not conform to the constraints described in Implementation Details, or the return value of `malfunctioning_cores` is incorrect, the score of your solution for that subtask will be 0. ## Sample Grader The sample grader reads the input in the following format: * line 1: $N$ * line 2: $M[0] \; M[1] \; \ldots \; M[N-1]$ where for each $i$ from $0$ to $N-1$, inclusive, $M[i] = 1$ if core $i$ is malfunctioning, and $M[i] = 0$ otherwise. Before calling `malfunctioning_cores`, the sample grader checks whether there is at least one malfunctioning core. If this condition is not met, it prints the message `No Malfunctioning Cores` and terminates. If the sample grader detects a protocol violation, the output of the sample grader is `Protocol Violation: <MSG>`, where `<MSG>` is one of the error messages: * `invalid array`: in a call to `run_diagnostic`, array $T$ * has more than $N$ elements, or * contains an element that is not an integer between $0$ and $N-1$, inclusive, or * contains the same element at least twice. * `too many calls`: the number of calls made to `run_diagnostic` exceeds 32. Otherwise, let the elements of the array returned by `malfunctioning_cores` be $c[0], c[1], \ldots, c[n-1]$ for some nonnegative $n$. The output of the sample grader is in the following format: * line 1: $c[0] \; c[1] \; \ldots \; c[n-1]$ * line 2: the number of calls to `run_diagnostic`
Python
seed_270
# Coreputer Coreputer, the brand new computing machine has $N$ cores numbered from $0$ to $N-1$. Recent maintenance revealed that some of the cores are malfunctioning. It is unknown which specific cores are malfunctioning, but there is *at least one* malfunctioning core. To find the malfunctioning cores, Coreputer can run **diagnostic scans**. In each scan, the user tags a (possibly empty) group of *distinct* cores $T[0], \ldots, T[l-1]$ for some $0 \le l \le N$. The rest of the cores are untagged. Coreputer then benchmarks the tagged cores and the untagged ones. Finally, it reports which of the two groups contains a greater number of malfunctioning cores, or that the two groups contain an equal number of malfunctioning cores. Note that an empty group contains $0$ malfunctioning cores. Your task is to find the malfunctioning cores by running diagnostic scans on Coreputer. ## Implementation Details You should implement the following procedure. ``` int[] malfunctioning_cores(int N) ``` * $N$: the number of cores. * This procedure should return an array $c = [c[0], c[1], \ldots, c[N-1]]$, where for each $i$ from $0$ to $N-1$, inclusive, $c[i] = 1$ if core $i$ is malfunctioning, and $c[i] = 0$ otherwise. * This procedure is called exactly once for each test case. The above procedure can make calls to the following procedure: ``` int run_diagnostic(int[] T) ``` * $T$: an array of distinct cores. * This procedure returns * $1$ if there are more tagged cores than untagged cores which are malfunctioning; * $0$ if the number of tagged and untagged malfunctioning cores are equal; * $-1$ if there are fewer tagged cores than untagged cores which are malfunctioning. * This procedure can be called at most 32 times in each test case. The grader is **not adaptive**, meaning that the set of malfunctioning cores is fixed before a call to `malfunctioning_cores` is made. ## Example Consider a scenario when there are $N = 4$ cores, and only core 2 is malfunctioning. Procedure `malfunctioning_cores` is called the following way: ``` malfunctioning_cores(4) ``` The procedure may call `run_diagnostic` as follows. | Call | Tagged cores | Untagged cores | Return value | |------|--------------|----------------|--------------| | `run_diagnostic([0])` | 0 | 1,2,3 | $-1$ | | `run_diagnostic([1, 2])` | 1, 2 | 0, 3 | 1 | | `run_diagnostic([2])` | 2 | 0, 1, 3 | 1 | In the first call, there are no malfunctioning tagged cores, and one untagged core is malfunctioning, so the procedure returns $-1$. After the third call returns 1, it is clear that at least one tagged core (that is, core 2) is malfunctioning. But then, the number of untagged malfunctioning cores must be zero, so we conclude that no other core is malfunctioning. Therefore, the procedure `malfunctioning_cores` should return $[0, 0, 1, 0]$. ## Constraints Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: * $2 \le N \le 16$ * The number of malfunctioning cores is even. In this subtask, you can obtain a partial score based on the number of calls to `run_diagnostic`: * 50% of points if $24 < q \le 32$ calls * 75% of points if $18 < q \le 24$ calls * 100% of points if $q \le 18$ calls ## Sample Grader The sample grader reads the input in the following format: * line 1: $N$ * line 2: $M[0] \; M[1] \; \ldots \; M[N-1]$ where for each $i$ from $0$ to $N-1$, inclusive, $M[i] = 1$ if core $i$ is malfunctioning, and $M[i] = 0$ otherwise. Before calling `malfunctioning_cores`, the sample grader checks whether there is at least one malfunctioning core. If this condition is not met, it prints the message `No Malfunctioning Cores` and terminates. If the sample grader detects a protocol violation, the output of the sample grader is `Protocol Violation: <MSG>`, where `<MSG>` is one of the error messages: * `invalid array`: in a call to `run_diagnostic`, array $T$ * has more than $N$ elements, or * contains an element that is not an integer between $0$ and $N-1$, inclusive, or * contains the same element at least twice. * `too many calls`: the number of calls made to `run_diagnostic` exceeds 32. Otherwise, let the elements of the array returned by `malfunctioning_cores` be $c[0], c[1], \ldots, c[n-1]$ for some nonnegative $n$. The output of the sample grader is in the following format: * line 1: $c[0] \; c[1] \; \ldots \; c[n-1]$ * line 2: the number of calls to `run_diagnostic`
Python
seed_274
# Crayfish scrivener Some people say that Leonardo was a great admirer of Johannes Gutenberg, the German blacksmith who invented movable-type printing, and that he paid homage by designing a machine called the crayfish scrivener --- *il gambero scrivano* --- a very simple typing device. It is somehow similar to a simple modern typewriter and accepts only two commands: one to type the next character and one to undo the most recent commands. The notable feature of the crayfish scrivener is that the undo command is extremely powerful: an undo is also considered to be a command itself, and can be undone. ## Statement Your task is to realize a software version of the crayfish scrivener: it starts with an empty text and accepts a sequence of commands entered by the user, and queries for specific positions of the current version of the text, as follows. - **Init()** --- called once at the beginning of the execution, without arguments. It can be used for initializing data structures. It will never need to be undone. - **TypeLetter(L)** --- append to the end of the text a single lowercase letter `L` chosen from `a, ..., z`. - **UndoCommands(U)** --- undo the last `U` commands, for a positive integer `U`. - **GetLetter(P)** --- return the letter at position `P` in the current text, for a non-negative index `P`. The first letter in the text has index `0`. (This query is not a command and thus is ignored by the undo command.) After the initial call to **Init()**, the other routines can be called zero or more times in any order. It is guaranteed that `U` will not exceed the number of previously received commands, and that `P` will be less than the current text length (the number of letters in the current text). As for **UndoCommands(U)**, it undoes the previous `U` commands in *reverse order*: if the command to be undone is **TypeLetter(L)**, then it removes `L` from the end of the current text; if the command to be undone is **UndoCommands(X)** for some value `X`, it re-does the previous `X` commands in their *original order*. ### Example We show a possible sequence of calls, together with the state of the text after each call. | **Call** | **Returns** | **Current text** | |---------------------|-------------|------------------| | Init() | | | | TypeLetter(a) | | a | | TypeLetter(b) | | ab | | GetLetter(1) | b | ab | | TypeLetter(d) | | abd | | UndoCommands(2) | | a | | UndoCommands(1) | | abd | | GetLetter(2) | d | abd | | TypeLetter(e) | | abde | | UndoCommands(1) | | abd | | UndoCommands(5) | | ab | | TypeLetter(c) | | abc | | GetLetter(2) | c | abc | | UndoCommands(2) | | abd | | GetLetter(2) | d | abd | ## Implementation details You have to submit exactly one file, called `scrivener.c`, `scrivener.cpp` or `scrivener.pas`. This file must implement the subprograms described above using the following signatures. ### C/C++ programs ``` void Init(); void TypeLetter(char L); void UndoCommands(int U); char GetLetter(int P); ``` ### Pascal programs ``` procedure Init; procedure TypeLetter(L : Char); procedure UndoCommands(U : LongInt); function GetLetter(P : LongInt) : Char; ``` These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file. ### Sample grader The sample grader reads the input in the following format: - **line 1**: the total number of commands and queries in the input; - on each following line: - **T** followed by a space and a lowercase letter for a **TypeLetter** command; - **U** followed by a space and an integer for **UndoCommands**; - **P** followed by a space and an integer for **GetLetter**. The sample grader will print the characters returned by **GetLetter**, each one on a separate line. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: The total number of commands and queries is between 1 and 1,000,000 (inclusive).
Python
seed_275
# Crayfish scrivener Some people say that Leonardo was a great admirer of Johannes Gutenberg, the German blacksmith who invented movable-type printing, and that he paid homage by designing a machine called the crayfish scrivener --- *il gambero scrivano* --- a very simple typing device. It is somehow similar to a simple modern typewriter and accepts only two commands: one to type the next character and one to undo the most recent commands. The notable feature of the crayfish scrivener is that the undo command is extremely powerful: an undo is also considered to be a command itself, and can be undone. ## Statement Your task is to realize a software version of the crayfish scrivener: it starts with an empty text and accepts a sequence of commands entered by the user, and queries for specific positions of the current version of the text, as follows. - **Init()** --- called once at the beginning of the execution, without arguments. It can be used for initializing data structures. It will never need to be undone. - **TypeLetter(L)** --- append to the end of the text a single lowercase letter `L` chosen from `a, ..., z`. - **UndoCommands(U)** --- undo the last `U` commands, for a positive integer `U`. - **GetLetter(P)** --- return the letter at position `P` in the current text, for a non-negative index `P`. The first letter in the text has index `0`. (This query is not a command and thus is ignored by the undo command.) After the initial call to **Init()**, the other routines can be called zero or more times in any order. It is guaranteed that `U` will not exceed the number of previously received commands, and that `P` will be less than the current text length (the number of letters in the current text). As for **UndoCommands(U)**, it undoes the previous `U` commands in *reverse order*: if the command to be undone is **TypeLetter(L)**, then it removes `L` from the end of the current text; if the command to be undone is **UndoCommands(X)** for some value `X`, it re-does the previous `X` commands in their *original order*. ### Example We show a possible sequence of calls, together with the state of the text after each call. | **Call** | **Returns** | **Current text** | |---------------------|-------------|------------------| | Init() | | | | TypeLetter(a) | | a | | TypeLetter(b) | | ab | | GetLetter(1) | b | ab | | TypeLetter(d) | | abd | | UndoCommands(2) | | a | | UndoCommands(1) | | abd | | GetLetter(2) | d | abd | | TypeLetter(e) | | abde | | UndoCommands(1) | | abd | | UndoCommands(5) | | ab | | TypeLetter(c) | | abc | | GetLetter(2) | c | abc | | UndoCommands(2) | | abd | | GetLetter(2) | d | abd | ## Implementation details You have to submit exactly one file, called `scrivener.c`, `scrivener.cpp` or `scrivener.pas`. This file must implement the subprograms described above using the following signatures. ### C/C++ programs ``` void Init(); void TypeLetter(char L); void UndoCommands(int U); char GetLetter(int P); ``` ### Pascal programs ``` procedure Init; procedure TypeLetter(L : Char); procedure UndoCommands(U : LongInt); function GetLetter(P : LongInt) : Char; ``` These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file. ### Sample grader The sample grader reads the input in the following format: - **line 1**: the total number of commands and queries in the input; - on each following line: - **T** followed by a space and a lowercase letter for a **TypeLetter** command; - **U** followed by a space and an integer for **UndoCommands**; - **P** followed by a space and an integer for **GetLetter**. The sample grader will print the characters returned by **GetLetter**, each one on a separate line. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: The total number of commands and queries is between 1 and 1,000,000 (inclusive). All calls to **GetLetter** will occur after all calls to **TypeLetter** and **UndoCommands**.
Python
seed_276
# Crayfish scrivener Some people say that Leonardo was a great admirer of Johannes Gutenberg, the German blacksmith who invented movable-type printing, and that he paid homage by designing a machine called the crayfish scrivener --- *il gambero scrivano* --- a very simple typing device. It is somehow similar to a simple modern typewriter and accepts only two commands: one to type the next character and one to undo the most recent commands. The notable feature of the crayfish scrivener is that the undo command is extremely powerful: an undo is also considered to be a command itself, and can be undone. ## Statement Your task is to realize a software version of the crayfish scrivener: it starts with an empty text and accepts a sequence of commands entered by the user, and queries for specific positions of the current version of the text, as follows. - **Init()** --- called once at the beginning of the execution, without arguments. It can be used for initializing data structures. It will never need to be undone. - **TypeLetter(L)** --- append to the end of the text a single lowercase letter `L` chosen from `a, ..., z`. - **UndoCommands(U)** --- undo the last `U` commands, for a positive integer `U`. - **GetLetter(P)** --- return the letter at position `P` in the current text, for a non-negative index `P`. The first letter in the text has index `0`. (This query is not a command and thus is ignored by the undo command.) After the initial call to **Init()**, the other routines can be called zero or more times in any order. It is guaranteed that `U` will not exceed the number of previously received commands, and that `P` will be less than the current text length (the number of letters in the current text). As for **UndoCommands(U)**, it undoes the previous `U` commands in *reverse order*: if the command to be undone is **TypeLetter(L)**, then it removes `L` from the end of the current text; if the command to be undone is **UndoCommands(X)** for some value `X`, it re-does the previous `X` commands in their *original order*. ### Example We show a possible sequence of calls, together with the state of the text after each call. | **Call** | **Returns** | **Current text** | |---------------------|-------------|------------------| | Init() | | | | TypeLetter(a) | | a | | TypeLetter(b) | | ab | | GetLetter(1) | b | ab | | TypeLetter(d) | | abd | | UndoCommands(2) | | a | | UndoCommands(1) | | abd | | GetLetter(2) | d | abd | | TypeLetter(e) | | abde | | UndoCommands(1) | | abd | | UndoCommands(5) | | ab | | TypeLetter(c) | | abc | | GetLetter(2) | c | abc | | UndoCommands(2) | | abd | | GetLetter(2) | d | abd | ## Implementation details You have to submit exactly one file, called `scrivener.c`, `scrivener.cpp` or `scrivener.pas`. This file must implement the subprograms described above using the following signatures. ### C/C++ programs ``` void Init(); void TypeLetter(char L); void UndoCommands(int U); char GetLetter(int P); ``` ### Pascal programs ``` procedure Init; procedure TypeLetter(L : Char); procedure UndoCommands(U : LongInt); function GetLetter(P : LongInt) : Char; ``` These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file. ### Sample grader The sample grader reads the input in the following format: - **line 1**: the total number of commands and queries in the input; - on each following line: - **T** followed by a space and a lowercase letter for a **TypeLetter** command; - **U** followed by a space and an integer for **UndoCommands**; - **P** followed by a space and an integer for **GetLetter**. The sample grader will print the characters returned by **GetLetter**, each one on a separate line. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: The total number of commands and queries is between 1 and 100 (inclusive) and no **UndoCommands** will be undone.
Python
seed_278
# Crayfish scrivener Some people say that Leonardo was a great admirer of Johannes Gutenberg, the German blacksmith who invented movable-type printing, and that he paid homage by designing a machine called the crayfish scrivener --- *il gambero scrivano* --- a very simple typing device. It is somehow similar to a simple modern typewriter and accepts only two commands: one to type the next character and one to undo the most recent commands. The notable feature of the crayfish scrivener is that the undo command is extremely powerful: an undo is also considered to be a command itself, and can be undone. ## Statement Your task is to realize a software version of the crayfish scrivener: it starts with an empty text and accepts a sequence of commands entered by the user, and queries for specific positions of the current version of the text, as follows. - **Init()** --- called once at the beginning of the execution, without arguments. It can be used for initializing data structures. It will never need to be undone. - **TypeLetter(L)** --- append to the end of the text a single lowercase letter `L` chosen from `a, ..., z`. - **UndoCommands(U)** --- undo the last `U` commands, for a positive integer `U`. - **GetLetter(P)** --- return the letter at position `P` in the current text, for a non-negative index `P`. The first letter in the text has index `0`. (This query is not a command and thus is ignored by the undo command.) After the initial call to **Init()**, the other routines can be called zero or more times in any order. It is guaranteed that `U` will not exceed the number of previously received commands, and that `P` will be less than the current text length (the number of letters in the current text). As for **UndoCommands(U)**, it undoes the previous `U` commands in *reverse order*: if the command to be undone is **TypeLetter(L)**, then it removes `L` from the end of the current text; if the command to be undone is **UndoCommands(X)** for some value `X`, it re-does the previous `X` commands in their *original order*. ### Example We show a possible sequence of calls, together with the state of the text after each call. | **Call** | **Returns** | **Current text** | |---------------------|-------------|------------------| | Init() | | | | TypeLetter(a) | | a | | TypeLetter(b) | | ab | | GetLetter(1) | b | ab | | TypeLetter(d) | | abd | | UndoCommands(2) | | a | | UndoCommands(1) | | abd | | GetLetter(2) | d | abd | | TypeLetter(e) | | abde | | UndoCommands(1) | | abd | | UndoCommands(5) | | ab | | TypeLetter(c) | | abc | | GetLetter(2) | c | abc | | UndoCommands(2) | | abd | | GetLetter(2) | d | abd | ## Implementation details You have to submit exactly one file, called `scrivener.c`, `scrivener.cpp` or `scrivener.pas`. This file must implement the subprograms described above using the following signatures. ### C/C++ programs ``` void Init(); void TypeLetter(char L); void UndoCommands(int U); char GetLetter(int P); ``` ### Pascal programs ``` procedure Init; procedure TypeLetter(L : Char); procedure UndoCommands(U : LongInt); function GetLetter(P : LongInt) : Char; ``` These subprograms must behave as described above. Of course you are free to implement other subprograms for their internal use. Your submissions must not interact in any way with standard input/output, nor with any other file. ### Sample grader The sample grader reads the input in the following format: - **line 1**: the total number of commands and queries in the input; - on each following line: - **T** followed by a space and a lowercase letter for a **TypeLetter** command; - **U** followed by a space and an integer for **UndoCommands**; - **P** followed by a space and an integer for **GetLetter**. The sample grader will print the characters returned by **GetLetter**, each one on a separate line. Do note that you DO NOT necessarily have to solve for the general case, but only for the subproblem defined by the following constraints: The total number of commands and queries is between 1 and 5,000 (inclusive).
Python