Prompt:
def sum_of_multiples(T: int, test_cases: List[int]) -> List[int]:
    """
    Find sum of all the numbers that are multiples of 10 and are less than or equal to a given number "N". (quotes for clarity and be careful of integer overflow)

    -----Input-----
    Input will start with an integer T the count of test cases, each case will have an integer N.

    -----Output-----
    Output each values, on a newline.

    -----Constraints-----
    - 1 ≤ T ≤ 10
    - 1 ≤ N ≤1000000000

    -----Example-----
    Input:
    1
    10

    Output:
    10

    -----Explanation-----
    Example case 1. Only integer that is multiple 10 that is less than or equal to 10 is 10
    """

def check(candidate):
    assert candidate(1, [10]) == [10]
    assert candidate(2, [10, 20]) == [10, 30]
    assert candidate(1, [1]) == [0]
    assert candidate(3, [30, 40, 50]) == [60, 100, 150]
check(sum_of_multiples)

assert sum_of_multiples(1, [10]) == [10]


Prompt:
def avoid_arrest(T: int, test_cases: List[Tuple[int, int, int, List[int]]]) -> List[int]:
    """
    The Little Elephant and his friends from the Zoo of Lviv were returning from the party. But suddenly they were stopped by the policeman Big Hippo, who wanted to make an alcohol test for elephants.
    There were N elephants ordered from the left to the right in a row and numbered from 0 to N-1. Let R[i] to be the result of breathalyzer test of i-th elephant.
    Considering current laws in the Zoo, elephants would be arrested if there exists K consecutive elephants among them for which at least M of these K elephants have the maximal test result among these K elephants.
    Using poor math notations we can alternatively define this as follows. The elephants would be arrested if there exists i from 0 to N-K, inclusive, such that for at least M different values of j from i to i+K-1, inclusive, we have R[j] = max{R[i], R[i+1], ..., R[i+K-1]}.

    The Big Hippo is very old and the Little Elephant can change some of the results. In a single operation he can add 1 to the result of any elephant. But for each of the elephants he can apply this operation at most once.
    What is the minimum number of operations that the Little Elephant needs to apply, such that the sequence of results, after all operations will be applied, let elephants to avoid the arrest? If it is impossible to avoid the arrest applying any number of operations, output -1.

    -----Input-----
    The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains three space-separated integers N, K, M. The second line contains N space-separated integers  R[0], R[1], ..., R[N-1] denoting the test results of the elephants.

    -----Output-----
    For each test case, output a single line containing the minimum number of operations needed to avoid the arrest.

    -----Constraints-----
    - 1 ≤ T ≤ 10
    - 1 ≤ M ≤ K ≤ N ≤ 17
    - 1 ≤ R[i] ≤ 17

    -----Example-----
    Input:
    4
    5 3 2
    1 3 1 2 1
    5 3 3
    7 7 7 7 7
    5 3 3
    7 7 7 8 8
    4 3 1
    1 3 1 2

    Output:
    0
    1
    1
    -1

    -----Explanation-----
    Example case 1. Let's follow the poor math definition of arrest. We will consider all values of i from 0 to N-K = 2, inclusive, and should count the number of values of j described in the definition. If it less than M = 2 then this value of i does not cause the arrest, otherwise causes.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1
    we have R[j] = maxConclusioni=0{1, 3, 1}max = 3R[j] = 3 for j = 1does not cause the arresti=1{3, 1, 2}max = 3R[j] = 3 for j = 1does not cause the arresti=2{1, 2, 1}max = 2R[j] = 2 for j = 3does not cause the arrest
    So we see that initial test results of the elephants do not cause their arrest. Hence the Little Elephant does not need to apply any operations. Therefore, the answer is 0.
    Example case 2.We have N = 5, K = 3, M = 3. Let's construct similar table as in example case 1. Here the value of i will cause the arrest if we have at least 3 values of j described in the definition.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1
    we have R[j] = maxConclusioni=0{7, 7, 7}max = 7R[j] = 7 for j = 0, 1, 2causes the arresti=1{7, 7, 7}max = 7R[j] = 7 for j = 1, 2, 3causes the arresti=2{7, 7, 7}max = 7R[j] = 7 for j = 2, 3, 4causes the arrest
    So we see that for initial test results of the elephants each value of i causes their arrest. Hence the Little Elephant needs to apply some operations in order to avoid the arrest. He could achieve his goal by adding 1 to the result R[2]. Then results will be {R[0], R[1], R[2], R[3], R[4]} = {7, 7, 8, 7, 7}. Let's check that now elephants will be not arrested.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1
    we have R[j] = maxConclusioni=0{7, 7, 8}max = 8R[j] = 8 for j = 2does not cause the arresti=1{7, 8, 7}max = 8R[j] = 8 for j = 2does not cause the arresti=2{8, 7, 7}max = 8R[j] = 8 for j = 2does not cause the arrest
    So we see that now test results of the elephants do not cause their arrest. Thus we see that using 0 operations we can't avoid the arrest but using 1 operation can. Hence the answer is 1.
    Example case 3.We have N = 5, K = 3, M = 3. Let's construct similar table as in example case 1. Here the value of i will cause the arrest if we have at least 3 values of j described in the definition.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1
    we have R[j] = maxConclusioni=0{7, 7, 7}max = 7R[j] = 7 for j = 0, 1, 2causes the arresti=1{7, 7, 8}max = 8R[j] = 8 for j = 3does not cause the arresti=2{7, 8, 8}max = 8R[j] = 8 for j = 3, 4does not cause the arrest
    So we see that for initial test results of the elephants the value of i = 0 causes their arrest. Hence the Little Elephant needs to apply some operations in order to avoid the arrest. He could achieve his goal by adding 1 to the result R[1]. Then results will be {R[0], R[1], R[2], R[3], R[4]} = {7, 8, 7, 8, 8}. Let's check that now elephants will be not arrested.i{R[i],...,R[i+K-1]}max{R[i],...,R[i+K-1]}For which j = i, ..., i+K-1
    we have R[j] = maxConclusioni=0{7, 8, 7}max = 8R[j] = 8 for j = 1does not cause the arresti=1{8, 7, 8}max = 8R[j] = 8 for j = 1, 3does not cause the arresti=2{7, 8, 8}max = 8R[j] = 8 for j = 3, 4does not cause the arrest
    So we see that now test results of the elephants do not cause their arrest. Thus we see that using 0 operations we can't avoid the arrest but using 1 operation can. Hence the answer is 1. Note that if we increase by 1 the result R[2] instead of R[1] then the value i = 2 will cause the arrest since {R[2], R[3], R[4]} will be {8, 8, 8} after this operation and we will have 3 values of j from 2 to 4, inclusive, for which R[j] = max{R[2], R[3], R[4]}, namely, j = 2, 3, 4.
    Example case 4. When M = 1 the Little Elephant can't reach the goal since for each value of i from 0 to N-K we have at least one value of j for which R[j] = max{R[i], R[i+1], ..., R[i+K-1]}.
    """


Prompt:
def max_nice_bouquet(T: int, test_cases: List[Tuple[List[int], List[int], List[int]]]) -> List[int]:
    """
    It's autumn now, the time of the leaf fall.
    Sergey likes to collect fallen leaves in autumn. In his city, he can find fallen leaves of maple, oak and poplar. These leaves can be of three different colors: green, yellow or red.
    Sergey has collected some leaves of each type and color. Now he wants to create the biggest nice bouquet from them. He considers the bouquet nice iff all the leaves in it are either from the same type of tree or of the same color (or both). Moreover, he doesn't want to create a bouquet with even number of leaves in it, since this kind of bouquets are considered to attract bad luck. However, if it's impossible to make any nice bouquet, he won't do anything, thus, obtaining a bouquet with zero leaves.
    Please help Sergey to find the maximal number of leaves he can have in a nice bouquet, which satisfies all the above mentioned requirements.
    Please note that Sergey doesn't have to use all the leaves of the same color or of the same type. For example, if he has 20 maple leaves, he can still create a bouquet of 19 leaves.

    -----Input-----
    IThe first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows."
    The first line of each test case contains three space-separated integers MG MY MR denoting the number of green, yellow and red maple leaves respectively.
    The second line contains three space-separated integers OG OY OR denoting the number of green, yellow and red oak leaves respectively.
    The third line of each test case contains three space-separated integers PG PY PR denoting the number of green, yellow and red poplar leaves respectively.

    -----Output-----
    For each test case, output a single line containing the maximal amount of flowers in nice bouquet, satisfying all conditions or 0 if it's impossible to create any bouquet, satisfying the conditions.

    -----Constraints-----

    - 1 ≤ T ≤ 10000
    - Subtask 1 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤ 5
    - Subtask 2 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤ 109

    -----Example-----
    Input:1
    1 2 3
    3 2 1
    1 3 4

    Output:7

    -----Explanation-----
    Example case 1. We can create a bouquet with 7 leaves, for example, by collecting all yellow leaves. This is not the only way to create the nice bouquet with 7 leaves (for example, Sergey can use all but one red leaves), but it is impossible to create a nice bouquet with more than 7 leaves.
    """

def check(candidate):
    assert candidate(1, [([1, 2, 3], [3, 2, 1], [1, 3, 4])]) == [7]
check(max_nice_bouquet)


Prompt:
def max_gcd_of_tracks(T: int, test_cases: List[Tuple[int, str, Tuple[int, int, int]]]) -> List[int]:
    """
    Mr. Wilson was planning to record his new Progressive Rock music album called "Digits. Cannot. Separate". Xenny and PowerShell, popular pseudo-number-theoreticists from the Land of Lazarus were called by him to devise a strategy to ensure the success of this new album. Xenny and Powershell took their Piano Lessons and arrived at the Studio in different Trains.
    Mr. Wilson, creative as usual, had created one single, long music track S. The track consisted of N musical notes. The beauty of each musical note was represented by a decimal digit from 0 to 9.
    Mr. Wilson told them that he wanted to create multiple musical tracks out of this long song. Since Xenny and Powershell were more into the number theory part of music, they didn’t know much about their real workings. Mr. Wilson told them that a separator could be placed between 2 digits. After placing separators, the digits between 2 separators would be the constituents of this new track and the number formed by joining them together would represent the Quality Value of that track. He also wanted them to make sure that no number formed had greater than M digits.
    Mr. Wilson had Y separators with him. He wanted Xenny and PowerShell to use at least X of those separators, otherwise he would have to ask them to Drive Home.
    Xenny and PowerShell knew straight away that they had to put place separators in such a way that the Greatest Common Divisor (GCD) of all the Quality Values would eventually determine the success of this new album. Hence, they had to find a strategy to maximize the GCD.
    If you find the maximum GCD of all Quality Values that can be obtained after placing the separators, Xenny and PowerShell shall present you with a Porcupine Tree.
    Note:
    -
    You can read about GCD here.

    -
    Greatest Common Divisor of 0 and 0 is defined as 0.

    -----Input-----
    The first line of input consists of a single integer T - the number of testcases.
    Each test case is of the following format:
    First line contains a single integer N - the length of the long musical track.
    Second line contains the string of digits S.
    Third line contains 3 space-separated integers - M, X and Y - the maximum number of digits in a number, the minimum number of separators to be used and the maximum number of separators to be used.

    -----Output-----
    For each testcase, output a single integer on a new line - the maximum GCD possible after placing the separators.

    -----Constraints-----
    Subtask 1: 20 points

    - 1 ≤ T ≤ 10
    - 1 ≤ N ≤ 18
    - 1 ≤ M ≤ 2
    - 1 ≤ X ≤ Y ≤ (N - 1)

    Subtask 2: 80 points

    - 1 ≤ T ≤ 10
    - 1 ≤ N ≤ 300
    - 1 ≤ M ≤ 10
    - 1 ≤ X ≤ Y ≤ (N - 1)

    For both Subtask 1 and Subtask 2:

    - 1 ≤ X ≤ Y ≤ (N - 1)
    - M*(Y+1) ≥ N
    - S may contain leading 0s.

    -----Example-----Input:
    2
    3
    474
    2 1 1
    34
    6311861109697810998905373107116111
    10 4 25

    Output:
    2
    1

    -----Explanation-----
    Test case 1.
    Since only 1 separator can be placed, we can only have 2 possibilities:

    a. 4 | 74

    The GCD in this case is 2.

    b. 47 | 4

    The GCD in this case is 1.

    Hence, the maximum GCD is 2.
    Test case 2.

    One of the optimal partitions is:
    63|118|61|109|69|78|109|98|90|53|73|107|116|111
    Bonus: Decode the above partition to unlock a hidden treasure.
    """


