question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Your task is to write a program which reads a date (from 2004/1/1 to 2004/12/31) and prints the day of the date. Jan. 1, 2004, is Thursday. Note that 2004 is a leap year and we have Feb. 29. Input The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset consists of two integers m and d separated by a single space in a line. These integers respectively represent the month and the day. The number of datasets is less than or equal to 50. Output For each dataset, print the day (please see the following words) in a line. Monday Tuesday Wednesday Thursday Friday Saturday Sunday Example Input 1 1 2 29 0 0 Output Thursday Sunday Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≤ l ≤ r ≤ 109) — the left and right interval limits. Output In the single line print the only number — the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 7 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A: Alphabet block Wakana Nakawa loves palindromes. Because my name is also a palindrome. Wakana got a set with some alphabet blocks. An alphabet block is a block in which one lowercase alphabet is written for each block, and you can create your favorite character string by changing the order of the blocks and combining them. Wakana is wondering if she can make a palindrome with this set. The following three types of operations are possible in the set of alphabet blocks, and the cost of each operation is 1. 1. Add one alphabet block (any letter is listed) 2. Change one alphabet block you have to another block (whatever the letters are listed) 3. Delete one alphabet block you currently have I want to make a set that can be rearranged into palindromes by operating the set of alphabet blocks several times. What is the minimum cost of such an operation? Let's think with Wakana-chan. Input The input consists of one line of the string S that points to the information in the first set of alphabet blocks. S consists of lowercase letters only and satisfies 1 \ leq | S | \ leq 10 ^ 3. Output Output the minimum cost for creating a palindrome. Don't forget the newline at the end. Sample Input 1 hcpc Sample Output 1 1 In this case, a palindrome can be created at a cost of 1, but multiple methods are possible. For example, if you add a block of'h', you can make a'hcpch', so you can make a palindrome at a cost of 1. Also, if you delete the block of'h', you can make'cpc', so you can make a palindrome with this method at cost 1. Sample Input 2 ritscamp Sample Output 2 Four Sample Input 3 nakawawakana Sample Output 3 0 If you can create a palindrome from scratch, the cost is zero. Example Input hcpc Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ## The story you are about to hear is true Our cat, Balor, sadly died of cancer in 2015. While he was alive, the three neighborhood cats Lou, Mustache Cat, and Raoul all recognized our house and yard as Balor's territory, and would behave respectfully towards him and each other when they would visit. But after Balor died, gradually each of these three neighborhood cats began trying to claim his territory as their own, trying to drive the others away by growling, yowling, snarling, chasing, and even fighting, when one came too close to another, and no human was right there to distract or extract one of them before the situation could escalate. It is sad that these otherwise-affectionate animals, who had spent many afternoons peacefully sitting and/or lying near Balor and each other on our deck or around our yard, would turn on each other like that. However, sometimes, if they are far enough away from each other, especially on a warm day when all they really want to do is pick a spot in the sun and lie in it, they will ignore each other, and once again there will be a Peaceable Kingdom. ## Your Mission In this, the first and simplest of a planned trilogy of cat katas :-), all you have to do is determine whether the distances between any visiting cats are large enough to make for a peaceful afternoon, or whether there is about to be an altercation someone will need to deal with by carrying one of them into the house or squirting them with water or what have you. As input your function will receive a list of strings representing the yard as a grid, and an integer representing the minimum distance needed to prevent problems (considering the cats' current states of sleepiness). A point with no cat in it will be represented by a "-" dash. Lou, Mustache Cat, and Raoul will be represented by an upper case L, M, and R respectively. At any particular time all three cats may be in the yard, or maybe two, one, or even none. If the number of cats in the yard is one or none, or if the distances between all cats are at least the minimum distance, your function should return True/true/TRUE (depending on what language you're using), but if there are two or three cats, and the distance between at least two of them is smaller than the minimum distance, your function should return False/false/FALSE. ## Some examples (The yard will be larger in the random test cases, but a smaller yard is easier to see and fit into the instructions here.) In this first example, there is only one cat, so your function should return True. ``` ["------------", "------------", "-L----------", "------------", "------------", "------------"], 10 ``` In this second example, Mustache Cat is at the point yard[1][3] and Raoul is at the point yard[4][7] -- a distance of 5, so because the distance between these two points is smaller than the specified minimum distance of 6, there will be trouble, and your function should return False. ``` ["------------", "---M--------", "------------", "------------", "-------R----", "------------"], 6 ``` In this third example, Lou is at yard[0][11], Raoul is at yard[1][2], and Mustache Cat at yard[5][2]. The distance between Lou and Raoul is 9.05538513814, the distance between Raoul and Mustache Cat is 4, and the distance between Mustache Cat and Lou is 10.295630141 -- all greater than or equal to the specified minimum distance of 4, so the three cats will nap peacefully, and your function should return True. ``` ["-----------L", "--R---------", "------------", "------------", "------------", "--M---------"], 4 ``` Have fun! Write your solution by modifying this code: ```python def peaceful_yard(yard, min_distance): ``` Your solution should implemented in the function "peaceful_yard". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Word $s$ of length $n$ is called $k$-complete if $s$ is a palindrome, i.e. $s_i=s_{n+1-i}$ for all $1 \le i \le n$; $s$ has a period of $k$, i.e. $s_i=s_{k+i}$ for all $1 \le i \le n-k$. For example, "abaaba" is a $3$-complete word, while "abccba" is not. Bob is given a word $s$ of length $n$ consisting of only lowercase Latin letters and an integer $k$, such that $n$ is divisible by $k$. He wants to convert $s$ to any $k$-complete word. To do this Bob can choose some $i$ ($1 \le i \le n$) and replace the letter at position $i$ with some other lowercase Latin letter. So now Bob wants to know the minimum number of letters he has to replace to convert $s$ to any $k$-complete word. Note that Bob can do zero changes if the word $s$ is already $k$-complete. You are required to answer $t$ test cases independently. -----Input----- The first line contains a single integer $t$ ($1 \le t\le 10^5$) — the number of test cases. The first line of each test case contains two integers $n$ and $k$ ($1 \le k < n \le 2 \cdot 10^5$, $n$ is divisible by $k$). The second line of each test case contains a word $s$ of length $n$. It is guaranteed that word $s$ only contains lowercase Latin letters. And it is guaranteed that the sum of $n$ over all test cases will not exceed $2 \cdot 10^5$. -----Output----- For each test case, output one integer, representing the minimum number of characters he has to replace to convert $s$ to any $k$-complete word. -----Example----- Input 4 6 2 abaaba 6 3 abaaba 36 9 hippopotomonstrosesquippedaliophobia 21 7 wudixiaoxingxingheclp Output 2 0 23 16 -----Note----- In the first test case, one optimal solution is aaaaaa. In the second test case, the given word itself is $k$-complete. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. There are N students living in the dormitory of Berland State University. Each of them sometimes wants to use the kitchen, so the head of the dormitory came up with a timetable for kitchen's usage in order to avoid the conflicts: The first student starts to use the kitchen at the time 0 and should finish the cooking not later than at the time A_{1}. The second student starts to use the kitchen at the time A_{1} and should finish the cooking not later than at the time A_{2}. And so on. The N-th student starts to use the kitchen at the time A_{N-1} and should finish the cooking not later than at the time A_{N} The holidays in Berland are approaching, so today each of these N students wants to cook some pancakes. The i-th student needs B_{i} units of time to cook. The students have understood that probably not all of them will be able to cook everything they want. How many students will be able to cook without violating the schedule? ------ Input Format ------ 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 3 lines of input - The first line of each test case contains a single integer N denoting the number of students. - The second line contains N space-separated integers A1, A2, ..., AN denoting the moments of time by when the corresponding student should finish cooking. - The third line contains N space-separated integers B1, B2, ..., BN denoting the time required for each of the students to cook. ------ Output Format ------ For each test case, output a single line containing the number of students that will be able to finish the cooking. ------ Constraints ------ 1 ≤ T ≤ 10 \ 1 ≤ N ≤ 104 \ 0 A1 A2 AN 109 \ 1 ≤ Bi ≤ 109 ----- Sample Input 1 ------ 2 3 1 10 15 1 10 3 3 10 20 30 15 5 20 ----- Sample Output 1 ------ 2 1 ----- explanation 1 ------ Example case 1. The first student has 1 unit of time - the moment 0. It will be enough for her to cook. The second student has 9 units of time, but wants to cook for 10 units of time, and won't fit in time. The third student has 5 units of time and will fit in time, because needs to cook only for 3 units of time. Example case 2. Each of students has 10 units of time, but only the second one will be able to fit in time. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are N children, numbered 1, 2, ..., N. Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets. For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy children by optimally distributing the sweets. Find the maximum possible number of happy children. Constraints * All values in input are integers. * 2 \leq N \leq 100 * 1 \leq x \leq 10^9 * 1 \leq a_i \leq 10^9 Input Input is given from Standard Input in the following format: N x a_1 a_2 ... a_N Output Print the maximum possible number of happy children. Examples Input 3 70 20 30 10 Output 2 Input 3 10 20 30 10 Output 1 Input 4 1111 1 10 100 1000 Output 4 Input 2 10 20 20 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Each day in Berland consists of $n$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $a_1, a_2, \dots, a_n$ (each $a_i$ is either $0$ or $1$), where $a_i=0$ if Polycarp works during the $i$-th hour of the day and $a_i=1$ if Polycarp rests during the $i$-th hour of the day. Days go one after another endlessly and Polycarp uses the same schedule for each day. What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day. -----Input----- The first line contains $n$ ($1 \le n \le 2\cdot10^5$) — number of hours per day. The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 1$), where $a_i=0$ if the $i$-th hour in a day is working and $a_i=1$ if the $i$-th hour is resting. It is guaranteed that $a_i=0$ for at least one $i$. -----Output----- Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day. -----Examples----- Input 5 1 0 1 0 1 Output 2 Input 6 0 1 0 1 1 0 Output 2 Input 7 1 0 1 1 1 0 1 Output 3 Input 3 0 0 0 Output 0 -----Note----- In the first example, the maximal rest starts in last hour and goes to the first hour of the next day. In the second example, Polycarp has maximal rest from the $4$-th to the $5$-th hour. In the third example, Polycarp has maximal rest from the $3$-rd to the $5$-th hour. In the fourth example, Polycarp has no rest at all. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A prime number is an integer that is greater than 1 and can only be divided by itself or 1. For example, 2 is a prime number because it is divisible only by 2 and 1, but 12 is not a prime number because it is divisible by 2, 3, 4, 6 in addition to 12 and 1. When you enter the integer n, write a program that outputs the largest prime number less than n and the smallest prime number greater than n. Input Given multiple datasets. Each dataset is given n (3 ≤ n ≤ 50,000) on one row. The number of datasets does not exceed 50. Output For each dataset, output the largest prime number less than n and the smallest prime number greater than n on one line, separated by a space. Example Input 19 3517 Output 17 23 3511 3527 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this Kata you must convert integers numbers from and to a negative-base binary system. Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this advantage is countered by an increased complexity of arithmetic operations. To help understand, the first eight digits (in decimal) of the Base(-2) system is: `[1, -2, 4, -8, 16, -32, 64, -128]` Example conversions: `Decimal, negabinary` ``` 6, '11010' -6, '1110' 4, '100' 18, '10110' -11, '110101' ``` Write your solution by modifying this code: ```python def int_to_negabinary(i): ``` Your solution should implemented in the function "int_to_negabinary". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. Write your solution by modifying this code: ```python def add_binary(a,b): ``` Your solution should implemented in the function "add_binary". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given a string `s` of uppercase letters, your task is to determine how many strings `t` (also uppercase) with length equal to that of `s` satisfy the followng conditions: * `t` is lexicographical larger than `s`, and * when you write both `s` and `t` in reverse order, `t` is still lexicographical larger than `s`. ```Haskell For example: solve('XYZ') = 5. They are: YYZ, ZYZ, XZZ, YZZ, ZZZ ``` String lengths are less than `5000`. Return you answer `modulo 10^9+7 (= 1000000007)`. More examples in test cases. Good luck! Write your solution by modifying this code: ```python def solve(s): ``` Your solution should implemented in the function "solve". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. One day alice and bob were playing with their old toys , they had moved all the rakes and drawers to in the pursuit of their childhood toys. Finally they found bunch of cubes ,with letters and digits written on it ,which they recalled they used to make words from. They have already come up with a word they would like to make. Could you help him by saying if the word can be built from the cubes in the drawer? Input On the first line of input there is a string S, consisting of lowercase English letters, and an integer N (4≤|S|≤100, 1≤N≤100) – the word Bob and Alice wants to build and the number of cubes. On the every of the following N lines there are 6 characters. Every of those characters is either a lowercase English letter or a digit. It is guaranteed that the string S consists only of lowercase English letters. Output Output one word, either "YES", if the word can be built using given cubes, or "NO" otherwise. SAMPLE TEST CASE INPUT egos 4 d 1 w e 7 9 o 2 h a v e g 3 c o o k s 3 i e s 5 OUTPUT YES SAMPLE INPUT egos 4 d 1 w e 7 9 o 2 h a v e g 3 c o o k s 3 i e s 5 SAMPLE OUTPUT YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sort array by last character Complete the function to sort a given array or list by last character of elements. ```if-not:haskell Element can be an integer or a string. ``` ### Example: ``` ['acvd', 'bcc'] --> ['bcc', 'acvd'] ``` The last characters of the strings are `d` and `c`. As `c` comes before `d`, sorting by last character will give `['bcc', 'acvd']`. If two elements don't differ in the last character, then they should be sorted by the order they come in the array. ```if:haskell Elements will not be empty (but the list may be). ``` Write your solution by modifying this code: ```python def sort_me(arr): ``` Your solution should implemented in the function "sort_me". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either + or -. Your task is to evaluate the formula instead of her. -----Constraints----- - 1≦A,B≦10^9 - op is either + or -. -----Input----- The input is given from Standard Input in the following format: A op B -----Output----- Evaluate the formula and print the result. -----Sample Input----- 1 + 2 -----Sample Output----- 3 Since 1 + 2 = 3, the output should be 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array of `n+1` integers `1` through `n`. In addition there is a single duplicate integer. The array is unsorted. An example valid array would be `[3, 2, 5, 1, 3, 4]`. It has the integers `1` through `5` and `3` is duplicated. `[1, 2, 4, 5, 5]` would not be valid as it is missing `3`. You should return the duplicate value as a single integer. Write your solution by modifying this code: ```python def find_dup(arr): ``` Your solution should implemented in the function "find_dup". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are N rabbits on a number line. The rabbits are conveniently numbered 1 through N. The coordinate of the initial position of rabbit i is x_i. The rabbits will now take exercise on the number line, by performing sets described below. A set consists of M jumps. The j-th jump of a set is performed by rabbit a_j (2≤a_j≤N-1). For this jump, either rabbit a_j-1 or rabbit a_j+1 is chosen with equal probability (let the chosen rabbit be rabbit x), then rabbit a_j will jump to the symmetric point of its current position with respect to rabbit x. The rabbits will perform K sets in succession. For each rabbit, find the expected value of the coordinate of its eventual position after K sets are performed. Constraints * 3≤N≤10^5 * x_i is an integer. * |x_i|≤10^9 * 1≤M≤10^5 * 2≤a_j≤N-1 * 1≤K≤10^{18} Input The input is given from Standard Input in the following format: N x_1 x_2 ... x_N M K a_1 a_2 ... a_M Output Print N lines. The i-th line should contain the expected value of the coordinate of the eventual position of rabbit i after K sets are performed. The output is considered correct if the absolute or relative error is at most 10^{-9}. Examples Input 3 -1 0 2 1 1 2 Output -1.0 1.0 2.0 Input 3 1 -1 1 2 2 2 2 Output 1.0 -1.0 1.0 Input 5 0 1 3 6 10 3 10 2 3 4 Output 0.0 3.0 7.0 8.0 10.0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You receive some random elements as a space-delimited string. Check if the elements are part of an ascending sequence of integers starting with 1, with an increment of 1 (e.g. 1, 2, 3, 4). Return: * `0` if the elements can form such a sequence, and no number is missing ("not broken", e.g. `"1 2 4 3"`) * `1` if there are any non-numeric elements in the input ("invalid", e.g. `"1 2 a"`) * `n` if the elements are part of such a sequence, but some numbers are missing, and `n` is the lowest of them ("broken", e.g. `"1 2 4"` or `"1 5"`) ## Examples ``` "1 2 3 4" ==> return 0, because the sequence is complete "1 2 4 3" ==> return 0, because the sequence is complete (order doesn't matter) "2 1 3 a" ==> return 1, because it contains a non numerical character "1 3 2 5" ==> return 4, because 4 is missing from the sequence "1 5" ==> return 2, because the sequence is missing 2, 3, 4 and 2 is the lowest ``` Write your solution by modifying this code: ```python def find_missing_number(sequence): ``` Your solution should implemented in the function "find_missing_number". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split! Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space). The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXT SENTENCE ::= WORD SPACE SENTENCE | WORD END END ::= {'.', '?', '!'} WORD ::= LETTER | LETTER WORD LETTER ::= {'a'..'z', 'A'..'Z'} SPACE ::= ' ' SPACE stands for the symbol of a space. So, how many messages did Fangy send? Input The first line contains an integer n, which is the size of one message (2 ≤ n ≤ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty. Output On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes. Examples Input 25 Hello. I am a little walrus. Output 2 Input 2 How are you? Output Impossible Input 19 Hello! Do you like fish? Why? Output 3 Note Let's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: * Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below. * During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. 1. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. 2. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times. Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. Input The first line contains two integers n and k (1 ≤ n, k ≤ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≤ qi ≤ n) — the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format. It is guaranteed that the given sequences q and s are correct permutations. Output If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes). Examples Input 4 1 2 3 4 1 1 2 3 4 Output NO Input 4 1 4 3 1 2 3 4 2 1 Output YES Input 4 3 4 3 1 2 3 4 2 1 Output YES Input 4 2 4 3 1 2 2 1 4 3 Output YES Input 4 1 4 3 1 2 2 1 4 3 Output NO Note In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed. In the second sample the described situation is possible, in case if after we toss a coin, we get tails. In the third sample the possible coin tossing sequence is: heads-tails-tails. In the fourth sample the possible coin tossing sequence is: heads-heads. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's denote correct match equation (we will denote it as CME) an equation $a + b = c$ there all integers $a$, $b$ and $c$ are greater than zero. For example, equations $2 + 2 = 4$ (||+||=||||) and $1 + 2 = 3$ (|+||=|||) are CME but equations $1 + 2 = 4$ (|+||=||||), $2 + 2 = 3$ (||+||=|||), and $0 + 1 = 1$ (+|=|) are not. Now, you have $n$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME! For example, if $n = 2$, you can buy two matches and assemble |+|=||, and if $n = 5$ you can buy one match and assemble ||+|=|||. [Image] Calculate the minimum number of matches which you have to buy for assembling CME. Note, that you have to answer $q$ independent queries. -----Input----- The first line contains one integer $q$ ($1 \le q \le 100$) — the number of queries. The only line of each query contains one integer $n$ ($2 \le n \le 10^9$) — the number of matches. -----Output----- For each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME. -----Example----- Input 4 2 5 8 11 Output 2 1 0 1 -----Note----- The first and second queries are explained in the statement. In the third query, you can assemble $1 + 3 = 4$ (|+|||=||||) without buying matches. In the fourth query, buy one match and assemble $2 + 4 = 6$ (||+||||=||||||). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the hard version of this problem. The only difference is the constraint on $k$ — the number of gifts in the offer. In this version: $2 \le k \le n$. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$k$ of goods for the price of one" is held in store. Using this offer, Vasya can buy exactly $k$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has. More formally, for each good, its price is determined by $a_i$ — the number of coins it costs. Initially, Vasya has $p$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index $i$ if he currently has enough coins (i.e $p \ge a_i$). After buying this good, the number of Vasya's coins will decrease by $a_i$, (i.e it becomes $p := p - a_i$). Vasya can buy a good with the index $i$, and also choose exactly $k-1$ goods, the price of which does not exceed $a_i$, if he currently has enough coins (i.e $p \ge a_i$). Thus, he buys all these $k$ goods, and his number of coins decreases by $a_i$ (i.e it becomes $p := p - a_i$). Please note that each good can be bought no more than once. For example, if the store now has $n=5$ goods worth $a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$, respectively, $k=2$, and Vasya has $6$ coins, then he can buy $3$ goods. A good with the index $1$ will be bought by Vasya without using the offer and he will pay $2$ coins. Goods with the indices $2$ and $3$ Vasya will buy using the offer and he will pay $4$ coins. It can be proved that Vasya can not buy more goods with six coins. Help Vasya to find out the maximum number of goods he can buy. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the test. The next lines contain a description of $t$ test cases. The first line of each test case contains three integers $n, p, k$ ($2 \le n \le 2 \cdot 10^5$, $1 \le p \le 2\cdot10^9$, $2 \le k \le n$) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $n$ integers $a_i$ ($1 \le a_i \le 10^4$) — the prices of goods. It is guaranteed that the sum of $n$ for all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case in a separate line print one integer $m$ — the maximum number of goods that Vasya can buy. -----Example----- Input 8 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 3 2 3 4 2 6 5 2 3 10 1 3 9 2 2 10000 2 10000 10000 2 9999 2 10000 10000 4 6 4 3 2 3 2 5 5 3 1 2 2 1 2 Output 3 4 1 1 2 0 4 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i. Constraints * 1 ≤ length of T ≤ 1000000 * 1 ≤ length of P_i ≤ 1000 * 1 ≤ Q ≤ 10000 * The input consists of alphabetical characters and digits Input In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively. Output For each question, print 1 if the text includes P_i, or print 0 otherwise. Example Input aabaaa 4 aa ba bb xyz Output 1 1 0 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased. eg: foobar == fooBAR If it is an odd number then 'round' it up to find which letters to uppercase. See example below. sillycase("brian") // --^-- midpoint // bri first half (lower-cased) // AN second half (upper-cased) Write your solution by modifying this code: ```python def sillycase(silly): ``` Your solution should implemented in the function "sillycase". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently, chef Ciel often hears about lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Ciel decides to make Ciel numbers. As you know, Ciel likes the digit 8 very much. And then, Ciel likes the digits 5 and 3. So Ciel defines Ciel numbers as the positive integers k such that d(k, 8) ≥ d(k, 5) ≥ d(k, 3) and d(k, i) = 0 for all i = 0, 1, 2, 4, 6, 7, 9, where d(k, i) denotes the number of the digit i in the decimal representation of the integer k. For example, the first few Ciel numbers are 8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888, .... Ciel's restaurant has N menus. And Ciel want to know how many menus have Ciel numbers as their price. Your task is to find it. ------ Input ------ The first line contains an integer N. Then N lines follow. Each line has the name S_{i} of the menu and its price P_{i} separated by a single space. ------ Output ------ Print the number of menus whose prices are one of Ciel numbers. ------ Constraints ------ 1 ≤ N ≤ 1000 1 ≤ |S_{i}| ≤ 100, where |S_{i}| denotes the length of S_{i} Each letter of S_{i} is either an alphabetical letter or a digit or a single quotation mark or a space. 1 ≤ P_{i} < 1000000 (10^{6}) P_{i} contains no leading zeros. ------ Notes ------ Different operating systems have different ways of representing a newline; do not assume one particular way will be used. ----- Sample Input 1 ------ 6 milk 58 Ciel's Drink 80 The curry 2nd edition 888888 rice omelet 85855 unagi 1 The first and last letters can be a space 358 ----- Sample Output 1 ------ 3 ----- explanation 1 ------ 58 and 888888 and 358 are Ciel numbers. 80 and 85855 and 1 are not Ciel numbers. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help. The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence. Input The first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value. Output Output one integer — minimum number of steps required to achieve the goal. Examples Input 5 3 2 -1 2 11 Output 4 Input 5 2 1 1 1 1 Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place: * A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars. * Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally. Input The first input line contains number n (1 ≤ n ≤ 5000) — amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≤ x ≤ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≤ x ≤ 2000). Output Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time. Examples Input 7 win 10 win 5 win 3 sell 5 sell 3 win 10 sell 10 Output 1056 Input 3 win 5 sell 6 sell 4 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability <image>. Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times. Input A single line contains two integers m and n (1 ≤ m, n ≤ 105). Output Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. Examples Input 6 1 Output 3.500000000000 Input 6 3 Output 4.958333333333 Input 2 2 Output 1.750000000000 Note Consider the third test example. If you've made two tosses: 1. You can get 1 in the first toss, and 2 in the second. Maximum equals to 2. 2. You can get 1 in the first toss, and 1 in the second. Maximum equals to 1. 3. You can get 2 in the first toss, and 1 in the second. Maximum equals to 2. 4. You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: <image> You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21). The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (integer). ~~~if:c Note: in C the function receives a character array with the card `10` represented by the character `T`. ~~~ ### Scoring rules: Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11. Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21. ## Examples ``` ["A"] ==> 11 ["A", "J"] ==> 21 ["A", "10", "A"] ==> 12 ["5", "3", "7"] ==> 15 ["5", "4", "3", "2", "A", "K"] ==> 25 ``` Write your solution by modifying this code: ```python def score_hand(cards): ``` Your solution should implemented in the function "score_hand". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Little Elephant from the Zoo of Lviv likes listening to music. There are N songs, numbered from 1 to N, in his MP3-player. The song i is described by a pair of integers B_{i} and L_{i} - the band (represented as integer) that performed that song and the length of that song in seconds. The Little Elephant is going to listen all the songs exactly once in some order. The sweetness of the song is equal to the product of the length of that song and the number of different bands listened before (including the current playing song). Help the Little Elephant to find the order that maximizes the total sweetness of all N songs. Print that sweetness. ------ Input ------ The first line of the input contains single integer T, denoting the number of test cases. Then T test cases follow. The first line of each test case contains single integer N, denoting the number of the songs. The next N lines describe the songs in the MP3-player. The i-th line contains two space-sparated integers B_{i} and L_{i}. ------ Output ------ For each test, output the maximum total sweetness. ------ Constraints ------ $1 ≤ T ≤ 5$ $1 ≤ N ≤ 100000 (10^{5})$ $1 ≤ B_{i}, L_{i} ≤ 1000000000 (10^{9})$ ----- Sample Input 1 ------ 2 3 1 2 2 2 3 2 3 2 3 1 2 2 4 ----- Sample Output 1 ------ 12 16 ----- explanation 1 ------ In the first sample: if he listens the songs in given order, thenB1=1, L1=2: the sweetness = 2 * 1 = 2B2=2, L2=2: the sweetness = 2 * 2 = 4B3=3, L3=2: the sweetness = 2 * 3 = 6So the total sweetness is 12. In this case, you can check the total sweetness does not depend on the order of the songs. In the second sample: if he listens the songs in given order, thenB1=2, L1=3: the sweetness = 3 * 1 = 3B2=1, L2=2: the sweetness = 2 * 2 = 4B3=2, L3=4: the sweetness = 4 * 2 = 8So the total sweetness is 15. However, he listens the song 2 firstly, thenB2=1, L2=2: the sweetness = 2 * 1 = 2B1=2, L1=3: the sweetness = 3 * 2 = 6B3=2, L3=4: the sweetness = 4 * 2 = 8So the total sweetness is 16, and it is the maximum total sweetness. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following: function rangeIncrement(l, r) for i := l .. r do a[i] = a[i] + 1 Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105. Before calls of function rangeIncrement(l, r) all array elements equal zero. Input The first input line contains a single integer n (1 ≤ n ≤ 105) — the length of the array a[1... n]. The second line contains its integer space-separated elements, a[1], a[2], ..., a[n] (0 ≤ a[i] ≤ 105) after some series of function calls rangeIncrement(l, r). It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r). Output Print on the first line t — the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105. Then print t lines — the descriptions of function calls, one per line. Each line should contain two integers li, ri (1 ≤ li ≤ ri ≤ n) — the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order. If there are multiple solutions, you are allowed to print any of them. Examples Input 6 1 2 1 1 4 1 Output 5 2 2 5 5 5 5 5 5 1 6 Input 5 1 0 1 0 1 Output 3 1 1 3 3 5 5 Note The first sample requires a call for the entire array, and four additional calls: * one for the segment [2,2] (i.e. the second element of the array), * three for the segment [5,5] (i.e. the fifth element of the array). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task Your task is to find the sum for the range `0 ... m` for all powers from `0 ... n. # Example For `m = 2, n = 3`, the result should be `20` `0^0+1^0+2^0 + 0^1+1^1+2^1 + 0^2+1^2+2^2 + 0^3+1^3+2^3 = 20` Note, that no output ever exceeds 2e9. # Input/Output - `[input]` integer m `0 <= m <= 50000` - `[input]` integer `n` `0 <= n <= 9` - `[output]` an integer(double in C#) The sum value. Write your solution by modifying this code: ```python def S2N(m, n): ``` Your solution should implemented in the function "S2N". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an integer $n$. You have to calculate the number of binary (consisting of characters 0 and/or 1) strings $s$ meeting the following constraints. For every pair of integers $(i, j)$ such that $1 \le i \le j \le n$, an integer $a_{i,j}$ is given. It imposes the following constraint on the string $s_i s_{i+1} s_{i+2} \dots s_j$: if $a_{i,j} = 1$, all characters in $s_i s_{i+1} s_{i+2} \dots s_j$ should be the same; if $a_{i,j} = 2$, there should be at least two different characters in $s_i s_{i+1} s_{i+2} \dots s_j$; if $a_{i,j} = 0$, there are no additional constraints on the string $s_i s_{i+1} s_{i+2} \dots s_j$. Count the number of binary strings $s$ of length $n$ meeting the aforementioned constraints. Since the answer can be large, print it modulo $998244353$. -----Input----- The first line contains one integer $n$ ($2 \le n \le 100$). Then $n$ lines follow. The $i$-th of them contains $n-i+1$ integers $a_{i,i}, a_{i,i+1}, a_{i,i+2}, \dots, a_{i,n}$ ($0 \le a_{i,j} \le 2$). -----Output----- Print one integer — the number of strings meeting the constraints, taken modulo $998244353$. -----Examples----- Input 3 1 0 2 1 0 1 Output 6 Input 3 1 1 2 1 0 1 Output 2 Input 3 1 2 1 1 0 1 Output 0 Input 3 2 0 2 0 1 1 Output 0 -----Note----- In the first example, the strings meeting the constraints are 001, 010, 011, 100, 101, 110. In the second example, the strings meeting the constraints are 001, 110. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has got a magic matrix a of size n × m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column. Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element. After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it. Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to √{(i_1-i_2)^2 + (j_1-j_2)^2}. Calculate the expected value of the Vasya's final score. It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q not≡ 0~(mod ~ 998244353). Print the value P ⋅ Q^{-1} modulo 998244353. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 1 000) — the number of rows and the number of columns in the matrix a. The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 ≤ a_{ij} ≤ 10^9). The following line contains two integers r and c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — the index of row and the index of column where the chip is now. Output Print the expected value of Vasya's final score in the format described in the problem statement. Examples Input 1 4 1 1 2 1 1 3 Output 2 Input 2 3 1 5 7 2 3 1 1 2 Output 665496238 Note In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. To satisfy his love of matching socks, Phoenix has brought his $n$ socks ($n$ is even) to the sock store. Each of his socks has a color $c_i$ and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: recolor a sock to any color $c'$ $(1 \le c' \le n)$ turn a left sock into a right sock turn a right sock into a left sock The sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa. A matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make $n/2$ matching pairs? Each sock must be included in exactly one matching pair. -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of each test case contains three integers $n$, $l$, and $r$ ($2 \le n \le 2 \cdot 10^5$; $n$ is even; $0 \le l, r \le n$; $l+r=n$) — the total number of socks, and the number of left and right socks, respectively. The next line contains $n$ integers $c_i$ ($1 \le c_i \le n$) — the colors of the socks. The first $l$ socks are left socks, while the next $r$ socks are right socks. It is guaranteed that the sum of $n$ across all the test cases will not exceed $2 \cdot 10^5$. -----Output----- For each test case, print one integer — the minimum cost for Phoenix to make $n/2$ matching pairs. Each sock must be included in exactly one matching pair. -----Examples----- Input 4 6 3 3 1 2 3 2 2 2 6 2 4 1 1 2 2 2 2 6 5 1 6 5 4 3 2 1 4 0 4 4 4 4 3 Output 2 3 5 3 -----Note----- In the first test case, Phoenix can pay $2$ dollars to: recolor sock $1$ to color $2$ recolor sock $3$ to color $2$ There are now $3$ matching pairs. For example, pairs $(1, 4)$, $(2, 5)$, and $(3, 6)$ are matching. In the second test case, Phoenix can pay $3$ dollars to: turn sock $6$ from a right sock to a left sock recolor sock $3$ to color $1$ recolor sock $4$ to color $1$ There are now $3$ matching pairs. For example, pairs $(1, 3)$, $(2, 4)$, and $(5, 6)$ are matching. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create a function which answers the question "Are you playing banjo?". If your name starts with the letter "R" or lower case "r", you are playing banjo! The function takes a name as its only argument, and returns one of the following strings: ``` name + " plays banjo" name + " does not play banjo" ``` Names given are always valid strings. Write your solution by modifying this code: ```python def areYouPlayingBanjo(name): ``` Your solution should implemented in the function "areYouPlayingBanjo". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In the good old Hachioji railroad station located in the west of Tokyo, there are several parking lines, and lots of freight trains come and go every day. All freight trains travel at night, so these trains containing various types of cars are settled in your parking lines early in the morning. Then, during the daytime, you must reorganize cars in these trains according to the request of the railroad clients, so that every line contains the “right” train, i.e. the right number of cars of the right types, in the right order. As shown in Figure 7, all parking lines run in the East-West direction. There are exchange lines connecting them through which you can move cars. An exchange line connects two ends of different parking lines. Note that an end of a parking line can be connected to many ends of other lines. Also note that an exchange line may connect the East-end of a parking line and the West-end of another. <image> Cars of the same type are not discriminated between each other. The cars are symmetric, so directions of cars don’t matter either. You can divide a train at an arbitrary position to make two sub-trains and move one of them through an exchange line connected to the end of its side. Alternatively, you may move a whole train as is without dividing it. Anyway, when a (sub-) train arrives at the destination parking line and the line already has another train in it, they are coupled to form a longer train. Your superautomatic train organization system can do these without any help of locomotive engines. Due to the limitation of the system, trains cannot stay on exchange lines; when you start moving a (sub-) train, it must arrive at the destination parking line before moving another train. In what follows, a letter represents a car type and a train is expressed as a sequence of letters. For example in Figure 8, from an initial state having a train "aabbccdee" on line 0 and no trains on other lines, you can make "bbaadeecc" on line 2 with the four moves shown in the figure. <image> To cut the cost out, your boss wants to minimize the number of (sub-) train movements. For example, in the case of Figure 8, the number of movements is 4 and this is the minimum. Given the configurations of the train cars in the morning (arrival state) and evening (departure state), your job is to write a program to find the optimal train reconfiguration plan. Input The input consists of one or more datasets. A dataset has the following format: x y p1 P1 q1 Q1 p2 P2 q2 Q2 . . . py Py qy Qy s0 s1 . . . sx-1 t0 t1 . . . tx-1 x is the number of parking lines, which are numbered from 0 to x-1. y is the number of exchange lines. Then y lines of the exchange line data follow, each describing two ends connected by the exchange line; pi and qi are integers between 0 and x - 1 which indicate parking line numbers, and Pi and Qi are either "E" (East) or "W" (West) which indicate the ends of the parking lines. Then x lines of the arrival (initial) configuration data, s0, ... , sx-1, and x lines of the departure (target) configuration data, t0, ... tx-1, follow. Each of these lines contains one or more lowercase letters "a", "b", ..., "z", which indicate types of cars of the train in the corresponding parking line, in west to east order, or alternatively, a single "-" when the parking line is empty. You may assume that x does not exceed 4, the total number of cars contained in all the trains does not exceed 10, and every parking line has sufficient length to park all the cars. You may also assume that each dataset has at least one solution and that the minimum number of moves is between one and six, inclusive. Two zeros in a line indicate the end of the input. Output For each dataset, output the number of moves for an optimal reconfiguration plan, in a separate line. Example Input 3 5 0W 1W 0W 2W 0W 2E 0E 1E 1E 2E aabbccdee - - - - bbaadeecc 3 3 0E 1W 1E 2W 2E 0W aabb bbcc aa bbbb cc aaaa 3 4 0E 1W 0E 2E 1E 2W 2E 0W ababab - - aaabbb - - 0 0 Output 4 2 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people. But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him. Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that: * the number of different users online did not exceed M at any moment, * at some second the number of distinct users online reached value M, * the total number of users (the number of distinct identifiers) was as much as possible. Help Polycarpus cope with the test. Input The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59). Output In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes). Examples Input 4 2 10 17:05:53 17:05:58 17:06:01 22:39:47 Output 3 1 2 2 3 Input 1 2 86400 00:00:00 Output No solution Note Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56. In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc. A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i. He would like to make one as follows: * Specify two non-negative integers A and B. * Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1. * Repeat the following operation until he has one connected tree: * Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y. * Properly number the vertices in the tree. Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized. Solve this problem for him. Constraints * 2 \leq N \leq 10^5 * 1 \leq a_i,b_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output For the lexicographically smallest (A,B), print A and B with a space in between. Examples Input 7 1 2 2 3 2 4 4 5 4 6 6 7 Output 3 2 Input 8 1 2 2 3 3 4 4 5 5 6 5 7 5 8 Output 2 5 Input 10 1 2 2 3 3 4 2 5 6 5 6 7 7 8 5 9 10 5 Output 3 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided to upsolve the following problem: You have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \frac{l + r - 1}{2}$, then if $r - l + 1$ is an even number and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$, then the pair is funny. In other words, $\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\oplus$ of elements of the right half. Note that $\oplus$ denotes the bitwise XOR operation. It is time to continue solving the contest, so Sasha asked you to solve this task. -----Input----- The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the size of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^{20}$) — array itself. -----Output----- Print one integer — the number of funny pairs. You should consider only pairs where $r - l + 1$ is even number. -----Examples----- Input 5 1 2 3 4 5 Output 1 Input 6 3 2 2 3 7 6 Output 3 Input 3 42 4 2 Output 0 -----Note----- Be as cool as Sasha, upsolve problems! In the first example, the only funny pair is $(2, 5)$, as $2 \oplus 3 = 4 \oplus 5 = 1$. In the second example, funny pairs are $(2, 3)$, $(1, 4)$, and $(3, 6)$. In the third example, there are no funny pairs. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sender if unknown acronyms are present. Any combination of three or more letters in upper case will be considered an acronym. Acronyms will not be combined with lowercase letters, such as in the case of 'KPIs'. They will be kept isolated as a word/words within a string. For any string: All instances of 'KPI' must become "key performance indicators" All instances of 'EOD' must become "the end of the day" All instances of 'TBD' must become "to be decided" All instances of 'WAH' must become "work at home" All instances of 'IAM' must become "in a meeting" All instances of 'OOO' must become "out of office" All instances of 'NRN' must become "no reply necessary" All instances of 'CTA' must become "call to action" All instances of 'SWOT' must become "strengths, weaknesses, opportunities and threats" If there are any unknown acronyms in the string, Laura wants you to return only the message: '[acronym] is an acronym. I do not like acronyms. Please remove them from your email.' So if the acronym in question was 'BRB', you would return the string: 'BRB is an acronym. I do not like acronyms. Please remove them from your email.' If there is more than one unknown acronym in the string, return only the first in your answer. If all acronyms can be replaced with full words according to the above, however, return only the altered string. If this is the case, ensure that sentences still start with capital letters. '!' or '?' will not be used. Write your solution by modifying this code: ```python def acronym_buster(message): ``` Your solution should implemented in the function "acronym_buster". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters. Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name. Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league. Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. -----Output----- It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. -----Examples----- Input 2 DINAMO BYTECITY FOOTBALL MOSCOW Output YES DIN FOO Input 2 DINAMO BYTECITY DINAMO BITECITY Output NO Input 3 PLAYFOOTBALL MOSCOW PLAYVOLLEYBALL SPB GOGO TECHNOCUP Output YES PLM PLS GOG Input 3 ABC DEF ABC EFG ABD OOO Output YES ABD ABE ABO -----Note----- In the first sample Innokenty can choose first option for both clubs. In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs. In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club. In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function that calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return `1`. ~~~if:objc NOTE: The first (and only named) argument of the function `n` specifies the number of arguments in the variable-argument list. Do **not** take `n` into account when computing the LCM of the numbers. ~~~ Write your solution by modifying this code: ```python def lcm(*args): ``` Your solution should implemented in the function "lcm". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You will receive 5 points for solving this problem. Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using this operation, Manao converts the string into a structure that has one more level than there were fold operations performed. See the following examples for clarity. We will denote the positions of folds with '|' characters. For example, the word "ABRACADABRA" written as "AB|RACA|DAB|RA" indicates that it has been folded three times: first, between the leftmost pair of 'B' and 'R' letters; second, between 'A' and 'D'; and third, between the rightmost pair of 'B' and 'R' letters. Here are several examples of folded strings: "ABCDEF|GHIJK" | "A|BCDEFGHIJK" | "AB|RACA|DAB|RA" | "X|XXXXX|X|X|XXXXXX" | | | XXXXXX KJIHG | KJIHGFEDCB | AR | X ABCDEF | A | DAB | X | | ACAR | XXXXX | | AB | X One last example for "ABCD|EFGH|IJ|K": K IJ HGFE ABCD Manao noticed that each folded string can be viewed as several piles of letters. For instance, in the previous example, there are four piles, which can be read as "AHI", "BGJK", "CF", and "DE" from bottom to top. Manao wonders what is the highest pile of identical letters he can build using fold operations on a given word. Note that the pile should not contain gaps and should start at the bottom level. For example, in the rightmost of the four examples above, none of the piles would be considered valid since each of them has gaps, starts above the bottom level, or both. -----Input----- The input will consist of one line containing a single string of n characters with 1 ≤ n ≤ 1000 and no spaces. All characters of the string will be uppercase letters. This problem doesn't have subproblems. You will get 5 points for the correct submission. -----Output----- Print a single integer — the size of the largest pile composed of identical characters that can be seen in a valid result of folding operations on the given string. -----Examples----- Input ABRACADABRA Output 3 Input ABBBCBDB Output 3 Input AB Output 1 -----Note----- Consider the first example. Manao can create a pile of three 'A's using the folding "AB|RACAD|ABRA", which results in the following structure: ABRA DACAR AB In the second example, Manao can create a pile of three 'B's using the following folding: "AB|BB|CBDB". CBDB BB AB Another way for Manao to create a pile of three 'B's with "ABBBCBDB" is the following folding: "AB|B|BCBDB". BCBDB B AB In the third example, there are no folds performed and the string is just written in one line. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi has an N \times M grid, with N horizontal rows and M vertical columns. Determine if we can place A 1 \times 2 tiles (1 vertical, 2 horizontal) and B 2 \times 1 tiles (2 vertical, 1 horizontal) satisfying the following conditions, and construct one arrangement of the tiles if it is possible: * All the tiles must be placed on the grid. * Tiles must not stick out of the grid, and no two different tiles may intersect. * Neither the grid nor the tiles may be rotated. * Every tile completely covers exactly two squares. Constraints * 1 \leq N,M \leq 1000 * 0 \leq A,B \leq 500000 * N, M, A and B are integers. Input Input is given from Standard Input in the following format: N M A B Output If it is impossible to place all the tiles, print `NO`. Otherwise, print the following: YES c_{11}...c_{1M} : c_{N1}...c_{NM} Here, c_{ij} must be one of the following characters: `.`, `<`, `>`, `^` and `v`. Represent an arrangement by using each of these characters as follows: * When c_{ij} is `.`, it indicates that the square at the i-th row and j-th column is empty; * When c_{ij} is `<`, it indicates that the square at the i-th row and j-th column is covered by the left half of a 1 \times 2 tile; * When c_{ij} is `>`, it indicates that the square at the i-th row and j-th column is covered by the right half of a 1 \times 2 tile; * When c_{ij} is `^`, it indicates that the square at the i-th row and j-th column is covered by the top half of a 2 \times 1 tile; * When c_{ij} is `v`, it indicates that the square at the i-th row and j-th column is covered by the bottom half of a 2 \times 1 tile. Examples Input 3 4 4 2 Output YES <><> ^<>^ v<>v Input 4 5 5 3 Output YES <>..^ ^.<>v v<>.^ <><>v Input 7 9 20 20 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a n × m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). Input The first line contains two positive integer numbers n and m (1 ≤ n, m ≤ 1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed. Output Output a single number — total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 2 ** *. Output 1 Input 3 4 *..* .**. *.** Output 9 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two integers $a$ and $m$. Calculate the number of integers $x$ such that $0 \le x < m$ and $\gcd(a, m) = \gcd(a + x, m)$. Note: $\gcd(a, b)$ is the greatest common divisor of $a$ and $b$. -----Input----- The first line contains the single integer $T$ ($1 \le T \le 50$) — the number of test cases. Next $T$ lines contain test cases — one per line. Each line contains two integers $a$ and $m$ ($1 \le a < m \le 10^{10}$). -----Output----- Print $T$ integers — one per test case. For each test case print the number of appropriate $x$-s. -----Example----- Input 3 4 9 5 10 42 9999999967 Output 6 1 9999999966 -----Note----- In the first test case appropriate $x$-s are $[0, 1, 3, 4, 6, 7]$. In the second test case the only appropriate $x$ is $0$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a very complicated hashing function in order to change the names of the babies she steals. In order to prevent this from happening to future Doctors, Heidi decided to prepare herself by learning some basic hashing techniques. The first hashing function she designed is as follows. Given two positive integers $(x, y)$ she defines $H(x,y):=x^2+2xy+x+1$. Now, Heidi wonders if the function is reversible. That is, given a positive integer $r$, can you find a pair $(x, y)$ (of positive integers) such that $H(x, y) = r$? If multiple such pairs exist, output the one with smallest possible $x$. If there is no such pair, output "NO". -----Input----- The first and only line contains an integer $r$ ($1 \le r \le 10^{12}$). -----Output----- Output integers $x, y$ such that $H(x,y) = r$ and $x$ is smallest possible, or "NO" if no such pair exists. -----Examples----- Input 19 Output 1 8 Input 16 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This problem is different with hard version only by constraints on total answers length It is an interactive problem Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries: * ? l r – ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. * ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 3 queries of the first type. To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)^2. Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules. Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer. Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive. Input First line contains number n (1 ≤ n ≤ 100) — the length of the picked string. Interaction You start the interaction by reading the number n. To ask a query about a substring from l to r inclusively (1 ≤ l ≤ r ≤ n), you should output ? l r on a separate line. After this, all substrings of s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled. In the case, if you ask an incorrect query, ask more than 3 queries of the first type or there will be more than (n+1)^2 substrings returned in total, you will receive verdict Wrong answer. To guess the string s, you should output ! s on a separate line. After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack format To hack a solution, use the following format: The first line should contain one integer n (1 ≤ n ≤ 100) — the length of the string, and the following line should contain the string s. Example Input 4 a aa a cb b c c Output ? 1 2 ? 3 4 ? 4 4 ! aabc Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Everyone knows that computers become faster and faster. Recently Berland scientists have built a machine that can move itself back in time! More specifically, it works as follows. It has an infinite grid and a robot which stands on one of the cells. Each cell of the grid can either be empty or contain 0 or 1. The machine also has a program which consists of instructions, which are being handled one by one. Each instruction is represented by exactly one symbol (letter or digit) and takes exactly one unit of time (say, second) to be performed, except the last type of operation (it's described below). Here they are: * 0 or 1: the robot places this number into the cell he is currently at. If this cell wasn't empty before the operation, its previous number is replaced anyway. * e: the robot erases the number into the cell he is at. * l, r, u or d: the robot goes one cell to the left/right/up/down. * s: the robot stays where he is for a unit of time. * t: let x be 0, if the cell with the robot is empty, otherwise let x be one more than the digit in this cell (that is, x = 1 if the digit in this cell is 0, and x = 2 if the digit is 1). Then the machine travels x seconds back in time. Note that this doesn't change the instructions order, but it changes the position of the robot and the numbers in the grid as they were x units of time ago. You can consider this instruction to be equivalent to a Ctrl-Z pressed x times. For example, let the board be completely empty, and the program be sr1t0. Let the robot initially be at (0, 0). * [now is the moment 0, the command is s]: we do nothing. * [now is the moment 1, the command is r]: we are now at (1, 0). * [now is the moment 2, the command is 1]: we are at (1, 0), and this cell contains 1. * [now is the moment 3, the command is t]: we travel 1 + 1 = 2 moments back, that is, to the moment 1. * [now is the moment 1, the command is 0]: we are again at (0, 0), and the board is clear again, but after we follow this instruction, this cell has 0 in it. We've just rewritten the history. The consequences of the third instruction have never happened. Now Berland scientists want to use their machine in practice. For example, they want to be able to add two integers. Assume that the initial state of the machine is as follows: * One positive integer is written in binary on the grid in such a way that its right bit is at the cell (0, 1), from left to right from the highest bit to the lowest bit. * The other positive integer is written in binary on the grid in such a way that its right bit is at the cell (0, 0), from left to right from the highest bit to the lowest bit. * All the other cells are empty. * The robot is at (0, 0). * We consider this state to be always in the past; that is, if you manage to travel to any negative moment, the board was always as described above, and the robot was at (0, 0) for eternity. You are asked to write a program after which * The robot stands on a non-empty cell, * If we read the number starting from the cell with the robot and moving to the right until the first empty cell, this will be a + b in binary, from the highest bit to the lowest bit. Note that there are no restrictions on other cells. In particular, there may be a digit just to the left to the robot after all instructions. In each test you are given up to 1000 pairs (a, b), and your program must work for all these pairs. Also since the machine's memory is not very big, your program must consist of no more than 10^5 instructions. Input The first line contains the only integer t (1≤ t≤ 1000) standing for the number of testcases. Each of the next t lines consists of two positive integers a and b (1≤ a, b < 2^{30}) in decimal. Output Output the only line consisting of no more than 10^5 symbols from 01eslrudt standing for your program. Note that formally you may output different programs for different tests. Example Input 2 123456789 987654321 555555555 555555555 Output 0l1l1l0l0l0l1l1l1l0l1l0l1l1l0l0l0l1l0l1l1l1l0l0l0l1l0l0l0l0l1l0lr Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black. You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0, 0, 0, 1, 1, 1, 0, 0, 0] can be a photo of zebra, while the photo [0, 0, 0, 1, 1, 1, 1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not? -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100 000) — the width of the photo. The second line contains a sequence of integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 1) — the description of the photo. If a_{i} is zero, the i-th column is all black. If a_{i} is one, then the i-th column is all white. -----Output----- If the photo can be a photo of zebra, print "YES" (without quotes). Otherwise, print "NO". You can print each letter in any case (upper or lower). -----Examples----- Input 9 0 0 0 1 1 1 0 0 0 Output YES Input 7 0 0 0 1 1 1 1 Output NO Input 5 1 1 1 1 1 Output YES Input 8 1 1 1 0 0 0 1 1 Output NO Input 9 1 1 0 1 1 0 1 1 0 Output NO -----Note----- The first two examples are described in the statements. In the third example all pixels are white, so the photo can be a photo of zebra. In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are $n$ benches in the Berland Central park. It is known that $a_i$ people are currently sitting on the $i$-th bench. Another $m$ people are coming to the park and each of them is going to have a seat on some bench out of $n$ available. Let $k$ be the maximum number of people sitting on one bench after additional $m$ people came to the park. Calculate the minimum possible $k$ and the maximum possible $k$. Nobody leaves the taken seat during the whole process. -----Input----- The first line contains a single integer $n$ $(1 \le n \le 100)$ — the number of benches in the park. The second line contains a single integer $m$ $(1 \le m \le 10\,000)$ — the number of people additionally coming to the park. Each of the next $n$ lines contains a single integer $a_i$ $(1 \le a_i \le 100)$ — the initial number of people on the $i$-th bench. -----Output----- Print the minimum possible $k$ and the maximum possible $k$, where $k$ is the maximum number of people sitting on one bench after additional $m$ people came to the park. -----Examples----- Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 -----Note----- In the first example, each of four benches is occupied by a single person. The minimum $k$ is $3$. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum $k$ is $7$. That requires all six new people to occupy the same bench. The second example has its minimum $k$ equal to $15$ and maximum $k$ equal to $15$, as there is just a single bench in the park and all $10$ people will occupy it. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost a_{i} Egyptian pounds. If Sagheer buys k items with indices x_1, x_2, ..., x_{k}, then the cost of item x_{j} is a_{x}_{j} + x_{j}·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? -----Input----- The first line contains two integers n and S (1 ≤ n ≤ 10^5 and 1 ≤ S ≤ 10^9) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the base costs of the souvenirs. -----Output----- On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. -----Examples----- Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 -----Note----- In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007. Input The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≤ ai, bi ≤ n, ai ≠ bi, <image>). Each pair of people will be described no more than once. Output Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007. Examples Input 3 0 Output 4 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 0 Output 1 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 1 Output 0 Note In the first sample, the four ways are to: * Make everyone love each other * Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Petya loves looking for numbers' divisors. One day Petya came across the following problem: You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the following n lines contain two space-separated integers xi and yi (1 ≤ xi ≤ 105, 0 ≤ yi ≤ i - 1, where i is the query's ordinal number; the numeration starts with 1). If yi = 0 for the query, then the answer to the query will be the number of divisors of the number xi. In this case you do not need to take the previous numbers x into consideration. Output For each query print the answer on a single line: the number of positive integers k such that <image> Examples Input 6 4 0 3 1 5 2 6 2 18 4 10000 3 Output 3 1 1 2 2 22 Note Let's write out the divisors that give answers for the first 5 queries: 1) 1, 2, 4 2) 3 3) 5 4) 2, 6 5) 9, 18 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Once Chef decided to divide the tangerine into several parts. At first, he numbered tangerine's segments from 1 to n in the clockwise order starting from some segment. Then he intended to divide the fruit into several parts. In order to do it he planned to separate the neighbouring segments in k places, so that he could get k parts: the 1^{st} - from segment l_{1} to segment r_{1} (inclusive), the 2^{nd} - from l_{2} to r_{2}, ..., the k^{th} - from l_{k} to r_{k} (in all cases in the clockwise order). Suddenly, when Chef was absent, one naughty boy came and divided the tangerine into p parts (also by separating the neighbouring segments one from another): the 1^{st} - from segment a_{1} to segment b_{1}, the 2^{nd} - from a_{2} to b_{2}, ..., the p^{th} - from a_{p} to b_{p} (in all cases in the clockwise order). Chef became very angry about it! But maybe little boy haven't done anything wrong, maybe everything is OK? Please, help Chef to determine whether he is able to obtain the parts he wanted to have (in order to do it he can divide p current parts, but, of course, he can't join several parts into one). Please, note that parts are not cyclic. That means that even if the tangerine division consists of only one part, but that part include more than one segment, there are two segments which were neighbouring in the initial tangerine but are not neighbouring in the division. See the explanation of example case 2 to ensure you understood that clarification. ------ 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, p, denoting the number of tangerine's segments and number of parts in each of the two divisions. The next k lines contain pairs of space-separated integers l_{i} and r_{i}. The next p lines contain pairs of space-separated integers a_{i} and b_{i}. It is guaranteed that each tangerine's segment is contained in exactly one of the first k parts and in exactly one of the next p parts. ------ Output ------ For each test case, output a single line containing either "Yes" or "No" (without the quotes), denoting whether Chef is able to obtain the parts he wanted to have.   ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ n ≤ 5 * 10^{7}$ $1 ≤ k ≤ min(500, n)$ $1 ≤ p ≤ min(500, n)$ $1 ≤ l_{i}, r_{i}, a_{i}, b_{i} ≤ n$   ----- Sample Input 1 ------ 2 10 3 2 1 4 5 5 6 10 1 5 6 10 10 3 1 2 5 10 1 6 9 1 10 ----- Sample Output 1 ------ Yes No ----- explanation 1 ------ Example case 1: To achieve his goal Chef should divide the first part (1-5) in two by separating segments 4 and 5 one from another. Example case 2: The boy didn't left the tangerine as it was (though you may thought that way), he separated segments 1 and 10 one from another. But segments 1 and 10 are in one part in Chef's division, so he is unable to achieve his goal. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible. Input The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m. Output Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n. Examples Input 2 2 1 0 1 1 1 1 Output 0 Input 4 5 0 0 1 0 1 0 1 1 1 0 1 0 1 0 1 1 1 1 1 1 2 3 Output 2 Note In the second example the upper left square is (1,1) and the lower right is (3,2). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this Kata, you will be given two positive integers `a` and `b` and your task will be to apply the following operations: ``` i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii); ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii); iii) If b ≥ 2*a, set b = b - 2*a, and repeat step (i). Otherwise, return [a,b]. ``` `a` and `b` will both be lower than 10E8. More examples in tests cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) Write your solution by modifying this code: ```python def solve(a,b): ``` Your solution should implemented in the function "solve". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string $s$ of length $n$, which consists only of the first $k$ letters of the Latin alphabet. All letters in string $s$ are uppercase. A subsequence of string $s$ is a string that can be derived from $s$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not. A subsequence of $s$ called good if the number of occurences of each of the first $k$ letters of the alphabet is the same. Find the length of the longest good subsequence of $s$. -----Input----- The first line of the input contains integers $n$ ($1\le n \le 10^5$) and $k$ ($1 \le k \le 26$). The second line of the input contains the string $s$ of length $n$. String $s$ only contains uppercase letters from 'A' to the $k$-th letter of Latin alphabet. -----Output----- Print the only integer — the length of the longest good subsequence of string $s$. -----Examples----- Input 9 3 ACAABCCAB Output 6 Input 9 4 ABCABCABC Output 0 -----Note----- In the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length. In the second example, none of the subsequences can have 'D', hence the answer is $0$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In Morse code, an letter of English alphabet is represented as a string of some length from $1$ to $4$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1". Because there are $2^1+2^2+2^3+2^4 = 30$ strings with length $1$ to $4$ containing only "0" and/or "1", not all of them correspond to one of the $26$ English letters. In particular, each string of "0" and/or "1" of length at most $4$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111". You will work with a string $S$, which is initially empty. For $m$ times, either a dot or a dash will be appended to $S$, one at a time. Your task is to find and report, after each of these modifications to string $S$, the number of non-empty sequences of English letters that are represented with some substring of $S$ in Morse code. Since the answers can be incredibly tremendous, print them modulo $10^9 + 7$. -----Input----- The first line contains an integer $m$ ($1 \leq m \leq 3\,000$) — the number of modifications to $S$. Each of the next $m$ lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to $S$. -----Output----- Print $m$ lines, the $i$-th of which being the answer after the $i$-th modification to $S$. -----Examples----- Input 3 1 1 1 Output 1 3 7 Input 5 1 0 1 0 1 Output 1 4 10 22 43 Input 9 1 1 0 0 0 1 1 0 1 Output 1 3 10 24 51 109 213 421 833 -----Note----- Let us consider the first sample after all characters have been appended to $S$, so S is "111". As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of $S$ in Morse code, therefore, are as follows. "T" (translates into "1") "M" (translates into "11") "O" (translates into "111") "TT" (translates into "11") "TM" (translates into "111") "MT" (translates into "111") "TTT" (translates into "111") Although unnecessary for this task, a conversion table from English alphabets into Morse code can be found here. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create a program that reads the attendance numbers of students in a class and the data that stores the ABO blood group and outputs the number of people for each blood type. There are four types of ABO blood types: A, B, AB, and O. Input A comma-separated pair of attendance numbers and blood types is given over multiple lines. The attendance number is an integer between 1 and 50, and the blood type is one of the strings "A", "B", "AB" or "O". The number of students does not exceed 50. Output Number of people of type A on the first line Number of people of type B on the second line Number of people of AB type on the 3rd line Number of O-shaped people on the 4th line Is output. Example Input 1,B 2,A 3,B 4,AB 5,B 6,O 7,A 8,O 9,AB 10,A 11,A 12,B 13,AB 14,A Output 5 4 3 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Complete the function to determine the number of bits required to convert integer `A` to integer `B` (where `A` and `B` >= 0) The upper limit for `A` and `B` is 2^(16), `int.MaxValue` or similar. For example, you can change 31 to 14 by flipping the 4th and 0th bit: ``` 31 0 0 0 1 1 1 1 1 14 0 0 0 0 1 1 1 0 --- --------------- bit 7 6 5 4 3 2 1 0 ``` Thus `31` and `14` should return `2`. Write your solution by modifying this code: ```python def convert_bits(a, b): ``` Your solution should implemented in the function "convert_bits". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ## Witamy! You are in Poland and want to order a drink. You need to ask "One beer please": "Jedno piwo poprosze" ``` java Translator.orderingBeers(1) = "Jedno piwo poprosze" ``` But let's say you are really thirsty and want several beers. Then you need to count in Polish. And more difficult, you need to understand the Polish grammar and cases (nominative, genitive, accustative and more). ## The grammar In English, the plural of "beer" is simply "beers", with an "s". In Polish, the plural of "piwo" (nominative singular) is "piw" (genitive plural) or "piwa" (nominative plural). It depends! The rules: * usually the plural is genitive: "piw" * but after the numerals 2, 3, 4, and compound numbers ending with them (e.g. 22, 23, 24), the noun is plural and takes the same case as the numeral, so nominative: "piwa" * and exception to the exception: for 12, 13 and 14, it's the genitive plural again: "piw" (yes, I know, it's crazy!) ## The numbers From 0 to 9: "zero", "jeden", "dwa", "trzy", "cztery", "piec", "szesc" , "siedem", "osiem", "dziewiec" From 10 to 19 it's nearly the same, with "-ascie" at the end: "dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie" Tens from 10 to 90 are nearly the same, with "-ziesci" or "ziesiat" at the end: "dziesiec", "dwadziescia", "trzydziesci", "czterdziesci", "piecdziesiat", "szescdziesiat", "siedemdziesiat", "osiemdziesiat", "dziewiecdziesiat" Compound numbers are constructed similarly to English: tens + units. For example, 22 is "dwadziescia dwa". "One" could be male ("Jeden"), female ("Jedna") or neuter ("Jedno"), which is the case for "beer" (piwo). But all other numbers are invariant, even if ending with "jeden". Ah, and by the way, if you don't want to drink alcohol (so no beers are ordered), ask for mineral water instead: "Woda mineralna". Note: if the number of beers is outside your (limited) Polish knowledge (0-99), raise an error! --- More about the crazy polish grammar: https://en.wikipedia.org/wiki/Polish_grammar Write your solution by modifying this code: ```python def ordering_beers(beers): ``` Your solution should implemented in the function "ordering_beers". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Problem statement Meatishi can increase or decrease the number of fingers. There are n buns in front of Nikunishi-kun. Meatishi is trying to count the number of steamed buns by breaking his finger. There are only two shapes that Nishikun's fingers can take, whether they are broken or not. Nikunishi understands binary numbers. Nikunishi-kun can count numbers by associating each finger with a binary digit. Nikunishi doesn't understand the logarithm. Find the minimum number of fingers needed to count the buns instead of Nishikun. input n Constraint * An integer * 0 ≤ n ≤ 1018 output Print the answer on one line, and print a newline at the end. sample Sample input 1 0 Sample output 1 0 Sample input 2 Four Sample output 2 3 Sample input 3 31 Sample output 3 Five Sample input 4 36028797018963968 Sample output 4 56 Example Input 0 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. $\left. \begin{array}{l}{\text{Rey}} \\{\text{to my}} \\{\text{heart}} \end{array} \right.$ Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a_1, a_2, ..., a_{k} such that $n = \prod_{i = 1}^{k} a_{i}$ in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that $\operatorname{gcd}(p, q) = 1$, where $gcd$ is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 10^9 + 7. Please note that we want $gcd$ of p and q to be 1, not $gcd$ of their remainders after dividing by 10^9 + 7. -----Input----- The first line of input contains a single integer k (1 ≤ k ≤ 10^5) — the number of elements in array Barney gave you. The second line contains k integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 10^18) — the elements of the array. -----Output----- In the only line of output print a single string x / y where x is the remainder of dividing p by 10^9 + 7 and y is the remainder of dividing q by 10^9 + 7. -----Examples----- Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development. For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph. Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: n c1 c2 :: cn The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9). The number of datasets does not exceed 20. Output For each input dataset, the number of sales is output in numerical order of each ice cream type. Example Input 15 2 6 7 0 1 9 8 7 3 8 9 4 8 2 2 3 9 1 5 0 Output * * *** * * - * ** *** ** - * - - - * - - - * Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square. For a given string $s$ determine if it is square. -----Input----- The first line of input data contains an integer $t$ ($1 \le t \le 100$) —the number of test cases. This is followed by $t$ lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between $1$ and $100$ inclusive. -----Output----- For each test case, output on a separate line: YES if the string in the corresponding test case is square, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response). -----Examples----- Input 10 a aa aaa aaaa abab abcabc abacaba xxyy xyyx xyxy Output NO YES NO YES YES YES NO NO NO YES -----Note----- None Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have to write two methods to *encrypt* and *decrypt* strings. Both methods have two parameters: ``` 1. The string to encrypt/decrypt 2. The Qwerty-Encryption-Key (000-999) ``` The rules are very easy: ``` The crypting-regions are these 3 lines from your keyboard: 1. "qwertyuiop" 2. "asdfghjkl" 3. "zxcvbnm,." If a char of the string is not in any of these regions, take the char direct in the output. If a char of the string is in one of these regions: Move it by the part of the key in the region and take this char at the position from the region. If the movement is over the length of the region, continue at the beginning. The encrypted char must have the same case like the decrypted char! So for upperCase-chars the regions are the same, but with pressed "SHIFT"! The Encryption-Key is an integer number from 000 to 999. E.g.: 127 The first digit of the key (e.g. 1) is the movement for the first line. The second digit of the key (e.g. 2) is the movement for the second line. The third digit of the key (e.g. 7) is the movement for the third line. (Consider that the key is an integer! When you got a 0 this would mean 000. A 1 would mean 001. And so on.) ``` You do not need to do any prechecks. The strings will always be not null and will always have a length > 0. You do not have to throw any exceptions. An Example: ``` Encrypt "Ball" with key 134 1. "B" is in the third region line. Move per 4 places in the region. -> ">" (Also "upperCase"!) 2. "a" is in the second region line. Move per 3 places in the region. -> "f" 3. "l" is in the second region line. Move per 3 places in the region. -> "d" 4. "l" is in the second region line. Move per 3 places in the region. -> "d" --> Output would be ">fdd" ``` *Hint: Don't forget: The regions are from an US-Keyboard!* *In doubt google for "US Keyboard."* This kata is part of the Simple Encryption Series: Simple Encryption #1 - Alternating Split Simple Encryption #2 - Index-Difference Simple Encryption #3 - Turn The Bits Around Simple Encryption #4 - Qwerty Have fun coding it and please don't forget to vote and rank this kata! :-) Write your solution by modifying this code: ```python def encrypt(text, encryptKey): ``` Your solution should implemented in the function "encrypt". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one. Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. -----Input----- The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p_1, then coin located at position p_2 and so on. Coins are numbered from left to right. -----Output----- Print n + 1 numbers a_0, a_1, ..., a_{n}, where a_0 is a hardness of ordering at the beginning, a_1 is a hardness of ordering after the first replacement and so on. -----Examples----- Input 4 1 3 4 2 Output 1 2 3 2 1 Input 8 6 8 3 4 7 2 1 5 Output 1 2 2 3 4 3 4 5 1 -----Note----- Let's denote as O coin out of circulation, and as X — coin is circulation. At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges. After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process. XOOO → OOOX After replacement of the third coin, Dima's actions look this way: XOXO → OXOX → OOXX After replacement of the fourth coin, Dima's actions look this way: XOXX → OXXX Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe x_{i}. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg. The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather. -----Input----- The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 10^9), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 10^5), denoting the number of banknotes. The next line of input contains n space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9), denoting that the i-th banknote is located in the x_{i}-th safe. Note that x_{i} are not guaranteed to be distinct. -----Output----- Output a single integer: the maximum number of banknotes Oleg can take. -----Examples----- Input 5 3 7 8 4 7 5 5 3 6 2 8 Output 4 Input 6 5 7 5 1 5 7 92 3 Output 0 -----Note----- In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes. For the second sample, Oleg can't take any banknotes without bumping into any of the security guards. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $100^{500}$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $i$-th attack is performed at the beginning of the $a_i$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $1$ damage during each of the next $k$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one). For example, suppose $k = 4$, and Monocarp stabs the dragon during the seconds $2$, $4$ and $10$. Then the poison effect is applied at the start of the $2$-nd second and deals $1$ damage during the $2$-nd and $3$-rd seconds; then, at the beginning of the $4$-th second, the poison effect is reapplied, so it deals exactly $1$ damage during the seconds $4$, $5$, $6$ and $7$; then, during the $10$-th second, the poison effect is applied again, and it deals $1$ damage during the seconds $10$, $11$, $12$ and $13$. In total, the dragon receives $10$ damage. Monocarp knows that the dragon has $h$ hit points, and if he deals at least $h$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $k$ (the number of seconds the poison effect lasts) that is enough to deal at least $h$ damage to the dragon. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of the test case contains two integers $n$ and $h$ ($1 \le n \le 100; 1 \le h \le 10^{18}$) — the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9; a_i < a_{i + 1}$), where $a_i$ is the second when the $i$-th attack is performed. -----Output----- For each test case, print a single integer — the minimum value of the parameter $k$, such that Monocarp will cause at least $h$ damage to the dragon. -----Examples----- Input 4 2 5 1 5 3 10 2 4 10 5 3 1 2 4 5 7 4 1000 3 25 64 1337 Output 3 4 1 470 -----Note----- In the first example, for $k=3$, damage is dealt in seconds $[1, 2, 3, 5, 6, 7]$. In the second example, for $k=4$, damage is dealt in seconds $[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$. In the third example, for $k=1$, damage is dealt in seconds $[1, 2, 4, 5, 7]$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Champernown constant is an irrational number represented in decimal by "0." followed by concatenation of all positive integers in the increasing order. The first few digits of this constant are: 0.123456789101112... Your task is to write a program that outputs the K digits of Chapnernown constant starting at the N-th place for given two natural numbers K and N. Input The input has multiple lines. Each line has two positive integers N and K (N ≤ 109, K ≤ 100) separated by a space. The end of input is indicated by a line with two zeros. This line should not be processed. Output For each line, output a line that contains the K digits. Example Input 4 5 6 7 0 0 Output 45678 6789101 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table). At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other. After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit"). But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss". Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated. -----Input----- The first line of the input contains three integers: n, k and a (1 ≤ n, k, a ≤ 2·10^5) — the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other. The second line contains integer m (1 ≤ m ≤ n) — the number of Bob's moves. The third line contains m distinct integers x_1, x_2, ..., x_{m}, where x_{i} is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n. -----Output----- Print a single integer — the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print "-1". -----Examples----- Input 11 3 3 5 4 8 6 1 11 Output 3 Input 5 1 3 2 1 5 Output -1 Input 5 1 3 1 3 Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a bookshelf which can fit $n$ books. The $i$-th position of bookshelf is $a_i = 1$ if there is a book on this position and $a_i = 0$ otherwise. It is guaranteed that there is at least one book on the bookshelf. In one move, you can choose some contiguous segment $[l; r]$ consisting of books (i.e. for each $i$ from $l$ to $r$ the condition $a_i = 1$ holds) and: Shift it to the right by $1$: move the book at index $i$ to $i + 1$ for all $l \le i \le r$. This move can be done only if $r+1 \le n$ and there is no book at the position $r+1$. Shift it to the left by $1$: move the book at index $i$ to $i-1$ for all $l \le i \le r$. This move can be done only if $l-1 \ge 1$ and there is no book at the position $l-1$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps). For example, for $a = [0, 0, 1, 0, 1]$ there is a gap between books ($a_4 = 0$ when $a_3 = 1$ and $a_5 = 1$), for $a = [1, 1, 0]$ there are no gaps between books and for $a = [0, 0,0]$ there are also no gaps between books. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 200$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the number of places on a bookshelf. The second line of the test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$), where $a_i$ is $1$ if there is a book at this position and $0$ otherwise. It is guaranteed that there is at least one book on the bookshelf. -----Output----- For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps). -----Example----- Input 5 7 0 0 1 0 1 0 1 3 1 0 0 5 1 1 0 0 1 6 1 0 0 0 0 1 5 1 1 0 1 1 Output 2 0 2 4 1 -----Note----- In the first test case of the example, you can shift the segment $[3; 3]$ to the right and the segment $[4; 5]$ to the right. After all moves, the books form the contiguous segment $[5; 7]$. So the answer is $2$. In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already. In the third test case of the example, you can shift the segment $[5; 5]$ to the left and then the segment $[4; 4]$ to the left again. After all moves, the books form the contiguous segment $[1; 3]$. So the answer is $2$. In the fourth test case of the example, you can shift the segment $[1; 1]$ to the right, the segment $[2; 2]$ to the right, the segment $[6; 6]$ to the left and then the segment $[5; 5]$ to the left. After all moves, the books form the contiguous segment $[3; 4]$. So the answer is $4$. In the fifth test case of the example, you can shift the segment $[1; 2]$ to the right. After all moves, the books form the contiguous segment $[2; 5]$. So the answer is $1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarp took $n$ videos, the duration of the $i$-th video is $a_i$ seconds. The videos are listed in the chronological order, i.e. the $1$-st video is the earliest, the $2$-nd video is the next, ..., the $n$-th video is the last. Now Polycarp wants to publish exactly $k$ ($1 \le k \le n$) posts in Instabram. Each video should be a part of a single post. The posts should preserve the chronological order, it means that the first post should contain one or more of the earliest videos, the second post should contain a block (one or more videos) going next and so on. In other words, if the number of videos in the $j$-th post is $s_j$ then: $s_1+s_2+\dots+s_k=n$ ($s_i>0$), the first post contains the videos: $1, 2, \dots, s_1$; the second post contains the videos: $s_1+1, s_1+2, \dots, s_1+s_2$; the third post contains the videos: $s_1+s_2+1, s_1+s_2+2, \dots, s_1+s_2+s_3$; ... the $k$-th post contains videos: $n-s_k+1,n-s_k+2,\dots,n$. Polycarp is a perfectionist, he wants the total duration of videos in each post to be the same. Help Polycarp to find such positive integer values $s_1, s_2, \dots, s_k$ that satisfy all the conditions above. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$). The next line contains $n$ positive integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^4$), where $a_i$ is the duration of the $i$-th video. -----Output----- If solution exists, print "Yes" in the first line. Print $k$ positive integers $s_1, s_2, \dots, s_k$ ($s_1+s_2+\dots+s_k=n$) in the second line. The total duration of videos in each post should be the same. It can be easily proven that the answer is unique (if it exists). If there is no solution, print a single line "No". -----Examples----- Input 6 3 3 3 1 4 1 6 Output Yes 2 3 1 Input 3 3 1 1 1 Output Yes 1 1 1 Input 3 3 1 1 2 Output No Input 3 1 1 10 100 Output Yes 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget a is packed in the widget b if there exists a chain of widgets a = c1, c2, ..., ck = b, k ≥ 2, for which ci is packed directly to ci + 1 for any 1 ≤ i < k. In Vasya's library the situation when the widget a is packed in the widget a (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error. Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. <image> The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0 × 0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript. Input The first line contains an integer n — the number of instructions (1 ≤ n ≤ 100). Next n lines contain instructions in the language VasyaScript — one instruction per line. There is a list of possible instructions below. * "Widget [name]([x],[y])" — create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. * "HBox [name]" — create a new widget [name] of the type HBox. * "VBox [name]" — create a new widget [name] of the type VBox. * "[name1].pack([name2])" — pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. * "[name].set_border([x])" — set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. * "[name].set_spacing([x])" — set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data. All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget. Output For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator) Examples Input 12 Widget me(50,40) VBox grandpa HBox father grandpa.pack(father) father.pack(me) grandpa.set_border(10) grandpa.set_spacing(20) Widget brother(30,60) father.pack(brother) Widget friend(20,60) Widget uncle(100,20) grandpa.pack(uncle) Output brother 30 60 father 80 60 friend 20 60 grandpa 120 120 me 50 40 uncle 100 20 Input 15 Widget pack(10,10) HBox dummy HBox x VBox y y.pack(dummy) y.set_border(5) y.set_spacing(55) dummy.set_border(10) dummy.set_spacing(20) x.set_border(10) x.set_spacing(10) x.pack(pack) x.pack(dummy) x.pack(pack) x.set_border(0) Output dummy 0 0 pack 10 10 x 40 10 y 10 10 Note In the first sample the widgets are arranged as follows: <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site. He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by a_{i} per day and bring b_{i} dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time. Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true. For example, suppose Mikhail is suggested to work on three projects and a_1 = 6, b_1 = 2, a_2 = 1, b_2 = 3, a_3 = 2, b_3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a_1·2.5 + a_2·0 + a_3·2.5 = 6·2.5 + 1·0 + 2·2.5 = 20 and b_1·2.5 + b_2·0 + b_3·2.5 = 2·2.5 + 3·0 + 6·2.5 = 20. -----Input----- The first line of the input contains three integers n, p and q (1 ≤ n ≤ 100 000, 1 ≤ p, q ≤ 1 000 000) — the number of projects and the required number of experience and money. Each of the next n lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 1 000 000) — the daily increase in experience and daily income for working on the i-th project. -----Output----- Print a real value — the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$. -----Examples----- Input 3 20 20 6 2 1 3 2 6 Output 5.000000000000000 Input 4 1 1 2 3 3 2 2 3 3 2 Output 0.400000000000000 -----Note----- First sample corresponds to the example in the problem statement. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. -----Input----- The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. -----Output----- If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). -----Examples----- Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO -----Note----- In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let $LCM(x, y)$ be the minimum positive integer that is divisible by both $x$ and $y$. For example, $LCM(13, 37) = 481$, $LCM(9, 6) = 18$. You are given two integers $l$ and $r$. Find two integers $x$ and $y$ such that $l \le x < y \le r$ and $l \le LCM(x, y) \le r$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10000$) — the number of test cases. Each test case is represented by one line containing two integers $l$ and $r$ ($1 \le l < r \le 10^9$). -----Output----- For each test case, print two integers: if it is impossible to find integers $x$ and $y$ meeting the constraints in the statement, print two integers equal to $-1$; otherwise, print the values of $x$ and $y$ (if there are multiple valid answers, you may print any of them). -----Example----- Input 4 1 1337 13 69 2 4 88 89 Output 6 7 14 21 2 4 -1 -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. You are given an array A of N integers. You are to fulfill M queries. Each query has one of the following three types: C d : Rotate the array A clockwise by d units. A d : Rotate the array A anticlockwise by d units. R d : Query for the value of the element, currently being the d-th in the array A. ------ Input ------ The first line contains two numbers - N and M respectively. The next line contains N space separated Integers, denoting the array A. Each of the following M lines contains a query in the one of the forms described above. ------ Output ------ For each query of type R output the answer on a separate line. ------ Constraints ------ $1 ≤ N ≤ 100000 $ $1 ≤ M ≤ 100000 $ $1 ≤ d ≤ N, in all the queries$ $1 ≤ elements of A ≤ 1000000$ $The array A and the queries of the type R are 1-based. $  ----- Sample Input 1 ------ 5 5 5 4 3 3 9 R 1 C 4 R 5 A 3 R 2 ----- Sample Output 1 ------ 5 3 3 ----- explanation 1 ------ The initial array : 5 4 3 3 9 The answer for R 1 : 5 The array after C 4 : 9 5 4 3 3 The answer for R 5 : 3 The array after A 3 : 4 3 3 9 5 The answer for R 2 : 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve. The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos. Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up. Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients. Input The first line contains two integers n and d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) — the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1 ≤ a ≤ b ≤ 104) — the size of one low quality photo and of one high quality photo, correspondingly. Next n lines describe the clients. The i-th line contains two integers xi and yi (0 ≤ xi, yi ≤ 105) — the number of low quality photos and high quality photos the i-th client wants, correspondingly. All numbers on all lines are separated by single spaces. Output On the first line print the answer to the problem — the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data. Examples Input 3 10 2 3 1 4 2 1 1 0 Output 2 3 2 Input 3 6 6 6 1 1 1 0 1 0 Output 1 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Take an integer `n (n >= 0)` and a digit `d (0 <= d <= 9)` as an integer. Square all numbers `k (0 <= k <= n)` between 0 and n. Count the numbers of digits `d` used in the writing of all the `k**2`. Call `nb_dig` (or nbDig or ...) the function taking `n` and `d` as parameters and returning this count. #Examples: ``` n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 We are using the digit 1 in 1, 16, 81, 100. The total count is then 4. nb_dig(25, 1): the numbers of interest are 1, 4, 9, 10, 11, 12, 13, 14, 19, 21 which squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441 so there are 11 digits `1` for the squares of numbers between 0 and 25. ``` Note that `121` has twice the digit `1`. Write your solution by modifying this code: ```python def nb_dig(n, d): ``` Your solution should implemented in the function "nb_dig". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number $x$ in an array. For an array $a$ indexed from zero, and an integer $x$ the pseudocode of the algorithm is as follows: BinarySearch(a, x) left = 0 right = a.size() while left < right middle = (left + right) / 2 if a[middle] <= x then left = middle + 1 else right = middle if left > 0 and a[left - 1] == x then return true else return false Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find $x$! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size $n$ such that the algorithm finds $x$ in them. A permutation of size $n$ is an array consisting of $n$ distinct integers between $1$ and $n$ in arbitrary order. Help Andrey and find the number of permutations of size $n$ which contain $x$ at position $pos$ and for which the given implementation of the binary search algorithm finds $x$ (returns true). As the result may be extremely large, print the remainder of its division by $10^9+7$. -----Input----- The only line of input contains integers $n$, $x$ and $pos$ ($1 \le x \le n \le 1000$, $0 \le pos \le n - 1$) — the required length of the permutation, the number to search, and the required position of that number, respectively. -----Output----- Print a single number — the remainder of the division of the number of valid permutations by $10^9+7$. -----Examples----- Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 -----Note----- All possible permutations in the first test case: $(2, 3, 1, 4)$, $(2, 4, 1, 3)$, $(3, 2, 1, 4)$, $(3, 4, 1, 2)$, $(4, 2, 1, 3)$, $(4, 3, 1, 2)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $(0, 0)$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $OX$ or $OY$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification. Alexey wants to make a polyline in such a way that its end is as far as possible from $(0, 0)$. Please help him to grow the tree this way. Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches. -----Input----- The first line contains an integer $n$ ($1 \le n \le 100\,000$) — the number of sticks Alexey got as a present. The second line contains $n$ integers $a_1, \ldots, a_n$ ($1 \le a_i \le 10\,000$) — the lengths of the sticks. -----Output----- Print one integer — the square of the largest possible distance from $(0, 0)$ to the tree end. -----Examples----- Input 3 1 2 3 Output 26 Input 4 1 1 2 2 Output 20 -----Note----- The following pictures show optimal trees for example tests. The squared distance in the first example equals $5 \cdot 5 + 1 \cdot 1 = 26$, and in the second example $4 \cdot 4 + 2 \cdot 2 = 20$. [Image] [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first r_{i} numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m). Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence a_{i} of length n and the description of each manager, that is value r_{i} and his favourite order. You are asked to speed up the process and determine how the final report will look like. -----Input----- The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively. The second line contains n integers a_{i} (|a_{i}| ≤ 10^9) — the initial report before it gets to the first manager. Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers t_{i} and r_{i} ($t_{i} \in \{1,2 \}$, 1 ≤ r_{i} ≤ n), meaning that the i-th manager sorts the first r_{i} numbers either in the non-descending (if t_{i} = 1) or non-ascending (if t_{i} = 2) order. -----Output----- Print n integers — the final report, which will be passed to Blake by manager number m. -----Examples----- Input 3 1 1 2 3 2 2 Output 2 1 3 Input 4 2 1 2 4 3 2 3 1 2 Output 2 4 1 3 -----Note----- In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form. In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. <image> The International Clown and Pierrot Competition (ICPC), is one of the most distinguished and also the most popular events on earth in the show business. One of the unique features of this contest is the great number of judges that sometimes counts up to one hundred. The number of judges may differ from one contestant to another, because judges with any relationship whatsoever with a specific contestant are temporarily excluded for scoring his/her performance. Basically, scores given to a contestant's performance by the judges are averaged to decide his/her score. To avoid letting judges with eccentric viewpoints too much influence the score, the highest and the lowest scores are set aside in this calculation. If the same highest score is marked by two or more judges, only one of them is ignored. The same is with the lowest score. The average, which may contain fractions, are truncated down to obtain final score as an integer. You are asked to write a program that computes the scores of performances, given the scores of all the judges, to speed up the event to be suited for a TV program. Input The input consists of a number of datasets, each corresponding to a contestant's performance. There are no more than 20 datasets in the input. A dataset begins with a line with an integer n, the number of judges participated in scoring the performance (3 ≤ n ≤ 100). Each of the n lines following it has an integral score s (0 ≤ s ≤ 1000) marked by a judge. No other characters except for digits to express these numbers are in the input. Judges' names are kept secret. The end of the input is indicated by a line with a single zero in it. Output For each dataset, a line containing a single decimal integer indicating the score for the corresponding performance should be output. No other characters should be on the output line. Example Input 3 1000 342 0 5 2 2 9 11 932 5 300 1000 0 200 400 8 353 242 402 274 283 132 402 523 0 Output 342 7 300 326 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have integer $n$. Calculate how many ways are there to fully cover belt-like area of $4n-2$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $2$ coverings are different if some $2$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one. Please look at pictures below for better understanding. $\theta$ On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. [Image] These are the figures of the area you want to fill for $n = 1, 2, 3, 4$. You have to answer $t$ independent test cases. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^{4}$) — the number of test cases. Each of the next $t$ lines contains a single integer $n$ ($1 \le n \le 10^{9}$). -----Output----- For each test case, print the number of ways to fully cover belt-like area of $4n-2$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $10^{18}$. -----Example----- Input 2 2 1 Output 2 1 -----Note----- In the first test case, there are the following $2$ ways to fill the area: [Image] In the second test case, there is a unique way to fill the area: [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has g_{i} Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation f of {1, 2, ..., m}, such that f(x) = y means that a Pokemon of type x evolves into a Pokemon of type y. The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol. Two evolution plans f_1 and f_2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f_1(i) ≠ f_2(i). Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 10^9 + 7. -----Input----- The first line contains two integers n and m (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^6) — the number of gyms and the number of Pokemon types. The next n lines contain the description of Pokemons in the gyms. The i-th of these lines begins with the integer g_{i} (1 ≤ g_{i} ≤ 10^5) — the number of Pokemon in the i-th gym. After that g_{i} integers follow, denoting types of the Pokemons in the i-th gym. Each of these integers is between 1 and m. The total number of Pokemons (the sum of all g_{i}) does not exceed 5·10^5. -----Output----- Output the number of valid evolution plans modulo 10^9 + 7. -----Examples----- Input 2 3 2 1 2 2 2 3 Output 1 Input 1 3 3 1 2 3 Output 6 Input 2 4 2 1 2 3 2 3 4 Output 2 Input 2 2 3 2 2 1 2 1 2 Output 1 Input 3 7 2 1 2 2 3 4 3 5 6 7 Output 24 -----Note----- In the first case, the only possible evolution plan is: $1 \rightarrow 1,2 \rightarrow 2,3 \rightarrow 3$ In the second case, any permutation of (1, 2, 3) is valid. In the third case, there are two possible plans: $1 \rightarrow 1,2 \rightarrow 2,3 \rightarrow 4,4 \rightarrow 3$ $1 \rightarrow 1,2 \rightarrow 2,3 \rightarrow 3,4 \rightarrow 4$ In the fourth case, the only possible evolution plan is: $1 \rightarrow 1,2 \rightarrow 2$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function which reduces fractions to their simplest form! Fractions will be presented as an array/tuple (depending on the language), and the reduced fraction must be returned as an array/tuple: ``` input: [numerator, denominator] output: [newNumerator, newDenominator] example: [45, 120] --> [3, 8] ``` All numerators and denominators will be positive integers. Note: This is an introductory Kata for a series... coming soon! Write your solution by modifying this code: ```python def reduce_fraction(fraction): ``` Your solution should implemented in the function "reduce_fraction". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task. Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the f_{i}-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator). What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor? -----Input----- The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator. The next line contains n integers: f_1, f_2, ..., f_{n} (2 ≤ f_{i} ≤ 2000), where f_{i} denotes the target floor of the i-th person. -----Output----- Output a single integer — the minimal time needed to achieve the goal. -----Examples----- Input 3 2 2 3 4 Output 8 Input 4 2 50 100 50 100 Output 296 Input 10 3 2 2 2 2 2 2 2 2 2 2 Output 8 -----Note----- In first sample, an optimal solution is: The elevator takes up person #1 and person #2. It goes to the 2nd floor. Both people go out of the elevator. The elevator goes back to the 1st floor. Then the elevator takes up person #3. And it goes to the 2nd floor. It picks up person #2. Then it goes to the 3rd floor. Person #2 goes out. Then it goes to the 4th floor, where person #3 goes out. The elevator goes back to the 1st floor. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her. Given an array $a$ of length $n$, consisting only of the numbers $0$ and $1$, and the number $k$. Exactly $k$ times the following happens: Two numbers $i$ and $j$ are chosen equiprobable such that ($1 \leq i < j \leq n$). The numbers in the $i$ and $j$ positions are swapped. Sonya's task is to find the probability that after all the operations are completed, the $a$ array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem. It can be shown that the desired probability is either $0$ or it can be represented as $\dfrac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \not\equiv 0~\pmod {10^9+7}$. -----Input----- The first line contains two integers $n$ and $k$ ($2 \leq n \leq 100, 1 \leq k \leq 10^9$) — the length of the array $a$ and the number of operations. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$) — the description of the array $a$. -----Output----- If the desired probability is $0$, print $0$, otherwise print the value $P \cdot Q^{-1}$ $\pmod {10^9+7}$, where $P$ and $Q$ are defined above. -----Examples----- Input 3 2 0 1 0 Output 333333336 Input 5 1 1 1 1 0 0 Output 0 Input 6 4 1 0 0 1 1 0 Output 968493834 -----Note----- In the first example, all possible variants of the final array $a$, after applying exactly two operations: $(0, 1, 0)$, $(0, 0, 1)$, $(1, 0, 0)$, $(1, 0, 0)$, $(0, 1, 0)$, $(0, 0, 1)$, $(0, 0, 1)$, $(1, 0, 0)$, $(0, 1, 0)$. Therefore, the answer is $\dfrac{3}{9}=\dfrac{1}{3}$. In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is $0$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers. He has created a method to know how strong his army is. Let the i-th soldier’s strength be a_{i}. For some k he calls i_1, i_2, ..., i_{k} a clan if i_1 < i_2 < i_3 < ... < i_{k} and gcd(a_{i}_1, a_{i}_2, ..., a_{i}_{k}) > 1 . He calls the strength of that clan k·gcd(a_{i}_1, a_{i}_2, ..., a_{i}_{k}). Then he defines the strength of his army by the sum of strengths of all possible clans. Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (10^9 + 7). Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it. -----Input----- The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000000) — denoting the strengths of his soldiers. -----Output----- Print one integer — the strength of John Snow's army modulo 1000000007 (10^9 + 7). -----Examples----- Input 3 3 3 1 Output 12 Input 4 2 3 4 6 Output 39 -----Note----- In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 9900 * -2 × 107 ≤ di ≤ 2 × 107 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E). |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 |V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge. Output If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print NEGATIVE CYCLE in a line. Otherwise, print D0,0 D0,1 ... D0,|V|-1 D1,0 D1,1 ... D1,|V|-1 : D|V|-1,0 D1,1 ... D|V|-1,|V|-1 The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs. Examples Input 4 6 0 1 1 0 2 5 1 2 2 1 3 4 2 3 1 3 2 7 Output 0 1 3 4 INF 0 2 3 INF INF 0 1 INF INF 7 0 Input 4 6 0 1 1 0 2 -5 1 2 2 1 3 4 2 3 1 3 2 7 Output 0 1 -5 -4 INF 0 2 3 INF INF 0 1 INF INF 7 0 Input 4 6 0 1 1 0 2 5 1 2 2 1 3 4 2 3 1 3 2 -7 Output NEGATIVE CYCLE Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is an infinite 2-dimensional grid. The robot stands in cell $(0, 0)$ and wants to reach cell $(x, y)$. Here is a list of possible commands the robot can execute: move north from cell $(i, j)$ to $(i, j + 1)$; move east from cell $(i, j)$ to $(i + 1, j)$; move south from cell $(i, j)$ to $(i, j - 1)$; move west from cell $(i, j)$ to $(i - 1, j)$; stay in cell $(i, j)$. The robot wants to reach cell $(x, y)$ in as few commands as possible. However, he can't execute the same command two or more times in a row. What is the minimum number of commands required to reach $(x, y)$ from $(0, 0)$? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of testcases. Each of the next $t$ lines contains two integers $x$ and $y$ ($0 \le x, y \le 10^4$) — the destination coordinates of the robot. -----Output----- For each testcase print a single integer — the minimum number of commands required for the robot to reach $(x, y)$ from $(0, 0)$ if no command is allowed to be executed two or more times in a row. -----Examples----- Input 5 5 5 3 4 7 1 0 0 2 0 Output 10 7 13 0 3 -----Note----- The explanations for the example test: We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively. In the first test case, the robot can use the following sequence: NENENENENE. In the second test case, the robot can use the following sequence: NENENEN. In the third test case, the robot can use the following sequence: ESENENE0ENESE. In the fourth test case, the robot doesn't need to go anywhere at all. In the fifth test case, the robot can use the following sequence: E0E. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: $a_{1} OR a_{2} OR \ldots OR a_{k}$ where $a_{i} \in \{0,1 \}$ is equal to 1 if some a_{i} = 1, otherwise it is equal to 0. Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as A_{ij}. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula: [Image]. (B_{ij} is OR of all elements in row i and column j of matrix A) Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large. -----Input----- The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively. The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1). -----Output----- In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one. -----Examples----- Input 2 2 1 0 0 0 Output NO Input 2 3 1 1 1 1 1 1 Output YES 1 1 1 1 1 1 Input 2 3 0 1 0 1 1 1 Output YES 0 0 0 0 1 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. $n$ heroes fight against each other in the Arena. Initially, the $i$-th hero has level $a_i$. Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute). When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $1$. The winner of the tournament is the first hero that wins in at least $100^{500}$ fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament. Calculate the number of possible winners among $n$ heroes. -----Input----- The first line contains one integer $t$ ($1 \le t \le 500$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $n$ ($2 \le n \le 100$) — the number of heroes. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the initial level of the $i$-th hero. -----Output----- For each test case, print one integer — the number of possible winners among the given $n$ heroes. -----Examples----- Input 3 3 3 2 2 2 5 5 4 1 3 3 7 Output 1 0 3 -----Note----- In the first test case of the example, the only possible winner is the first hero. In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters $s_i$ and $s_{i+1}$, and if $s_i$ is 1 and $s_{i + 1}$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing. Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $s$ as clean as possible. He thinks for two different strings $x$ and $y$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner. Now you should answer $t$ test cases: for the $i$-th test case, print the cleanest possible string that Lee can get by doing some number of moves. Small reminder: if we have two strings $x$ and $y$ of the same length then $x$ is lexicographically smaller than $y$ if there is a position $i$ such that $x_1 = y_1$, $x_2 = y_2$,..., $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$. -----Input----- The first line contains the integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Next $2t$ lines contain test cases — one per two lines. The first line of each test case contains the integer $n$ ($1 \le n \le 10^5$) — the length of the string $s$. The second line contains the binary string $s$. The string $s$ is a string of length $n$ which consists only of zeroes and ones. It's guaranteed that sum of $n$ over test cases doesn't exceed $10^5$. -----Output----- Print $t$ answers — one per test case. The answer to the $i$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero). -----Example----- Input 5 10 0001111111 4 0101 8 11001101 10 1110000000 1 1 Output 0001111111 001 01 0 1 -----Note----- In the first test case, Lee can't perform any moves. In the second test case, Lee should erase $s_2$. In the third test case, Lee can make moves, for example, in the following order: 11001101 $\rightarrow$ 1100101 $\rightarrow$ 110101 $\rightarrow$ 10101 $\rightarrow$ 1101 $\rightarrow$ 101 $\rightarrow$ 01. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's imagine we have a popular online RPG. A player begins with a score of 0 in class E5. A1 is the highest level a player can achieve. Now let's say the players wants to rank up to class E4. To do so the player needs to achieve at least 100 points to enter the qualifying stage. Write a script that will check to see if the player has achieved at least 100 points in his class. If so, he enters the qualifying stage. In that case, we return, ```"Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up."```. Otherwise return, ```False/false``` (according to the language n use). NOTE: Remember, in C# you have to cast your output value to Object type! Write your solution by modifying this code: ```python def playerRankUp(pts): ``` Your solution should implemented in the function "playerRankUp". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.