Prompt:
def count_trips(T: int, test_cases: List[Tuple[int, int, int, List[Tuple[int, int]], int, List[Tuple[int, int]]]]) -> List[int]:
    """
    Nadaca is a country with N$N$ cities. These cities are numbered 1$1$ through N$N$ and connected by M$M$ bidirectional roads. Each city can be reached from every other city using these roads.
    Initially, Ryan is in city 1$1$. At each of the following K$K$ seconds, he may move from his current city to an adjacent city (a city connected by a road to his current city) or stay at his current city. Ryan also has Q$Q$ conditions (a1,b1),(a2,b2),…,(aQ,bQ)$(a_1, b_1), (a_2, b_2), \ldots, (a_Q, b_Q)$ meaning that during this K$K$-second trip, for each valid i$i$, he wants to be in city ai$a_i$ after exactly bi$b_i$ seconds.
    Since you are very good with directions, Ryan asked you to tell him how many different trips he could make while satisfying all conditions. Compute this number modulo 109+7$10^9 + 7$. A trip is a sequence of Ryan's current cities after 1,2,…,K$1, 2, \ldots, K$ seconds.

    -----Input-----
    - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
    - The first line of each test case contains three space-separated integers N$N$, M$M$ and K$K$.
    - Each of the next M$M$ lines contains two space-separated integers u$u$ and v$v$ denoting a road between cities u$u$ and v$v$.
    - The next line contains a single integer Q$Q$.
    - Q$Q$ lines follow. For each i$i$ (1≤i≤Q$1 \le i \le Q$), the i$i$-th of these lines contains two space-separated integers ai$a_i$ and bi$b_i$.

    -----Output-----
    For each test case, print a single line containing one integer — the number of trips Ryan can make, modulo 109+7$10^9+7$.

    -----Constraints-----
    - 1≤T≤50$1 \le T \le 50$
    - 1≤N,M,K,Q≤9,000$1 \le N, M, K, Q \le 9,000$
    - 1≤ui,vi≤N$1 \le u_i, v_i \le N$ for each valid i$i$
    - ui≠vi$u_i \neq v_i$ for each valid i$i$
    - there is at most one road between each pair of cities
    - each city is reachable from every other city
    - 1≤ai≤N$1 \le a_i \le N$ for each valid i$i$
    - 0≤bi≤K$0 \le b_i \le K$ for each valid i$i$
    - the sum of N$N$ over all test cases does not exceed 9,000$9,000$
    - the sum of K$K$ over all test cases does not exceed 9,000$9,000$
    - the sum of M$M$ over all test cases does not exceed 9,000$9,000$
    - the sum of Q$Q$ over all test cases does not exceed 9,000$9,000$

    -----Subtasks-----
    Subtask #1 (20 points):
    - the sum of N$N$ over all test cases does not exceed 400$400$
    - the sum of K$K$ over all test cases does not exceed 400$400$
    - the sum of M$M$ over all test cases does not exceed 400$400$
    - the sum of Q$Q$ over all test cases does not exceed 400$400$
    Subtask #2 (80 points): original constraints

    -----Example Input-----
    3
    4 3 3
    1 2
    1 3
    1 4
    0
    4 3 3
    1 2
    1 3
    1 4
    1
    2 2
    4 3 3
    1 2
    1 3
    1 4
    1
    2 1

    -----Example Output-----
    28
    4
    6
    """


Prompt:
def min_moves_to_sort(N: int, books: List[int]) -> int:
    """
    Indraneel has to sort the books in his library. His library has one long shelf. His books are numbered $1$ through $N$ and he wants to rearrange the books so that they appear in the sequence $1,2, ..., N$.
    He intends to do this by a sequence of moves. In each move he can pick up any book from the shelf and insert it at a different place in the shelf. Suppose Indraneel has $5$ books and they are initially arranged in the order
    21453214532 \quad 1 \quad 4 \quad 5 \quad 3
    Indraneel will rearrange this in ascending order by first moving book $1$ to the beginning of the shelf to get
    12453124531 \quad 2 \quad 4 \quad 5 \quad 3
    Then, moving book $3$ to position $3$, he gets
    12345123451 \quad 2 \quad 3 \quad 4 \quad 5
    Your task is to write a program to help Indraneel determine the minimum number of moves that are necessary to sort his book shelf.

    -----Input:-----
    The first line of the input will contain a single integer $N$ indicating the number of books in Indraneel's library. This is followed by a line containing a permutation of $1, 2, ..., N$ indicating the intial state of Indraneel's book-shelf.

    -----Output:-----
    A single integer indicating the minimum number of moves necessary to sort Indraneel's book-shelf.

    -----Constraints:-----
    - $1 \leq N \leq 200000$.
    - You may also assume that in $50 \%$ of the inputs, $1 \leq N \leq 5000$.

    -----Sample Input-----
    5
    2 1 4 5 3

    -----Sample Output-----
    2
    """

def check(candidate):
    assert candidate(5, [2, 1, 4, 5, 3]) == 2
check(min_moves_to_sort)


Prompt:
def score_of_parentheses(S: str) -> int:
    """
    Given a balanced parentheses string S, compute the score of the string based on the following rule:

    () has score 1
    AB has score A + B, where A and B are balanced parentheses strings.
    (A) has score 2 * A, where A is a balanced parentheses string.

    Example 1:
    Input: "()"
    Output: 1

    Example 2:
    Input: "(())"
    Output: 2

    Example 3:
    Input: "()()"
    Output: 2

    Example 4:
    Input: "(()(()))"
    Output: 6

    Note:

    S is a balanced parentheses string, containing only ( and ).
    2 <= S.length <= 50
    """

def check(candidate):
    assert candidate('()') == 1
    assert candidate('(())') == 2
    assert candidate('()()') == 2
    assert candidate('(()(()))') == 6
check(score_of_parentheses)

assert score_of_parentheses('(())') == 2

assert score_of_parentheses('()()') == 2

assert score_of_parentheses('(()(()))') == 6


Prompt:
def factorial_modulo(T: int, numbers: List[int]) -> List[int]:
    """
    Master Oogway has forseen that a panda named Po will be the dragon warrior, and the master of Chi. But he did not tell anyone about the spell that would make him the master of Chi, and has left Po confused. Now Po has to defeat Kai, who is the super villian, the strongest of them all. Po needs to master Chi, and he finds a spell which unlocks his powerful Chi. But the spell is rather strange. It asks Po to calculate the factorial of a number! Po is very good at mathematics, and thinks that this is very easy. So he leaves the spell, thinking it's a hoax. But little does he know that this can give him the ultimate power of Chi. Help Po by solving the spell and proving that it's not a hoax.

    -----Input-----
    First line of input contains an integer T denoting the number of test cases.
    The next T lines contain an integer N.

    -----Output-----
    For each test case, print a single line containing the solution to the spell which is equal to factorial of N, i.e. N!. Since the output could be large, output it modulo 1589540031(Grand Master Oogway's current age).

    -----Constraints-----
    - 1 ≤ T ≤ 100000
    - 1 ≤ N ≤ 100000

    -----Example-----
    Input:
    4
    1
    2
    3
    4

    Output:
    1
    2
    6
    24
    """

def check(candidate):
    assert candidate(4, [1, 2, 3, 4]) == [1, 2, 6, 24]
check(factorial_modulo)


Prompt:
def expected_cost(T: int, test_cases: List[Tuple[int, int, List[Tuple[int, int]]]]) -> List[float]:
    """
    The Little Elephant from the Zoo of Lviv is going to the Birthday Party of  the Big Hippo tomorrow. Now he wants to prepare a gift for the Big Hippo.

    He has N balloons, numbered from 1 to N. The i-th balloon has the color Ci and it costs Pi dollars. The gift for the Big Hippo will be any subset (chosen randomly, possibly empty) of the balloons such that the number of different colors in that subset is at least M.

    Help Little Elephant to find the expected cost of the gift.

    -----Input-----
    The first line of the input contains a single integer T - the number of test cases. T test cases follow. The first line of each test case contains a pair of integers N and M. The next N lines contain N pairs of integers Ci and Pi, one pair per line.

    -----Output-----
    In T lines print T real numbers - the answers for the corresponding test cases. Your answer will considered correct if it has at most 10^-6 absolute or relative error.

    -----Constraints-----
    - 1 ≤ T ≤ 40
    - 1 ≤ N,  Ci≤ 40
    - 1 ≤ Pi ≤ 1000000
    - 0 ≤ M ≤ K, where K is the number of different colors in the test case.

    -----Example-----
    Input:
    2
    2 2
    1 4
    2 7
    2 1
    1 4
    2 7

    Output:
    11.000000000
    7.333333333
    """


Prompt:
def minimum_cost_to_seal(T: int, test_cases: List[Tuple[int, List[Tuple[int, int]], int, List[Tuple[int, int]]]]) -> List[int]:
    """
    January and February are usually very cold in ChefLand. The temperature may reach -20 and even -30 degrees Celsius. Because of that, many people seal up windows in their houses.
    Sergey also lives in ChefLand. He wants to seal the window in his house. The window has the shape of a   simple convex polygon with N vertices.
    For the sealing, there are M kinds of sticky stripes, which are sold in the shops. The stripe of the ith type has the length of Li millimeters and the cost of Ci rubles.
    The sealing process consists in picking the stripe and sticking it on the border of the window. The stripe can't be cut (it is made of very lasting material) and can only be put straight, without foldings. It is not necessary to put the strip strictly on the window border, it can possibly extend outside the border side of window too (by any possible amount). The window is considered sealed up if every point on its' border is covered with at least one stripe.
    Now Sergey is curious about the stripes he needs to buy. He wonders about the cheapest cost, at which he can seal his window. Please help him.

    -----Input-----
    The first line of the input contains an 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 denoting the number of number of vertices in the polygon denoting Sergey's window.
    Each of the following N lines contains a pair of space-separated integer numbers Xi Yi, denoting the coordinates of the ith points.
    The following line contains a single integer M denoting the number of types of sticky stripe which is sold in the shop.
    Each of the following M lines contains a pair of space-separated integers Li Ci denoting the length and the cost of the sticky stripe of the ith type respectively.

    -----Output-----
    For each test case, output a single line containing the minimum cost of sealing up the window.

    -----Constraints-----
    - 1 ≤ T ≤ 10
    - The coordinates of the window are given either in clockwise or in a counter-clockwise order.
    - No three or more vertices lie on the same line (i.e. are collinear).
    - 0 ≤ Xi, Yi ≤ 106
    - 1 ≤ Li, Ci ≤ 106

    -----Subtasks-----
    - Subtask #1 (17 points): 3 ≤ N ≤ 10,  M = 1
    - Subtask #2 (24 points): 3 ≤ N ≤ 42, M ≤ 2
    - Subtask #3 (59 points): 3 ≤ N ≤ 2000, 1 ≤ M ≤ 10

    -----Example-----
    Input:1
    4
    0 0
    1000 0
    1000 2000
    0 2000
    2
    1000 10
    2000 15

    Output:50

    -----Explanation-----
    Example case 1. In this case, Sergey's window is a rectangle with the side lengths of 1000 and 2000. There are two types of the sticky stripes in the shop - the one of the length 1000 with the cost of 10 rubles and with the length of 2000 and the cost of 15 rubles. The optimal solution would be to buy 2 stripes of the first type 2 stripes of the second type. The cost will be 2 × 15 + 2 × 10 = 50 rubles.
    """


Prompt:
def calculate_distances(N: int, M: int, catchers: List[Tuple[int, int]], S: str) -> List[int]:
    """
    Today, puppy Tuzik is going to a new dog cinema. He has already left his home and just realised that he forgot his dog-collar! This is a real problem because the city is filled with catchers looking for stray dogs.
    A city where Tuzik lives in can be considered as an infinite grid, where each cell has exactly four neighbouring cells: those sharing a common side with the cell. Such a property of the city leads to the fact, that the distance between cells (xA, yA) and (xB, yB) equals |xA - xB| + |yA - yB|.
    Initially, the puppy started at the cell with coordinates (0, 0). There are N dog-catchers located at the cells with the coordinates (xi, yi), where 1 ≤ i ≤ N. Tuzik's path can be described as a string S of M characters, each of which belongs to the set {'D', 'U', 'L', 'R'} (corresponding to it moving down, up, left, and right, respectively). To estimate his level of safety, Tuzik wants to know the sum of the distances from each cell on his path to all the dog-catchers. You don't need to output this sum for the staring cell of the path (i.e. the cell with the coordinates (0, 0)).

    -----Input-----
    The first line of the input contains two integers N and M.
    The following N lines contain two integers xi and yi each, describing coordinates of the dog-catchers.
    The last line of the input contains string S of M characters on the set {'D', 'U', 'L', 'R'}.
    - 'D' - decrease y by 1
    - 'U' - increase y by 1
    - 'L' - decrease x by 1
    - 'R' - increase x by 1

    -----Output-----
    Output M lines: for each cell of the path (except the starting cell), output the required sum of the distances.

    -----Constraints-----
    - 1 ≤ N ≤ 3 ✕ 105
    - 1 ≤ M ≤ 3 ✕ 105
    - -106 ≤ xi, yi ≤ 106

    -----Example-----
    Input:
    2 3
    1 2
    0 1
    RDL

    Output:
    4
    6
    6

    -----Explanation-----

    Initially Tuzik stays at cell (0, 0). Let's consider his path:

    - Move 'R' to the cell (1, 0). Distance to the catcher (1, 2) equals 2, distance to the catcher (0, 1) equals 2, so the total distance equals 4
    - Move 'D' to the cell (1, -1). Distance to the catcher (1, 2) equals 3, distance to the catcher (0, 1) equals 3, so the total distance equals 6
    - Move 'L' to the cell (0, -1). Distance to the catcher (1, 2) equals 4, distance to the catcher (0, 1) equals 2, so the total distance equals 6
    """

def check(candidate):
    assert candidate(2, 3, [(1, 2), (0, 1)], 'RDL') == [4, 6, 6]
check(calculate_distances)


Prompt:
def shortest_subsequence_length(T: int, test_cases: List[Tuple[int, int, List[int]]]) -> List[int]:
    """
    You are given a sequence of n integers a1, a2, ..., an and an integer d.
    Find the length of the shortest non-empty contiguous subsequence with sum of elements at least d. Formally, you should find the smallest positive integer k with the following property: there is an integer s (1 ≤ s ≤ N-k+1) such that as + as+1 + ... + as+k-1 ≥ d.

    -----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 two space-separated integers n and d.
    - The second line contains n space-separated integers a1, a2, ..., an.

    -----Output-----
    For each test case, print a single line containing one integer — the length of the shortest contiguous subsequence with sum of elements ≥ d. If there is no such subsequence, print -1 instead.

    -----Constraints-----
    - 1 ≤ T ≤ 105
    - 1 ≤ n ≤ 105
    - -109 ≤ d ≤ 109
    - -104 ≤ ai ≤ 104
    - 1 ≤ sum of n over all test cases ≤ 2 · 105

    -----Example-----
    Input:

    2
    5 5
    1 2 3 1 -5
    5 1
    1 2 3 1 -5

    Output:

    2
    1
    """

def check(candidate):
    assert candidate(2, [(5, 5, [1, 2, 3, 1, -5]), (5, 1, [1, 2, 3, 1, -5])]) == [2, 1]
check(shortest_subsequence_length)


Prompt:
def find_path_costs(N: int, parents: List[int], values: List[int]) -> List[int]:
    """
    You are given a rooted tree on N vertices. The nodes are numbered from 1 to N, and Node 1 is the root. Each node u has an associated value attached to it: Au.
    For each vertex v, we consider the path going upwards from v to the root. Suppose that path is v1, v2, .., vk, where v1 = v and vk = 1. The cost of any node on this path is equal to the minimum value among all the nodes to its left in the path sequence, including itself. That is, cost(vi) = min1 <= j <= i{Avj}. And the cost of the path is the sum of costs of all the nodes in it.
    For every node in the tree, find the cost of the path from that node to the root.

    -----Input-----
    - The first line of the input contains a single integer, N, denoting the number of nodes in the tree.
    - The next line contains N-1 integers, the i-th of which denotes the parent of node i+1.
    - The next line contains N integers, the i-th of which denotes Ai.

    -----Output-----
    Output a single line containing N integers, the i-th of which should be the cost of the path from node i to the root.

    -----Constraints-----
    - 1 ≤ N ≤ 100,000
    - -1,000,000,000 ≤ Av ≤ 1,000,000,000

    -----Subtasks-----
    - Subtask #1 (30 points): 1 ≤ N ≤ 2000
    - Subtask #2 (70 points): Original constraints.

    -----Example-----
    Input:
    8
    1 1 1 1 5 8 6
    1 2 3 4 5 15 70 10

    Output:
    1 3 4 5 6 21 96 26

    -----Explanation-----
    For example, take a look at the path from vertex 7: The path is 7 -> 8 -> 6 -> 5 -> 1.
    Cost(7) has no choice but to be A7. So Cost(7) = 70.
    Cost(8) will be minimum of A7 and A8, which turns out to be A8. So Cost(8) = 10.
    Cost(6) = minimum {A7, A8, A6} = minimum {70, 10, 15} = 10.
    Cost(5) = minimum {70, 10, 15, 5} = 5.
    Cost(1) = minimum {70, 10, 15, 5, 1} = 1.
    So, the cost of the path from 7 to the root is 70 + 10 + 10 + 5 + 1 = 96.
    """


Prompt:
def min_lies(t: int, test_cases: List[Tuple[int, List[Tuple[str, int, str]]]]) -> List[int]:
    """
    Alice and Johnny are playing a simple guessing game. Johnny picks an arbitrary positive integer n (1<=n<=109) and gives Alice exactly k hints about the value of n. It is Alice's task to guess n, based on the received hints.

    Alice often has a serious problem guessing the value of n, and she's beginning to suspect that Johnny occasionally cheats, that is, gives her incorrect hints.
    After the last game, they had the following little conversation:

    - [Alice] Johnny, you keep cheating!

    - [Johnny] Indeed? You cannot prove it.

    - [Alice] Oh yes I can. In fact, I can tell you with the utmost certainty that in the last game you lied to me at least *** times.

    So, how many times at least did Johnny lie to Alice? Try to determine this, knowing only the hints Johnny gave to Alice.

    -----Input-----
    The first line of input contains t, the number of test cases (about 20). Exactly t test cases follow.

    Each test case starts with a line containing a single integer k, denoting the number of hints given by Johnny (1<=k<=100000). Each of the next k lines contains exactly one hint. The i-th hint is of the form:
    operator li logical_value
    where operator denotes one of the symbols < , > , or =; li is an integer (1<=li<=109), while logical_value is one of the words: Yes or No. The hint is considered correct if logical_value is the correct reply to the question: "Does the relation: n operator li hold?", and is considered to be false (a lie) otherwise.

    -----Output-----
    For each test case output a line containing a single integer, equal to the minimal possible number of Johnny's lies during the game.

    -----Example-----
    Input:
    3
    2
    < 100 No
    > 100 No
    3
    < 2 Yes
    > 4 Yes
    = 3 No
    6
    < 2 Yes
    > 1 Yes
    = 1 Yes
    = 1 Yes
    > 1 Yes
    = 1 Yes

    Output:
    0
    1
    2

    Explanation: for the respective test cases, the number picked by Johnny could have been e.g. n=100, n=5, and n=1.
    """


Prompt:
def min_string_length(T: int, test_cases: List[str]) -> List[int]:
    """
    Given a string $s$.
    You can perform the following operation on given string any number of time.
    Delete two successive elements of the string if they are same.
    After performing the above operation you have to return the least possible length of the string.

    -----Input:-----
    - First line will contain $T$, number of testcases. Then the testcases follow.
    - Each testcase contains of a single line of input, a string $s$.

    -----Output:-----
    For each testcase, output in a single line answer- minimum length of string possible after performing given operations.

    -----Constraints-----
    - $1 \leq T \leq 1000$
    - $2 \leq length of string \leq 10^5$
    $s$ contains only lowercase letters.

    -----Sample Input:-----
    3
    abccd
    abbac
    aaaa

    -----Sample Output:-----
    3
    1
    0

    -----EXPLANATION:-----
    - In first case, $"abd"$ will be final string.
    - in second case, $"c"$ will be final string
    """

def check(candidate):
    assert candidate(3, ['abccd', 'abbac', 'aaaa']) == [3, 1, 0]
check(min_string_length)

assert min_string_length(3, ['abccd', 'abbac', 'aaaa']) == [3, 1, 0]


Prompt:
def generate_tiles(T: int, cases: List[int]) -> List[str]:
    """
    Chef Tobby asked Bhuvan to brush up his knowledge of statistics for a test. While studying some distributions, Bhuvan learns the fact that for symmetric distributions, the mean and the median are always the same.
    Chef Tobby asks Bhuvan out for a game and tells him that it will utilize his new found knowledge. He lays out a total of 109 small tiles in front of Bhuvan. Each tile has a distinct number written on it from 1 to 109.
    Chef Tobby gives Bhuvan an integer N and asks him to choose N distinct tiles and arrange them in a line such that the mean of median of all subarrays lies between [N-1, N+1], both inclusive. The median of subarray of even length is the mean of the two numbers in the middle after the subarray is sorted
    Bhuvan realizes that his book didn’t teach him how to solve this and asks for your help. Can you solve the problem for him?
    In case, no solution exists, print -1.

    -----Input section-----
    First line contains, T, denoting the number of test cases.
    Each of the next T lines, contain a single integer N.

    -----Output section-----
    If no solution, exists print -1.
    If the solution exists, output N space separated integers denoting the elements of the array A such that above conditions are satisfied. In case, multiple answers exist, you can output any one them.

    -----Input constraints-----
    1 ≤ T ≤ 20
    1 ≤ N ≤ 100

    -----Sample Input-----
    3
    1
    2
    3

    -----Sample Output-----
    1
    1 2
    1 2 3

    -----Explanation-----
    For test case 3, the subarrays and their median are as follows:
    - {1}, median = 1
    - {2}, median = 2
    - {3}, median = 3
    - {1, 2}, median = 1.5
    - {2, 3}, median = 2.5
    - {1, 2, 3}, median = 2
    The mean of the medians is 2 which lies in the range [2, 4]
    """

def check(candidate):
    assert candidate(3, [1, 2, 3]) == ['1', '1 2', '1 2 3']
check(generate_tiles)


Prompt:
def shortest_average_path(T: int, test_cases: List[Tuple[int, int, List[Tuple[int, int, int]], Tuple[int, int]]]) -> List[float]:
    """
    There are a lot of problems related to the shortest paths. Nevertheless, there are not much problems, related to the shortest paths in average.
    Consider a directed graph G, consisting of N nodes and M edges. Consider a walk from the node A to the node B in this graph. The average length of this walk will be total sum of weight of its' edges divided by number of edges. Every edge counts as many times as it appears in this path.
    Now, your problem is quite simple. For the given graph and two given nodes, find out the shortest average length of the walk between these nodes. Please note, that the length of the walk need not to be finite, but average walk length will be.

    -----Input-----
    The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
    The first line of each test case contains a pair of space-separated integers N and M denoting the number of nodes and the number of edges in the graph.
    Each of the following M lines contains a triple of space-separated integers Xi Yi Zi, denoting the arc, connecting the node Xi to the node Yi (but not vice-versa!) having the weight of Zi.
    The next line contains a pair of space separated integers A and B, denoting the first and the last node of the path.

    -----Output-----
    For each test case, output a single line containing the length of the shortest path in average.
    If there is no path at all, output just -1 on the corresponding line of the output.

    -----Constraints-----
    - 1 ≤ N ≤ 500
    - 1 ≤ M ≤ 1000
    - A is not equal to B
    - 1 ≤ A, B, Xi, Yi ≤ N
    - 1 ≤ Zi ≤ 100
    - There are no self-loops and multiple edges in the graph.
    - 1 ≤ sum of N over all test cases ≤ 10000
    - 1 ≤ sum of M over all test cases ≤ 20000

    -----Subtasks-----
    - Subtask #1 (45 points): 1 ≤ N ≤ 10, 1 ≤ M ≤ 20; Your answer will be considered correct in case it has an absolute or relative error of no more than 10-2.
    - Subtask #2 (55 points): no additional constraints; Your answer will be considered correct in case it has an absolute or relative error of no more than 10-6.

    -----Example-----
    Input:2
    3 3
    1 2 1
    2 3 2
    3 2 3
    1 3
    3 3
    1 2 10
    2 3 1
    3 2 1
    1 3

    Output:1.5
    1.0

    -----Explanation-----
    Example case 1. The walk 1 -> 2 and 2 -> 3 has average length of 3/2 = 1.5. Any other walks in the graph will have more or equal average length than this.
    """


Prompt:
def check_reducible_anagrams(S: str, T: str) -> bool:
    """
    Given two strings S and T, each of which represents a non-negative rational number, return True if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
    In general a rational number can be represented using up to three parts: an integer part, a non-repeating part, and a repeating part. The number will be represented in one of the following three ways:

    <IntegerPart> (e.g. 0, 12, 123)
    <IntegerPart><.><NonRepeatingPart>  (e.g. 0.5, 1., 2.12, 2.0001)
    <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> (e.g. 0.1(6), 0.9(9), 0.00(1212))

    The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets.  For example:
    1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)
    Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6.

    Example 1:
    Input: S = "0.(52)", T = "0.5(25)"
    Output: true
    Explanation:
    Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.

    Example 2:
    Input: S = "0.1666(6)", T = "0.166(66)"
    Output: true

    Example 3:
    Input: S = "0.9(9)", T = "1."
    Output: true
    Explanation:
    "0.9(9)" represents 0.999999999... repeated forever, which equals 1.  [See this link for an explanation.]
    "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".

    Note:

    Each part consists only of digits.
    The <IntegerPart> will not begin with 2 or more zeros.  (There is no other restriction on the digits of each part.)
    1 <= <IntegerPart>.length <= 4
    0 <= <NonRepeatingPart>.length <= 4
    1 <= <RepeatingPart>.length <= 4
    """

def check(candidate):
    assert candidate("0.(52)", "0.5(25)") == True
    assert candidate("0.1666(6)", "0.166(66)") == True
    assert candidate("0.9(9)", "1.") == True
check(check_reducible_anagrams)

assert check_reducible_anagrams("0.(52)", "0.5(25)") == True

assert check_reducible_anagrams("0.1666(6)", "0.166(66)") == True

assert check_reducible_anagrams("0.9(9)", "1.") == True


Prompt:
def check_reducible_anagrams(T: int, N: List[int]) -> List[str]:
    """
    Problem description.
    Winston and Royce love sharing memes with each other. They express the amount of seconds they laughed ar a meme as the number of ‘XD’ subsequences in their messages. Being optimization freaks, they wanted to find the string with minimum possible length and having exactly the given number of ‘XD’ subsequences.

    -----Input-----
    - The first line of the input contains an integer T denoting the number of test cases.
    - Next T lines contains a single integer N, the no of seconds laughed.

    -----Output-----
    -
    For each input, print the corresponding string having minimum length. If there are multiple possible answers, print any.

    -----Constraints-----
    - 1 ≤ T ≤ 1000
    - 1 ≤ N ≤ 109
    - 1 ≤ Sum of length of output over all testcases ≤ 5*105

    -----Example-----
    Input:
    1
    9

    Output:
    XXXDDD

    -----Explanation-----
    Some of the possible strings are - XXDDDXD,XXXDDD,XDXXXDD,XDXDXDD etc. Of these, XXXDDD is the smallest.
    """

def check(candidate):
    assert candidate(1, [9]) == ['XXXDDD']
check(check_reducible_anagrams)

assert check_reducible_anagrams(1, [9]) == ['XXXDDD']


Prompt:
def min_cost(grid: List[List[int]]) -> int:
    """
    Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:

    1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
    2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
    3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
    4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])

    Notice that there could be some invalid signs on the cells of the grid which points outside the grid.
    You will initially start at the upper left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path doesn't have to be the shortest.
    You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
    Return the minimum cost to make the grid have at least one valid path.

    Example 1:

    Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
    Output: 3
    Explanation: You will start at point (0, 0).
    The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
    The total cost = 3.

    Example 2:

    Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
    Output: 0
    Explanation: You can follow the path from (0, 0) to (2, 2).

    Example 3:

    Input: grid = [[1,2],[4,3]]
    Output: 1

    Example 4:
    Input: grid = [[2,2,2],[2,2,2]]
    Output: 3

    Example 5:
    Input: grid = [[4]]
    Output: 0

    Constraints:

    m == grid.length
    n == grid[i].length
    1 <= m, n <= 100
    """


Prompt:
def find_A_from_B(T: int, test_cases: List[Tuple[int, int, int, List[List[List[int]]]]]) -> List[List[List[int]]]:
    """
    Suppose there is a X x Y x Z 3D matrix A of numbers having coordinates (i, j, k) where 0 ≤ i < X, 0 ≤ j < Y, 0 ≤ k < Z. Now another X x Y x Z matrix B is defined from A such that the (i, j, k) element of B is the sum of all the the numbers in A in the cuboid defined by the (0, 0, 0) and (i, j, k) elements as the diagonally opposite vertices. In other word (i, j, k) in B is the sum of numbers of A having coordinates (a, b, c) such that 0 ≤ a ≤ i, 0 ≤ b ≤ j, 0 ≤ c ≤ k. The problem is that given B, you have to find out A.

    -----Input-----
    The first line of input will contain the number of test cases ( ≤ 10). That many test cases will follow in subsequent lines. The first line of each test case will contain the numbers X Y Z (0 ≤ X, Y, Z ≤ 100). After that there will be X x Y lines each containing Z numbers of B. The first line contains the numbers (0, 0, 0), (0, 0, 1)..., (0, 0, Z-1). The second line has the numbers (0, 1, 0), (0, 1, 1)..., (0, 1, Z-1) and so on. The (Y+1)th line will have the numbers (1, 0, 0), (1, 0, 1)..., (1, 0, Z-1) and so on.

    -----Output-----
    For each test case print the numbers of A in exactly the same fashion as the input.

    -----Example-----
    Input:
    2
    3 1 1
    1
    8
    22
    1 2 3
    0 9 13
    18 45 51

    Output:
    1
    7
    14
    0 9 4
    18 18 2
    """


Prompt:
def game_outcome(N: int, M: int, A: List[int], games: List[Tuple[str, int, str]]) -> str:
    """
    Devu and Churu love to play games a lot. Today, they have an array A consisting of N positive integers. First they listed all N × (N+1) / 2 non-empty continuous subarrays of the array A on a piece of paper and then replaced all the subarrays on the paper with the maximum element present in the respective subarray.
    Devu and Churu decided to play a game with numbers on the paper. They both have decided to make moves turn by turn. In one turn, the player picks some number from the list and discards that number. The one who is not able to make a valid move will be the loser. To make the game more interesting, they decided to put some constraints on their moves.
    A constraint on a game can be any of following three types :
    -  > K : They are allowed to choose numbers having values strictly greater than K only.
    -  < K : They are allowed to choose numbers having values strictly less than K only.
    -  = K : They are allowed to choose numbers having values equal to K only.

    Given M constraints and who goes first, you have to tell the outcome of each game. Print 'D' if Devu wins otherwise print 'C' without quotes.
    Note that M games are independent, that is, they'll rewrite numbers by using array A after each game. (This is the task for the loser of the previous game!)

    -----Input -----
    First line of input contains two space separated integers N and M denoting the size of array A and number of game played by them. Next line of input contains N space-separated integers denoting elements of array A. Each of the next M lines of input contains three space-separated parameters describing a game. First two parameter are a character C ∈ {<, >, =} and an integer K denoting the constraint for that game. The last parameter is a character X ∈ {D, C} denoting the player who will start the game.

    ----- Output -----
    Output consists of a single line containing a string of length M made up from characters D and C only, where ith character in the string denotes the outcome of the ith game.

    ----- Constraints: -----
    - 1 ≤ N, M ≤ 106
    - 1 ≤ Ai, K ≤ 109
    - X ∈ {D, C}
    - C ∈ {<, >, =}

    -----Subtasks: -----
    - Subtask 1 : 1 ≤ N, M ≤ 104 : ( 20 pts )
    - Subtask 2 : 1 ≤ N, M ≤ 105 : ( 30 pts )
    - Subtask 3 : 1 ≤ N, M ≤ 106 : ( 50 pts )

    -----Example:-----
    Input:
    3 5
    1 2 3
    > 1 D
    < 2 C
    = 3 D
    > 4 C
    < 5 D

    Output:
    DCDDC

    -----Explanation: -----
    Subarray List :
    - [1]

    - [2]

    - [3]

    - [1,2]

    - [2,3]

    - [1,2,3]

    Numbers on the paper after replacement :

    - [1]

    - [2]

    - [3]

    - [2]

    - [3]

    - [3]

    Game 1 : There are only 5 numbers > 1 in the list.
    Game 2 : There is only 1 number < 2 in the list.
    Game 3 : There are only 3 numbers = 3 in the list.
    Game 4 : There are no numbers > 4 in the list. So the first player cannot make his move.
    Game 5 : There are 6 numbers < 5 in the list.
    """


Prompt:
def arrange_buildings(T: int, test_cases: List[Tuple[int, int]]) -> List[str]:
    """
    Problem Statement:Captain America and Iron Man are at WAR and the rage inside Iron Man is rising.

    But Iron Man faces a problem to identify the location of Captain America.

    There are N buildings situtaed adjacently to each other and Captain America can be at any building.

    Iron Man has to arrange the Buildings from 1 to N is such a way that Value(i.e abs(Building Number -Position of Building))=K for every building.

    Can You help Iron Man to Find The Arrangement of the Buildings?

    P.S- If no arrangement exist, then print
    “CAPTAIN AMERICA EVADES”.

    Input Format:
    The first line of input contains a single integer,T, denoting the number of test cases.

    Each of the T  subsequent lines contains 2 space-separated integers describing the respective N and K values for a test case.

    Output Format:
    On a new line for each test case,

    Print the lexicographically smallest arrangement;

    If no absolute arrangement exists, print “CAPTAIN AMERICA EVADES”.

    Constraints:
    SubTask#1
    1<=T<=10

    1<=N<=10^5

    0<=K<=N

    SubTask#2
    Original Constraints..

    SubTask#3
    Original Constraints..

    Sample Input:
    3

    2 1

    3 0

    3 2

    Sample Output:

    2 1

    1 2 3

    CAPTAIN AMERICA EVADES

    Explanation:
    Case 1:

    N=2 and K=1

    Therefore the arrangement is [2,1].

    Case 2:

    N=3 and K=0

    Therefore arrangement is [1,2,3].
    """

def check(candidate):
    assert candidate(3, [(2, 1), (3, 0), (3, 2)]) == ['2 1', '1 2 3', 'CAPTAIN AMERICA EVADES']
check(arrange_buildings)

assert arrange_buildings(3, [(2, 1), (3, 0), (3, 2)]) == ['2 1', '1 2 3', 'CAPTAIN AMERICA EVADES']


Prompt:
def min_cuts_sky_scrapers(n: int, heights: List[int]) -> int:
    """
    In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly decreasing but he also didn’t want to waste much money so he decided to get the minimum cuts possible. Your job is to output the minimum value of cut that is possible to arrange the skyscrapers in descending order.

    -----Input-----

    *First line of input is the number of sky-scrappers in the city
    *Second line of input is the height of the respective sky-scrappers

    -----Output-----

    * Your output should be the minimum value of cut required to arrange these sky-scrappers in descending order.

    -----Example-----
    Input:
    5
    1 2 3 4 5

    Output:
    8

    By:
    Chintan,Asad,Ashayam,Akanksha
    """

def check(candidate):
    assert candidate(5, [1, 2, 3, 4, 5]) == 8
check(min_cuts_sky_scrapers)

assert min_cuts_sky_scrapers(5, [1, 2, 3, 4, 5]) == 8


Prompt:
def earliest_arrival_time(M: int, N: int, rows: List[Tuple[str, int]], cols: List[Tuple[str, int]], start: Tuple[int, int, int], destination: Tuple[int, int]) -> int:
    """
    The city of Siruseri is impeccably planned. The city is divided into a rectangular array of cells with $M$ rows and $N$ columns. Each cell has a metro station. There is one train running left to right and back along each row, and one running top to bottom and back along each column. Each trains starts at some time $T$ and goes back and forth along its route (a row or a column) forever.
    Ordinary trains take two units of time to go from one station to the next. There are some fast trains that take only one unit of time to go from one station to the next. Finally, there are some slow trains that take three units of time to go from one station the next. You may assume that the halting time at any station is negligible.
    Here is a description of a metro system with $3$ rows and $4$ columns:
    $ $
    S(1)  F(2)  O(2)  F(4)
    F(3)    .     .     .     .
    S(2)    .     .     .     .
    O(2)    .     .     .     .

    $ $
    The label at the beginning of each row/column indicates the type of train (F for fast, O for ordinary, S for slow) and its starting time. Thus, the train that travels along row 1 is a fast train and it starts at time $3$. It starts at station ($1$, $1$) and moves right, visiting the stations along this row at times $3, 4, 5$ and $6$ respectively. It then returns back visiting the stations from right to left at times $6, 7, 8$ and $9$. It again moves right now visiting the stations at times $9, 10, 11$ and $12$, and so on. Similarly, the train along column $3$ is an ordinary train starting at time $2$. So, starting at the station ($3$,$1$), it visits the three stations on column $3$ at times $2, 4$ and $6$, returns back to the top of the column visiting them at times $6,8$ and $10$, and so on.
    Given a starting station, the starting time and a destination station, your task is to determine the earliest time at which one can reach the destination using these trains.
    For example suppose we start at station ($2$,$3$) at time $8$ and our aim is to reach the station ($1$,$1$). We may take the slow train of the second row at time $8$ and reach ($2$,$4$) at time $11$. It so happens that at time $11$, the fast train on column $4$ is at ($2$,$4$) travelling upwards, so we can take this fast train and reach ($1$,$4$) at time $12$. Once again we are lucky and at time $12$ the fast train on row $1$ is at ($1$,$4$), so we can take this fast train and reach ($1$, $1$) at time $15$. An alternative route would be to take the ordinary train on column $3$ from ($2$,$3$) at time $8$ and reach ($1$,$3$) at time $10$. We then wait there till time $13$ and take the fast train on row $1$ going left, reaching ($1$,$1$) at time $15$. You can verify that there is no way of reaching ($1$,$1$) earlier than that.

    -----Input:-----
    The first line contains two integers $M$ and $N$ indicating the number rows and columns in the metro system. This is followed by $M$ lines, lines $2, 3, …, M+1$, describing the trains along the $M$ rows. The first letter on each line is either F or O or S, indicating whether the train is a fast train, an ordinary train or a slow train. Following this, separated by a blank space, is an integer indicating the time at which this train starts running. The next $N$ lines, lines $M+2, M+3, …, N+M+1$, contain similar descriptions of the trains along the $N$ columns. The last line, line $N+M+2$, contains $5$ integers $a, b, c, d$ and $e$ where ($a$,$b$) is the starting station, $c$ is the starting time and ($d$,$e$) is the destination station.

    -----Output:-----
    A single integer indicating the earliest time at which one may reach the destination.

    -----Constraints:-----
    - $1 \leq M, N \leq 50$.
    - $1 \leq a, d \leq M$
    - $1 \leq b, e \leq N$
    - $1 \leq$ all times in input $\leq 20$

    -----Sample Input-----
    3 4
    F 3
    S 2
    O 2
    S 1
    F 2
    O 2
    F 4
    2 3 8 1 1

    -----Sample Output-----
    15
    """


Prompt:
def sum_of_digits_of_powers(T: int, numbers: List[int]) -> List[int]:
    """
    The chef won a duet singing award at Techsurge & Mridang 2012. From that time he is obsessed with the number 2.

    He just started calculating the powers of two. And adding the digits of the results.

    But he got puzzled after a few calculations. So gave you the job to generate the solutions to 2^n and find their sum of digits.

    -----Input-----
    N : number of inputs N<=100

    then N lines with input T<=2000

    -----Output-----
    The output for the corresponding input T

    -----Example-----
    Input:
    3
    5
    10
    4

    Output:
    5
    7
    7

    Explanation:
    2^5=32
    3+2=5
    2^10=1024
    1+0+2+4=7
    2^4=16
    1+6=7
    """

def check(candidate):
    assert candidate(3, [5, 10, 4]) == [5, 7, 7]
check(sum_of_digits_of_powers)

assert sum_of_digits_of_powers(3, [5, 10, 4]) == [5, 7, 7]


Prompt:
def string_game_winner(T: int, test_cases: List[str]) -> List[str]:
    """
    Abhi and his friends (Shanky,Anku and Pandey) love to play with strings. Abhi invented a simple game. He will give a string S to his friends. Shanky and Anku will play the game while Pandey is just a spectator. Shanky will traverse the string from beginning (left to right) while Anku will traverse from last (right to left). Both have to find the first character they encounter during their traversal,that appears only once in the entire string. Winner will be one whose character is alphabetically more superior(has higher ASCII value). When it is not possible to decide the winner by comparing their characters, Pandey will be the winner.

    -----Input-----
    The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.

    Each test case contains a string S having only lowercase alphabets ( a..z ).

    -----Output-----
    For each test case, output a single line containing "SHANKY" if Shanky is the winner or "ANKU" if Anku is the winner or "PANDEY" if the winner is Pandey. Output your answer without quotes.

    -----Constraints-----
    - 1 ≤ T ≤ 100
    - 1 < |S| ≤ 10^5

    -----Example-----
    Input:
    3
    google
    breakraekb
    aman

    Output:
    SHANKY
    PANDEY
    ANKU

    -----Explanation-----
    Example case 2. Both Shanky and Anku can not find any such character. Hence it is not possible to decide the winner between these two. So Pandey is the winner.
    """

def check(candidate):
    assert candidate(3, ['google', 'breakraekb', 'aman']) == ['SHANKY', 'PANDEY', 'ANKU']
check(string_game_winner)

assert string_game_winner(3, ['google', 'breakraekb', 'aman']) == ['SHANKY', 'PANDEY', 'ANKU']


Prompt:
def distribute_gifts(t: int, test_cases: List[Tuple[int, List[int], List[int]]]) -> List[Tuple[List[int], List[int]]]:
    """
    Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets:  the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are pairwise distinct (i.e. all $a_i$ are different),  the $i$-th bracelet has a brightness $b_i$, where all the $b_i$ are pairwise distinct (i.e. all $b_i$ are different).

    Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $i$-th daughter receives a necklace with brightness $x_i$ and a bracelet with brightness $y_i$, then the sums $x_i + y_i$ should be pairwise distinct. Help Kuroni to distribute the gifts.

    For example, if the brightnesses are $a = [1, 7, 5]$ and $b = [6, 1, 2]$, then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of $a_3 + b_1 = 11$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $a_1 + b_3 = 3$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $a_2 + b_2 = 8$.

    Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of $a_1 + b_1 = 7$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $a_2 + b_2 = 8$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $a_3 + b_3 = 7$.

    This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!

    -----Input-----

    The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$)  — the number of test cases. The description of the test cases follows.

    The first line of each test case contains a single integer $n$ ($1 \le n \le 100$)  — the number of daughters, necklaces and bracelets.

    The second line of each test case contains $n$ distinct integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$)  — the brightnesses of the necklaces.

    The third line of each test case contains $n$ distinct integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 1000$)  — the brightnesses of the bracelets.

    -----Output-----

    For each test case, print a line containing $n$ integers $x_1, x_2, \dots, x_n$, representing that the $i$-th daughter receives a necklace with brightness $x_i$. In the next line print $n$ integers $y_1, y_2, \dots, y_n$, representing that the $i$-th daughter receives a bracelet with brightness $y_i$.

    The sums $x_1 + y_1, x_2 + y_2, \dots, x_n + y_n$ should all be distinct. The numbers $x_1, \dots, x_n$ should be equal to the numbers $a_1, \dots, a_n$ in some order, and the numbers $y_1, \dots, y_n$ should be equal to the numbers $b_1, \dots, b_n$ in some order.

    It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.

    -----Example-----
    Input
    2
    3
    1 8 5
    8 4 5
    3
    1 7 5
    6 1 2

    Output
    1 8 5
    8 4 5
    5 1 7
    6 2 1

    -----Note-----

    In the first test case, it is enough to give the $i$-th necklace and the $i$-th bracelet to the $i$-th daughter. The corresponding sums are $1 + 8 = 9$, $8 + 4 = 12$, and $5 + 5 = 10$.

    The second test case is described in the statement.
    """


Prompt:
def subsets_parity(n: int, k: int) -> str:
    """
    # Task
    You are given integer `n` determining set S = {1, 2, ..., n}. Determine if the number of k-element subsets of S is `ODD` or `EVEN` for given integer k.

    # Example

    For `n = 3, k = 2`, the result should be `"ODD"`

    In this case, we have 3 2-element subsets of {1, 2, 3}:

    `{1, 2}, {1, 3}, {2, 3}`

    For `n = 2, k = 1`, the result should be `"EVEN"`.

    In this case, we have 2 1-element subsets of {1, 2}:

    `{1}, {2}`

    `Don't bother with naive solution - numbers here are really big.`

    # Input/Output

    - `[input]` integer `n`

    `1 <= n <= 10^9`

    - `[input]` integer `k`

    `1 <= k <= n`

    - `[output]` a string

    `"EVEN"` or `"ODD"` depending if the number of k-element subsets of S = {1, 2, ..., n} is ODD or EVEN.
    """
    return 'EVEN' if ~n & k else 'ODD'

def check(candidate):
    assert candidate(3, 2) == 'ODD'
    assert candidate(2, 1) == 'EVEN'
    assert candidate(1, 1) == 'ODD'
    assert candidate(20, 10) == 'EVEN'
    assert candidate(48, 12) == 'EVEN'
check(subsets_parity)


Prompt:
def occurrences_with_dp_and_bruteforce(t: int, test_cases: List[Tuple[int, List[int], int, int, List[int]]]) -> List[Tuple[int, int, int]]:
    """
    Problem description.

    This problem is simple and will introduce you to the Dynamic Programming.

    You will be given an array and a key value.

    You will have to find out the occurrences of the key value depending upon the query using Brute Force and Top Down Dynamic Programming.

    -----Brute-Force: -----
    You will check the query, and calculate the occurrences.

    -----DP: -----

    You will check the query; check whether the memoized solution is already available.

    If the memoized solution is available, no need to calculate the number of occurrences again.

    If the memoized solution is not available, then calculate the number of  occurrences and memoize it for future use.

    -----Pseudo Code for DP:-----
    countOccurences(key,from):

    if (from = size of array) then
    return 0
    endif
    if dp[from] is availabe then
    return dp[from]
    endif
    if( array[from] == key) then
    dp[from] = 1+countOccurences(key,from+1)
    else
    dp[from] = countOccurences(key,from+1)
    endif
    return dp[from]

    -----Input:-----

    The first line of input is the number of test cases (t).

    The first line of each test case is the number of array elements (n).

    The next will contain n space separated integers.

    The next line will have the key element (k).

    The next will have number of queries (q).

    The next q lines will contain an integer A such that 0<=A < n.

    You have to find out the number of occurrences from a to end of the array using both brute force and DP.

    Everything will fit into the range of int.

    -----Output:-----

    For each test case, the output will have q lines with 3 space separated integers.
    The first will be the number of occurrences, other will be the loop count/function calls,
    using brute force and the last will be the number of loop count/function calls using DP.

    -----Sample Input:-----
    1
    10
    1 2 3 1 2 3 1 2 3 1
    3
    5
    2
    4
    6
    8
    2

    -----Sample output:-----
    3 8 9
    2 6 1
    1 4 1
    1 2 1
    3 8 1

    -----Explanation:-----

    For the first query, we have to find the number of occurrences of 3 from index 2.

    Using the brute force, the loop will check each element from index 2 to 9. Thus the loop count is 8.

    Using DP, the method countOccurences(key,from) will be called like this :

    countOccurences(3,2)->countOccurences(3,3)->countOccurences(3,4)->countOccurences(3,5)
    ->countOccurences(3,6)->countOccurences(3,7)->countOccurences(3,8)
    ->countOccurences(3,9)->countOccurences(3,10).

    When the countOccurences(3,10) is called, it will return 0. Total 9 function calls.

    For the second query, the brute force will do the same as above.

    But the DP will check whether solution for countOccurences(3,4) is available or not.

    As it was calculated while solving the first query, it won’t solve it again and will directly give the answer.

    Total 1 function calls.
    """


Prompt:
def nth_magic_number(t: int, test_cases: List[int]) -> List[int]:
    """
    The chef was not happy with the binary number system, so he designed a new machine which is having 6 different states, i.e. in binary there is a total of 2 states as 0 and 1. Now, the chef is confused about how to correlate this machine to get an interaction with Integer numbers, when N(Integer number) is provided to the system, what will be the Nth number that system will return(in Integer form), help the chef to design this system.

    -----Input:-----
    - First-line will contain $T$, the number of test cases. Then the test cases follow.
    - Each test case contains a single line of input, $N$.

    -----Output:-----
    For each test case, output in a single line answer given by the system.

    -----Constraints-----
    - $1 \leq T \leq 10^5$
    - $1 \leq N \leq 10^5$

    -----Sample Input:-----
    2
    3
    5

    -----Sample Output:-----
    7
    37

    -----EXPLANATION:-----
    Initial numbers for system = [1, 6, 7, 36, 37, 42, 43, 216, …..
    For 1) 3rd Number for the system will be 7.
    For 2) 5th Number for the system will be 37.
    """
    results = []
    for n in test_cases:
        binary_rep = bin(n)[2:]
        magic_number = 0
        power = 1
        for digit in reversed(binary_rep):
            if digit == '1':
                magic_number += power
            power *= 6
        results.append(magic_number)
    return results

def check(candidate):
    assert candidate(2, [3, 5]) == [7, 37]
check(nth_magic_number)

assert nth_magic_number(2, [3, 5]) == [7, 37]


Prompt:
def find_zombie_lair(n: int, grid: List[List[int]]) -> Tuple[int, List[Tuple[int, int]]]:
    """
    Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of corners of the cell that are inside or on the border of the lair.

    Given this information, Heidi wants to know the exact shape of the lair to rain destruction on the zombies. Help her!

    [Image]

    -----Input-----

    The input contains multiple test cases.

    The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 500). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.

    Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).

    The last line of the file contains a zero. This line should not be treated as a test case. The sum of the N values for all tests in one file will not exceed 5000.

    -----Output-----

    For each test case, give the following output:

    The first line of the output should contain one integer V, the number of vertices of the polygon that is the secret lair. The next V lines each should contain two integers, denoting the vertices of the polygon in the clockwise order, starting from the lexicographically smallest vertex.

    -----Examples-----
    Input
    8
    00000000
    00000110
    00012210
    01234200
    02444200
    01223200
    00001100
    00000000
    5
    00000
    01210
    02420
    01210
    00000
    7
    0000000
    0122100
    0134200
    0013200
    0002200
    0001100
    0000000
    0

    Output
    4
    2 3
    2 4
    6 6
    5 2
    4
    2 2
    2 3
    3 3
    3 2
    3
    2 5
    4 5
    4 2

    -----Note-----

    It is guaranteed that the solution always exists and is unique. It is guaranteed that in the correct solution the coordinates of the polygon vertices are between 2 and N - 2. A vertex (x_1, y_1) is lexicographically smaller than vertex (x_2, y_2) if x_1 < x_2 or $x_{1} = x_{2} \wedge y_{1} < y_{2}$.
    """


Prompt:
def count_balanced_substrings(T: int, strings: List[str]) -> List[int]:
    """
    A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7.
    The Little Elephant calls some string T of the length M balanced if there exists at least one integer X (1 ≤ X ≤ M) such that the number of digits 4 in the substring T[1, X - 1] is equal to the number of digits 7 in the substring T[X, M]. For example, the string S = 7477447 is balanced since S[1, 4] = 7477 has 1 digit 4 and S[5, 7] = 447 has 1 digit 7. On the other hand, one can verify that the string S = 7 is not balanced.
    The Little Elephant has the string S of the length N. He wants to know the number of such pairs of integers (L; R) that 1 ≤ L ≤ R ≤ N and the substring S[L, R]  is balanced. Help him to find this number.
    Notes.

    Let S be some lucky string. Then

    - |S| denotes the length of the string S;

    - S[i] (1 ≤ i ≤ |S|) denotes the ith character of S (the numeration of characters starts from 1);

    -  S[L, R] (1 ≤ L ≤ R ≤ |S|) denotes the string with the following sequence of characters: S[L], S[L + 1], ..., S[R], and is called a substring of S. For L > R we mean by S[L, R] an empty string.

    -----Input-----
    The first line of the input file contains a single integer T, the number of test cases. Each of the following T lines contains one string, the string S for the corresponding test case. The input file does not contain any whitespaces.

    -----Output-----
    For each test case output a single line containing the answer for this test case.

    -----Constraints-----
    1 ≤ T ≤ 10

    1 ≤ |S| ≤ 100000

    S consists only of the lucky digits 4 and 7.

    -----Example-----
    Input:
    4
    47
    74
    477
    4747477

    Output:
    2
    2
    3
    23

    -----Explanation-----

    In the first test case balance substrings are S[1, 1] = 4 and S[1, 2] = 47.
    In the second test case balance substrings are S[2, 2] = 4 and S[1, 2] = 74.
    Unfortunately, we can't provide you with the explanations of the third and the fourth test cases. You should figure it out by yourself. Please, don't ask about this in comments.
    """

def check(candidate):
    assert candidate(4, ['47', '74', '477', '4747477']) == [2, 2, 3, 23]
check(count_balanced_substrings)


Prompt:
def find_best_friend_voting(T: int, test_cases: List[Tuple[int, List[int]]]) -> List[Union[List[int], int]]:
    """
    There are n chef's in Chefland. There is a festival in Chefland in which each chef is asked to vote a person as his best friend. Obviously, a person can't vote himself as his best friend.  Note that the best friend relationship is not necessarily bi-directional, i.e. it might be possible that x is best friend of y, but y is not a best friend of x.

    Devu was the election commissioner who conducted this voting. Unfortunately, he was sleeping during the voting time. So, he could not see the actual vote of each person, instead after the voting, he counted the number of votes of each person and found that number of votes of i-th person was equal to ci.

    Now he is wondering whether this distribution of votes corresponds to some actual voting or some fraudulent voting has happened. If the current distribution of votes does not correspond to any real voting, print -1. Otherwise, print any one of the possible voting which might have lead to the current distribution. If there are more than one possible ways of voting leading to the current distribution, you can print any one of them.

    -----Input-----
    - First line of the input contains a single integer T denoting number of test cases.
    - First line of each test case, contains a single integer n.
    - Second line of each test case, contains n space separated integers denoting array c.

    -----Output-----
    For each test case,

    - If there is no real voting corresponding to given distribution of votes, print -1 in a single line.
    - Otherwise, print n space separated integers denoting a possible voting leading to current distribution of votes. i-th integer should denote the index of the person (1 based indexing) whom i-th person has voted as his best friend.

    -----Constraints and Subtasks-----
    - 1 ≤ T ≤ 500
    - 1 ≤ n ≤ 50
    - 0 ≤ ci ≤ n

    -----Example-----
    Input:
    3
    3
    1 1 1
    3
    3 0 0
    3
    2 2 0

    Output:
    2 3 1
    -1
    -1

    -----Explanation-----
    Example 1: In this example, each person has received one vote. One possible example of real voting leading to this distribution is {2, 3, 1}. In this distribution, number of votes of all three persons are equal to 1. Also it is real voting because no person votes himself as his best friend.

    You can also output another possible distribution {3, 1, 2} too.

    Example 2: There is no real voting  corresponding to this voting distribution.

    Example 3: There is no real voting  corresponding to this voting distribution.
    """


Prompt:
def closest_farthest_values(N: int, values: List[int], edges: List[Tuple[int, int]], Q: int, queries: List[Tuple[str, int, int]]) -> List[int]:
    """
    Takaki Tono is a Computer Programmer in Tokyo. His boss at work shows him an online puzzle, which if solved would earn the solver a full expense paid trip to Los Angeles, California. Takaki really wants to solve this, as the love of his life, Akari, lives in Los Angeles and he hasn't met her since four years. Upon reading the puzzle he realizes that it is a query based problem. The problem is as follows :-

    You are given a Tree T with N nodes numbered from 1 to N, with each node numbered z having a positive integer Az written on it. This integer denotes the value of the node. You have to process Q queries, of the following forms :-
    1) C x y : Report the closest two values in the unique path from x to y i.e compute min(|Ap - Aq|) where p and q are two distinct nodes on the unique path from x to y.

    2) F x y : Report the farthest two values in the unique path from x to y i.e. compute max(|Ap - Aq|) where p and q are two distinct nodes on the unique path from x to y.

    It is also mentioned that x is not equal to y in any query and that no two nodes have the same value printed on them. Also, |x| denotes the absolute value of x.

    Takaki is perplexed and requires your help to solve this task? Can you help him out?

    -----Input-----
    The first line of the input contains an integer N denoting the number of nodes in tree T.
    The second line comprises N space separated integers denoting A, where the i-th integer denotes Ai.
    The next N-1 lines each comprise two space separated integers u and v, denoting that node u and node v
    are connected by an edge. It is guaranteed that the final graph will be a connected tree.
    The next line contains a single integer Q, denoting number of queries.
    The next Q lines comprise the queries. Each such line is of the format C x y or F x y.

    -----Output-----
    For each query, print the required output as mentioned above.

    -----Constraints-----
    - 2 ≤ N ≤ 35000
    - 1 ≤ Ai ≤ 109
    - 1 ≤ Q ≤ 35000
    - 1 ≤ u, v ≤ N
    - No two nodes have the same value printed on them.
    - x is not equal to y in any query.

    -----Subtasks-----

    -----Subtasks-----Subtask #1 (15 points)
    - N, Q ≤ 1000Subtask #2 (20 points)
    - Only Type F queries are present.Subtask #3 (65 points)
    - Original constraints

    -----Example-----
    Input:5
    1 2 7 4 5
    1 2
    2 3
    2 4
    2 5
    7
    C 1 5
    F 1 5
    C 2 4
    C 1 2
    F 1 3
    F 3 4
    F 2 4

    Output:1
    4
    2
    1
    6
    5
    2

    -----Explanation-----
    Given below is the tree corresponding to the sample input. Each node has two numbers written in it.
    The first number represents the node index and the second number indicates node value.
    """


Prompt:
def team_scores(T: int, cases: List[Tuple[int, int, List[Tuple[str, int]], List[Tuple[str, int]]]]) -> List[List[Tuple[str, int]]]:
    """
    Teacher Sungjae wanted to hold a programming competition for his students where every participant need to be included into  team. The participants submitted their team names before the deadline. After the competition ran for half an hour, (It is assured that each registered team will submit absolutely once within half an hour) Sungjae mistakenly pressed a button that changed the order of the registered team names. Now in the submission list, order of the characters in the team's name doesn't matter. That means $abc$, $acb$, $bac$, $bca$, $cab$, $cba$ refers to the same team. The competition ran for two hours and then ended. Sungjae now counting each of the team's score and wants to print the registered team names and score. The scoreboard should be ordered based on scores in decreasing order and if two teams have same score, Sangjae would follow lexicographical order.
    $N$.$B$. frequency of each character's in a registered team's name will not match with another team.
    That means two teams named $xoxo$ and $oxox$ is not possible. Because both of them have the same frequency of each of the characters (two 'o' and two 'x'). Similarly $abb$ and $bab$ is not possible (because both of them have one 'a' and two 'b').
    It is ensured that only possible test cases will be given.

    -----Input:-----Input:
    -
    First line will contain $T$, number of testcases. Then the testcases follow.
    -
    The first line of each test case contains two integers , $N$ and $R$ - total number of submissions and the number of submissions within first half an hour.
    -
    Then $R$  lines follow: the i'th line contains a string $ti$, registered names of the teams and an integer $pi$, points they got on that submission.
    -
    Then $N-R$  lines follow: the i-th line contains a string $ti$- the i-th team's name (in any order) in lowercase letter only and $pi$ -points they got on that submission.

    -----Output:-----Output:
    For each testcase,print the scoreboard.
    That means print the teams name and their point according to their score in decreasing order and if some of them have same score,print the teams name in lexicographical order

    -----Constraints-----Constraints
    - $1 \leq T \leq 10$
    - $1 \leq R \leq N \leq 1000$
    - $1 \leq ti \leq 1000$
    - $1 \leq pi \leq 10^6$
    Sum of points ($pi$) of a team will not cross $10^9$.

    -----Sample Input:-----Sample Input:
    1
    10 5
    amigoes  1
    bannermen 1
    monarchy 4
    outliers 5
    iniciador 10
    aegimos 2
    iiiacdnor 1
    eilorstu 1
    gimosae 3
    mnachroy 7

    -----Sample Output:-----Sample Output:
    iniciador 11
    monarchy 11
    amigoes 6
    outliers 6
    bannermen 1

    -----Explanation:-----Explanation:

    $It$ $is$ $assured$ $that$ $each$ $team$ $will$ $submit$ $once$ $within$ $first$ $half$ $an$ $hour$.That means -

    that kind of submissions isn't possible within first half an hour.
    Dataset can be huge. Use faster I/O method.
    """

def check(candidate):
    assert candidate(1, [(10, 5, [('amigoes', 1), ('bannermen', 1), ('monarchy', 4), ('outliers', 5), ('iniciador', 10)], [('aegimos', 2), ('iiiacdnor', 1), ('eilorstu', 1), ('gimosae', 3), ('mnachroy', 7)])]) == [['iniciador', 11], ['monarchy', 11], ['amigoes', 6], ['outliers', 6], ['bannermen', 1]]
check(team_scores)

assert team_scores(1, [(10, 5, [('amigoes', 1), ('bannermen', 1), ('monarchy', 4), ('outliers', 5), ('iniciador', 10)], [('aegimos', 2), ('iiiacdnor', 1), ('eilorstu', 1), ('gimosae', 3), ('mnachroy', 7)])]) == [['iniciador', 11], ['monarchy', 11], ['amigoes', 6], ['outliers', 6], ['bannermen', 1]]


Prompt:
def find_maximum_period(T: int, cases: List[Tuple[int, List[int]]]) -> List[Union[int, str]]:
    """
    Let's define a periodic infinite sequence S$S$ (0$0$-indexed) with period K$K$ using the formula Si=(i%K)+1$S_i = (i \% K) + 1$.
    Chef has found a sequence of positive integers A$A$ with length N$N$ buried underground. He suspects that it is a contiguous subsequence of some periodic sequence. Unfortunately, some elements of A$A$ are unreadable. Can you tell Chef the longest possible period K$K$ of an infinite periodic sequence which contains A$A$ (after suitably filling in the unreadable elements) as a contiguous subsequence?

    -----Input-----
    - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
    - The first line of each test case contains a single integer N$N$.
    - The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$. Unreadable elements are denoted by −1$-1$.

    -----Output-----
    For each test case, print a single line.
    - If the period can be arbitrarily large, this line should contain a single string "inf".
    - Otherwise, if A$A$ cannot be a contiguous subsequence of a periodic sequence, it should contain a single string "impossible".
    - Otherwise, it should contain a single integer — the maximum possible period.

    -----Constraints-----
    - 1≤T≤100$1 \le T \le 100$
    - 2≤N≤105$2 \le N \le 10^5$
    - the sum of N$N$ over all test cases does not exceed 106$10^6$
    - for each valid i$i$, 1≤Ai≤106$1 \le A_i \le 10^6$ or Ai=−1$A_i = -1$

    -----Subtasks-----
    Subtask #1 (50 points):
    - 2≤N≤1,000$2 \le N \le 1,000$
    - the sum of N$N$ over all test cases does not exceed 10,000$10,000$
    Subtask #2 (50 points): original constraints

    -----Example Input-----
    3
    3
    -1 -1 -1
    5
    1 -1 -1 4 1
    4
    4 6 7 -1

    -----Example Output-----
    inf
    4
    impossible
    """


Prompt:
def verify_logs(T: int, cases: List[Tuple[int, List[Tuple[int, int, int, int, int]]]]) -> List[str]:
    """
    You are in the future. It's the time of autonomous cars. Switching lanes is a pretty difficult task for autonomous cars, and you have the logs from an experiment you had run with two cars. You want to verify whether the logs are corrupted, or could be valid.
    In that experiment, you had a highway consisting of two lanes. These were represented by 2 rows of an infinite grid. The cell (1, 1) is the top left cell which is the starting point of the first lane. Cell (2, 1) is the bottom left cell of the grid which is the starting point of the second lane.
    There are two cars, 1 and 2 that start from the cell (1, 1) and (2, 1).
    At each instant, a car has the following choices.
    - Stay at the current position.
    - Move one cell to the right.
    - Switch Lanes. When a car switches its lane, it stays in the same column. That is, from (1, i) it could go to (2, i), or from (2, i) it could go to (1, i). But both both cars shouldn't end up at the same cell at any point. Note that there could have been a car which had moved at the very instant that you move into it.
    Consider one such scenario of driving cars.
    Time $t = 0$
    1.....
    2.....

    Time $t = 1$. Car 2 advances one cell right. Car 1 stays at the same place.
    1.....
    .2....

    Time $t = 2$. Car 2 stays at its place. Car 1 switches the lane.
    ......
    12....

    Time $t = 3$. Car 2 moves one cell to the right.  Car 1 also moves one cell to the right.
    ......
    .12...

    Time $t = 4$. Both the cars stay in the same place.
    ......
    .12...

    You are given positions of the car at $n$ instants. Your task is to check whether this situation is feasible or not.

    -----Input-----
    - The first line of the input contains an integer $T$ denoting the number of test cases. The description of the test cases follows.
    - The first line of each test case contains an integer $n$ denoting the number of instants where the positions of the cars were recorded.
    - Each of next $n$ lines contains 5 space separated integers denoting $t_i, x_i, y_i, X_i, Y_i$ denoting time, $x$ and $y$ coordinate of the first car, and that of second car.

    -----Output-----
    For each test case, output either yes or no according to the answer to the problem.

    -----Constraints-----
    - $1 \le T \le 10^5$
    - $1 \le n \leq 10^5$
    - $1 \le t_i, y_i, X_i, Y_i \leq 10^9$
    - $1 \leq x_i \leq 2$
    - $t_i < t_{i+1}$
    - Sum of $n$ over all the test cases doesn't exceed $10^6$

    -----Example Input-----
    2
    3
    1 1 1 2 2
    2 2 1 2 2
    4 2 2 2 3
    1
    1 1 3 2 2

    -----Example Output-----
    yes
    no
    """


Prompt:
def reverse_sum(N: int, cases: List[Tuple[int, int]]) -> List[int]:
    """
    A reversed arabic no is one whose digits have been written in the reversed order. However in this any trailing zeroes are omitted. The task at hand here is a simple one. You need to add two numbers which have been written in reversed arabic and return the output back in reversed arabic form, assuming no zeroes were lost while reversing.

    -----Input-----
    The input consists of N cases. The first line of the input contains only a positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers seperated by space. These are the reversednumbers you are to add.

    -----Output-----
    For each case, print exactly one line containing only one integer- the reversed sum of two reversed numbers. Omit any leading zeroes in the output.

    -----Example-----
    Input:
    1
    24 1

    Output:
    34
    """

def check(candidate):
    assert candidate(1, [(24, 1)]) == [34]
check(reverse_sum)


Prompt:
def count_valid_sequences(T: int, cases: List[int]) -> List[int]:
    """
    Shaun was given $N$ pairs of parenthesis ( )  by his teacher who gave him a difficult task.The task consists of two steps. First,Shaun should colour all $N$ pairs of parenthesis each with different color but opening and closing bracket of a particular pair should be of same colour. Then,Shaun should report to his teacher the number of ways he can arrange all $2*N$ brackets such that sequence form is valid. Teacher defined valid sequence by these rules:
    - Any left parenthesis '(' must have a corresponding right parenthesis ')'.
    - Any right parenthesis ')' must have a corresponding left parenthesis '('.
    - Left parenthesis '(' must go before the corresponding right parenthesis ')'.
    Note: Shaun could match opening and closing brackets of different colours.
    Since number of ways can be large, Shaun would report the answer as modulo 1000000007 ($10^9 + 7$).

    -----Input:-----
    - First line will contain $T$, number of testcases. Then the testcases follow.
    - Each testcase contains of a single line of input, one integer $N$.

    -----Output:-----
    For each testcase, output in a single line answer given by Shaun to his teacher modulo 1000000007.

    -----Constraints-----
    - $1 \leq T \leq 100000$
    - $1 \leq N \leq 100000$

    -----Sample Input:-----
    3
    1
    2
    3

    -----Sample Output:-----
    1
    6
    90

    -----EXPLANATION:-----
    Here numbers from $1$ to $N$ have been used to denote parenthesis.A unique number corresponds to a unique pair of parenthesis.
    -In the first test case , you can use only one color to color the parenthesis  you could arrange it only in one way i.e, 1 1
    -In the second test case  you can use two colors and the possible ways of arranging it are
    1 1 2 2
    1 2 2 1
    1 2 1 2
    2 2 1 1
    2 1 1 2
    2 1 2 1
    """

def check(candidate):
    assert candidate(3, [1, 2, 3]) == [1, 6, 90]
check(count_valid_sequences)

assert count_valid_sequences(3, [1, 2, 3]) == [1, 6, 90]


Prompt:
def find_regular_bracket_subsequence(n: int, k: int, s: str) -> str:
    """
    A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.

    Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

    You are given a regular bracket sequence $s$ and an integer number $k$. Your task is to find a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$.

    It is guaranteed that such sequence always exists.

    -----Input-----

    The first line contains two integers $n$ and $k$ ($2 \le k \le n \le 2 \cdot 10^5$, both $n$ and $k$ are even) — the length of $s$ and the length of the sequence you are asked to find.

    The second line is a string $s$ — regular bracket sequence of length $n$.

    -----Output-----

    Print a single string — a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$.

    It is guaranteed that such sequence always exists.

    -----Examples-----
    Input
    6 4
    ()(())

    Output
    ()()

    Input
    8 8
    (()(()))

    Output
    (()(()))
    """

def check(candidate):
    assert find_regular_bracket_subsequence(6, 4, "()(())") == '()()'
    assert find_regular_bracket_subsequence(8, 8, "(()(()))") == '(()(()))'
    assert find_regular_bracket_subsequence(20, 10, "((()))()((()()(())))") == '((()))()()'
    assert find_regular_bracket_subsequence(40, 30, "((((((((()()()))))))))((())((()())))(())") == '((((((((()()()))))))))(())()()'
    assert find_regular_bracket_subsequence(2, 2, "()") == '()'
check(find_regular_bracket_subsequence)


Prompt:
def open_door(n: int, x: int) -> str:
    """
    Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.

    You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n × n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:

    The sound of clashing rocks will awaken the door!

    Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:   '^': this rock moves upwards;  '<': this rock moves leftwards;  '>': this rock moves rightwards;  'v': this rock moves downwards.

    To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 10^7 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.

    If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds.

    The following picture illustrates the four possible scenarios of moving rocks.

    Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated.

    [Image]

    Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end.

    [Image]

    Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced.

    [Image]

    Does not move because the wall is in the way. No sounds are produced and the movements end.

    [Image]

    Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!

    -----Input-----

    The first line will consists of two integers n and x, denoting the size of the room and the number of sounds required to open the door. There will be exactly three test cases for this problem:

    n = 5, x = 5;  n = 3, x = 2;  n = 100, x = 10^5.

    All of these testcases are in pretest.

    -----Output-----

    Output n lines. Each line consists of n characters — the j-th character of the i-th line represents the content of the tile at the i-th row and the j-th column, and should be one of these:

    '^', '<', '>', or 'v': a rock as described in the problem statement.  '.': an empty tile.

    Then, output two integers r and c (1 ≤ r, c ≤ n) on the next line — this means that the rock you activate first is located at the r-th row from above and c-th column from the left. There must be a rock in this cell.

    If there are multiple solutions, you may output any of them.

    -----Examples-----
    Input
    5 5

    Output
    >...v
    v.<..
    ..^..
    >....
    ..^.<
    1 1

    Input
    3 2

    Output
    >vv
    ^<.
    ^.<
    1 3

    -----Note-----

    Here's a simulation of the first example, accompanied with the number of sounds produced so far.

    $8$ 0 sound

    [Image] 1 sound

    $8$ 2 sounds

    $8$ 3 sounds

    $8$ 4 sounds

    $8$ still 4 sounds

    In the picture above, the activated rock switches between the '^' rock and the '<' rock. However, no sound is produced since the '^' rock didn't move even a single tile. So, still 4 sound.

    [Image] 5 sounds

    At this point, 5 sound are already produced, so this solution is already correct. However, for the sake of example, we will continue simulating what happens.

    [Image] 6 sounds

    [Image] 7 sounds

    [Image] still 7 sounds

    [Image] 8 sounds

    And the movement stops. In total, it produces 8 sounds. Notice that the last move produced sound.

    Here's a simulation of the second example:

    [Image] 0 sound

    [Image] 1 sound

    [Image] 2 sounds

    Now, the activated stone will switch continuously from one to another without producing a sound until it reaches the 10^7 limit, after which the movement will cease.

    [Image]

    In total, it produced exactly 2 sounds, so the solution is correct.
    """

def check(candidate):
    assert candidate(5, 5) == '>...v\nv.<..\n..^..\n>....\n..^.<\n1 1'
    assert candidate(3, 2) == '>vv\n^<.\n^.<\n1 3'
check(open_door)


Prompt:
def restore_array(n: int, b: List[int]) -> Union[str, Tuple[str, List[int]]]:
    """
    While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers $a_1, a_2, \ldots, a_n$. Since the talk was long and not promising, Kostya created a new cyclic array $b_1, b_2, \ldots, b_{n}$ so that $b_i = (a_i \mod a_{i + 1})$, where we take $a_{n+1} = a_1$. Here $mod$ is the modulo operation. When the talk became interesting, Kostya completely forgot how array $a$ had looked like. Suddenly, he thought that restoring array $a$ from array $b$ would be an interesting problem (unfortunately, not A).

    -----Input-----

    The first line contains a single integer $n$ ($2 \le n \le 140582$) — the length of the array $a$.

    The second line contains $n$ integers $b_1, b_2, \ldots, b_{n}$ ($0 \le b_i \le 187126$).

    -----Output-----

    If it is possible to restore some array $a$ of length $n$ so that $b_i = a_i \mod a_{(i \mod n) + 1}$ holds for all $i = 1, 2, \ldots, n$, print «YES» in the first line and the integers $a_1, a_2, \ldots, a_n$ in the second line. All $a_i$ should satisfy $1 \le a_i \le 10^{18}$. We can show that if an answer exists, then an answer with such constraint exists as well.

    It it impossible to restore any valid $a$, print «NO» in one line.

    You can print each letter in any case (upper or lower).

    -----Examples-----
    Input
    4
    1 3 1 0

    Output
    YES
    1 3 5 2

    Input
    2
    4 4

    Output
    NO

    -----Note-----

    In the first example:  $1 \mod 3 = 1$  $3 \mod 5 = 3$  $5 \mod 2 = 1$  $2 \mod 1 = 0$
    """