source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Andrii is good in Math, but not in Programming. He is asking you to solve following problem: Given an integer number N and two sets of integer A and B. Let set A contain all numbers from 1 to N and set B contain all numbers from N + 1 to 2N. Multiset C contains all sums a + b such that a belongs to A and b belongs to B. Note that multiset may contain several elements with the same values. For example, if N equals to three, then A = {1, 2, 3}, B = {4, 5, 6} and C = {5, 6, 6, 7, 7, 7, 8, 8, 9}. Andrii has M queries about multiset C. Every query is defined by a single integer q. Andrii wants to know the number of times q is contained in C. For example, number 6 is contained two times, 1 is not contained in C at all. Please, help Andrii to answer all the queries. -----Input----- The first line of the input contains two integers N and M. Each of the next M line contains one integer q, the query asked by Andrii. -----Output----- Output the answer for each query in separate lines as in example. -----Constraints----- - 1 ≤ N ≤ 109 - 1 ≤ M ≤ 105 - 1 ≤ q ≤ 3N -----Example----- Input: 3 5 6 2 9 7 5 Output: 2 0 1 3 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import math; from math import gcd,sqrt,floor,factorial,ceil from bisect import bisect_left,bisect_right import bisect; import sys; from sys import stdin,stdout import os sys.setrecursionlimit(pow(10,7)) import collections from collections import defaultdict,Counter from statistics import median # input=stdin.readline # print=stdout.write from queue import Queue inf = float("inf") from operator import neg; n,m=map(int,input().split()) for i in range(m): k=int(input()) print(max(0,min(k-n-1,3*n+1-k))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Karen has just arrived at school, and she has a math test today! [Image] The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition. Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa. The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test. Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row? Since this number can be quite large, output only the non-negative remainder after dividing it by 10^9 + 7. -----Input----- The first line of input contains a single integer n (1 ≤ n ≤ 200000), the number of numbers written on the first row. The next line contains n integers. Specifically, the i-th one among these is a_{i} (1 ≤ a_{i} ≤ 10^9), the i-th number on the first row. -----Output----- Output a single integer on a line by itself, the number on the final row after performing the process above. Since this number can be quite large, print only the non-negative remainder after dividing it by 10^9 + 7. -----Examples----- Input 5 3 6 9 12 15 Output 36 Input 4 3 7 5 2 Output 1000000006 -----Note----- In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15. Karen performs the operations as follows: [Image] The non-negative remainder after dividing the final number by 10^9 + 7 is still 36, so this is the correct output. In the second test case, the numbers written on the first row are 3, 7, 5 and 2. Karen performs the operations as follows: [Image] The non-negative remainder after dividing the final number by 10^9 + 7 is 10^9 + 6, so this is the correct output. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #!/usr/bin/env pypy3 import math def make_nCr_mod(max_n=2*10**5 + 100, mod=10**9 + 7): fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1) fact[0] = 1 for i in range(max_n): fact[i + 1] = fact[i] * (i + 1) % mod inv_fact[-1] = pow(fact[-1], mod - 2, mod) for i in reversed(range(max_n)): inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod def nCr_mod(n, r): res = 1 while n or r: a, b = n % mod, r % mod if a < b: return 0 res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod n //= mod r //= mod return res return nCr_mod nCr_mod = make_nCr_mod() MODULUS = 10**9+7 input() A = input().split(' ') A = list(map(int, A)) if len(A) == 1: print(A[0]) return if len(A) % 2 == 1: new_A = [] next_plus = True for i in range(len(A) - 1): if next_plus: new_A += [A[i] + A[i+1]] else: new_A += [A[i] - A[i+1]] next_plus = not next_plus A = new_A if len(A) % 4 == 2: new_A = [] for i in range(len(A) // 2): new_A += [A[2*i] + A[2*i+1]] A = new_A else: new_A = [] for i in range(len(A) // 2): new_A += [A[2*i] - A[2*i+1]] A = new_A # binomial sum N = len(A)-1 ret = 0 for i in range(N+1): ret += A[i]*nCr_mod(N, i) ret = ret % MODULUS print(ret) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Calculate the power of an army of numbers from 1 to $N$, both included. -----Input:----- - First line will contain a single integer $N$. -----Output:----- For each testcase, output in a single line containing the answer. -----Constraints----- - $1 \leq N \leq 5000$ -----Sample Input:----- 24 -----Sample Output:----- 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here #powerful numbers n = int(input()) plist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313] power = 1 for i in range(2,n+1,1): pdiv = [] count = 0 for p in plist: if i>=p and i%p==0: pdiv.append(p) for pd in pdiv: if i%(pd**2)==0: count+=1 if count==len(pdiv) and count!=0: power+=1 print(power) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions: - Every group contains between A and B people, inclusive. - Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds. Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7. -----Constraints----- - 1≤N≤10^3 - 1≤A≤B≤N - 1≤C≤D≤N -----Input----- The input is given from Standard Input in the following format: N A B C D -----Output----- Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7. -----Sample Input----- 3 1 3 1 2 -----Sample Output----- 4 There are four ways to divide the people: - (1,2),(3) - (1,3),(2) - (2,3),(1) - (1,2,3) The following way to divide the people does not count: (1),(2),(3). This is because it only satisfies the first condition and not the second. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): mod = 10**9+7 inv_n = [0]*1001 nCr = [[1]*(i+1) for i in range(1001)] for i in range(1001): inv_n[i] = pow(i, mod-2, mod) for i in range(2, 1001): for j in range(1, i): nCr[i][j] = (nCr[i-1][j-1]+nCr[i-1][j]) % mod n, a, b, c, d = list(map(int, input().split())) dp = [0]*(n+1) dp[0] = 1 for A in range(b, a-1, -1): dp2 = [i for i in dp] for N in range(n-c*A, -1, -1): e = dp[N] if e: temp = 1 for C in range(1, c): temp = temp*nCr[n-N-(C-1)*A][A]*inv_n[C] % mod for C in range(c, min(d, (n-N)//A)+1): temp = temp*nCr[n-N-(C-1)*A][A]*inv_n[C] % mod dp2[N+C*A] = (dp2[N+C*A]+temp*e) % mod dp = dp2 print((dp[-1])) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order. Iroha is looking for X,Y,Z-Haiku (defined below) in integer sequences. Consider all integer sequences of length N whose elements are between 1 and 10, inclusive. Out of those 10^N sequences, how many contain an X,Y,Z-Haiku? Here, an integer sequence a_0, a_1, ..., a_{N-1} is said to contain an X,Y,Z-Haiku if and only if there exist four indices x, y, z, w (0 ≦ x < y < z < w ≦ N) such that all of the following are satisfied: - a_x + a_{x+1} + ... + a_{y-1} = X - a_y + a_{y+1} + ... + a_{z-1} = Y - a_z + a_{z+1} + ... + a_{w-1} = Z Since the answer can be extremely large, print the number modulo 10^9+7. -----Constraints----- - 3 ≦ N ≦ 40 - 1 ≦ X ≦ 5 - 1 ≦ Y ≦ 7 - 1 ≦ Z ≦ 5 -----Input----- The input is given from Standard Input in the following format: N X Y Z -----Output----- Print the number of the sequences that contain an X,Y,Z-Haiku, modulo 10^9+7. -----Sample Input----- 3 5 7 5 -----Sample Output----- 1 Here, the only sequence that contains a 5,7,5-Haiku is [5, 7, 5]. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline n,X,Y,Z = list(map(int,read().split())) N = 1<<(X+Y+Z) NX = 1<<X NY = 1<<(X+Y) NZ = 1<<(X+Y+Z) MX = (1<<X) - 1 MY = (1<<(Y+X)) - (1<<X) MZ = (1<<(X+Y+Z)) - (1<<(Y+X)) MMX = MX<<1 MMY = MY<<1 MMZ = MZ<<1 dp = [0]*N dp[1] = 1 MOD = 10**9+7 for _ in range(n): ndp = [0]*N #cnt = 0 #bad = 0 for mask in range(N): if dp[mask]==0: continue mx = mask&MX my = mask&MY mz = mask&MZ for j in range(1,11): nmx = mx << j nmx &= MMX nmy = my << j nmy &= MMY nmz = mz << j nmz &= MMZ nmask = nmx|nmy|nmz|1 if not nmask&(1<<(X+Y+Z)): ndp[nmask] += dp[mask] ndp[nmask] %= MOD dp = ndp #print(sum(dp),"sum") ans = (pow(10,n,MOD)-sum(dp)) print((ans%MOD)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle. [Image]   It's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row 1 while the second attendant serves row 3. When both rows are done they move one row forward: the first attendant serves row 2 while the second attendant serves row 4. Then they move three rows forward and the first attendant serves row 5 while the second attendant serves row 7. Then they move one row forward again and so on. Flight attendants work with the same speed: it takes exactly 1 second to serve one passenger and 1 second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one — in seat 'c'. Assume that all seats are occupied. Vasya has seat s in row n and wants to know how many seconds will pass before he gets his lunch. -----Input----- The only line of input contains a description of Vasya's seat in the format ns, where n (1 ≤ n ≤ 10^18) is the index of the row and s is the seat in this row, denoted as letter from 'a' to 'f'. The index of the row and the seat are not separated by a space. -----Output----- Print one integer — the number of seconds Vasya has to wait until he gets his lunch. -----Examples----- Input 1f Output 1 Input 2d Output 10 Input 4a Output 11 Input 5e Output 18 -----Note----- In the first sample, the first flight attendant serves Vasya first, so Vasya gets his lunch after 1 second. In the second sample, the flight attendants will spend 6 seconds to serve everyone in the rows 1 and 3, then they will move one row forward in 1 second. As they first serve seats located to the right of the aisle in order from window to aisle, Vasya has to wait 3 more seconds. The total is 6 + 1 + 3 = 10. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python seat = input() time_to = {'a': 4, 'f': 1, 'b': 5, 'e': 2, 'c': 6, 'd': 3} col = seat[-1] row = int(seat[:-1]) row -= 1 blocks_to_serve = row // 4 time = (6 * 2 + 4) * blocks_to_serve if row % 2 == 1: time += 6 + 1 time += time_to[col] print(time) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given the array of integer numbers a_0, a_1, ..., a_{n} - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array. -----Input----- The first line contains integer n (1 ≤ n ≤ 2·10^5) — length of the array a. The second line contains integer elements of the array separated by single spaces ( - 10^9 ≤ a_{i} ≤ 10^9). -----Output----- Print the sequence d_0, d_1, ..., d_{n} - 1, where d_{i} is the difference of indices between i and nearest j such that a_{j} = 0. It is possible that i = j. -----Examples----- Input 9 2 1 0 3 0 0 3 2 4 Output 2 1 0 1 0 0 1 2 3 Input 5 0 1 2 3 4 Output 0 1 2 3 4 Input 7 5 6 0 1 -2 3 4 Output 2 1 0 1 2 3 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python inf = 10 ** 6 n = int(input()) a = list(map(int, input().split())) dist = [inf] * n for i in range(len(a)): if not a[i]: dist[i] = 0 cur = 1 i1 = i while i1 - 1 > - 1 and a[i1 - 1] != 0: dist[i1 - 1] = min(dist[i1 - 1], cur) i1 -= 1 cur += 1 i1 = i cur = 1 while i1 + 1 < n and a[i1 + 1] != 0: dist[i1 + 1] = min(dist[i1 + 1], cur) i1 += 1 cur += 1 print(*dist) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In my town ,there live a coder named Chef . He is a cool programmer . One day , he participate in a programming contest ,the contest give him only one problem . If he can’t solve the problem ,the problem setter will kill him . But the round allow you to help Chef. Can you save the life of Chef from problem setter ? :p You are given two point of a straightline in X and Y axis and they are A(x1 , y1) and B(x2 ,y2) . Problem setter will give you another point C(x3 , y3) . If C exist in AB straightline ,then print “YES” . Otherwise ,print “NO” in first line and print the minimum distance from C to AB straightline in second line . Please , save the life of Chef . Note : It is not possible that A and B point is similar . -----Input:----- The first line of the input contains a single integer t (1≤t≤100) — the number of test cases . Each test case starts with four integers( x1, y1 , x2 , y2 ) in first line . Next line contains a single number q ,the number of queries . Each query contains two integers ( x3 ,y3 ) -----Output:----- Print , q number of “YES” or “NO” (as it mentioned above) in each test case .For every test case , print “Test case : i ” ( 1<= i <=T ) -----Constraints----- -1000 <= x1 , y1 , x2 , y2 , x3 , y3 <= 1000 -----Sample Input:----- 2 3 5 6 5 2 4 5 6 8 3 4 7 10 1 7 4 -----Sample Output:----- Test case : 1 YES NO 3.000000 Test case : 2 NO 3.328201 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from math import sqrt for i in range(int(input())): x1,y1,x2,y2=list(map(float,input().split())) m=(y2-y1)/(x2-x1) c=y2-m*x2 print('Test case : ',i+1) q=int(input()) for i in range(q): x3,y3=list(map(float,input().split())) if(y3-m*x3-c==0): print("YES") else: d=(abs(y3-m*x3-c))/sqrt(1+m*m) print("NO") print("%.6f" % d) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Laxman, a great Mathematician and Thinker, gives Sugreev an integer, $N$, and asks him to make an array $A$ of length $N$, such that $\sum A$i$^3 = X^2$, to prove the purity of the bond of his friendship with Ram. Sugreev is facing difficulty in forming the array. So, help Sugreev to form this array. -----Note:----- - $A$i must be an integer between $1$ to $10^3$ (both inclusive), where $A$i denotes the $i$$th$ element of the array, $A$. - $X$ must be an integer (Any Integer). - If there are multiple solutions, satisfying the condition, you can print any "one" solution. -----Input:----- - First line will contain $T$, number of testcases. Then, the testcases follow. - Each testcase contains a single line of input, integer $N$. -----Output:----- For each testcase, output in a single line, array $A$ of $N$ integers, where each element is between $1$ to $1000$ (both inclusive), satisfying the equation $\sum A$i$^3 = X^2$, where $X$ is "any" integer. -----Constraints:----- - $1 \leq T \leq 10^3$ - $1 \leq N \leq 10^3$ -----Sample Input:----- 2 1 6 -----Sample Output:----- 4 5 10 5 10 5 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t = int(input()) while(t>0): n = int(input()) k=1 while(k<=n): print(k, end=' ') k+=1 print('\n') t-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given sequences A and B consisting of non-negative integers. The lengths of both A and B are N, and the sums of the elements in A and B are equal. The i-th element in A is A_i, and the i-th element in B is B_i. Tozan and Gezan repeats the following sequence of operations: - If A and B are equal sequences, terminate the process. - Otherwise, first Tozan chooses a positive element in A and decrease it by 1. - Then, Gezan chooses a positive element in B and decrease it by 1. - Then, give one candy to Takahashi, their pet. Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible. Find the number of candies given to Takahashi when both of them perform the operations optimally. -----Constraints----- - 1 \leq N \leq 2 × 10^5 - 0 \leq A_i,B_i \leq 10^9(1\leq i\leq N) - The sums of the elements in A and B are equal. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N A_1 B_1 : A_N B_N -----Output----- Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally. -----Sample Input----- 2 1 2 3 2 -----Sample Output----- 2 When both Tozan and Gezan perform the operations optimally, the process will proceed as follows: - Tozan decreases A_1 by 1. - Gezan decreases B_1 by 1. - One candy is given to Takahashi. - Tozan decreases A_2 by 1. - Gezan decreases B_1 by 1. - One candy is given to Takahashi. - As A and B are equal, the process is terminated. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #from collections import deque,defaultdict printn = lambda x: print(x,end='') inn = lambda : int(input()) inl = lambda: list(map(int, input().split())) inm = lambda: map(int, input().split()) ins = lambda : input().strip() DBG = True # and False BIG = 10**18 R = 10**9 + 7 #R = 998244353 def ddprint(x): if DBG: print(x) n = inn() a = [] b = [] xb = 10**9+1 for i in range(n): aa,bb = inm() a.append(aa) b.append(bb) if aa>bb and xb>bb: xb = bb xi = i if n==-2 and a[0]==1: 3/0 print(0 if xb>10**9 else sum(a)-b[xi]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: “I am not in danger, Skyler. I am the danger. A guy opens his door and gets shot, and you think that of me? No! I am the one who knocks!” Skyler fears Walter and ponders escaping to Colorado. Walter wants to clean his lab as soon as possible and then go back home to his wife. In order clean his lab, he has to achieve cleaning level of lab as $Y$. The current cleaning level of the lab is $X$. He must choose one positive odd integer $a$ and one positive even integer $b$. Note that, he cannot change $a$ or $b$ once he starts cleaning. He can perform any one of the following operations for one round of cleaning: - Replace $X$ with $X+a$. - Replace $X$ with $X-b$. Find minimum number of rounds (possibly zero) to make lab clean. -----Input:----- - First line will contain $T$, number of test cases. $T$ testcases follow : - Each test case contains two space separated integers $X, Y$. -----Output:----- For each test case, output an integer denoting minimum number of rounds to clean the lab. -----Constraints----- - $1 \leq T \leq 10^5$ - $ |X|,|Y| \leq 10^9$ -----Sample Input:----- 3 0 5 4 -5 0 10000001 -----Sample Output:----- 1 2 1 -----EXPLANATION:----- - For the first testcase, you can convert $X$ to $Y$ by choosing $a=5$ and $b=2$. It will cost minimum of $1$ cleaning round. You can select any other combination of $a, b$ satisfying above condition but will take minimum of $1$ cleaning round in any case. - For the second testcase, you can convert $X$ to $Y$ by choosing $a=1$ and $b=10$. In first round they will replace $X$ to $X+a$ and then in second round replace to $X-b$. You can perform only one operation in one round. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for i in range(t): ans=0 x,y=list(map(int,input().split())) if y>x: if (y-x)%4==0:ans=3 elif (y-x)%2==0: ans=2 else: ans=1 if y<x: if (y-x)%2==0:ans=1 else: ans=2 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year. -----Input----- The first line contains integer number n (1 ≤ n ≤ 10^9) — current year in Berland. -----Output----- Output amount of years from the current year to the next lucky one. -----Examples----- Input 4 Output 1 Input 201 Output 99 Input 4000 Output 1000 -----Note----- In the first example next lucky year is 5. In the second one — 300. In the third — 5000. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): s = input() n = len(s) t = int(str(int(s[0]) + 1) + '0' * (n - 1)) print(t - int(s)) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to d kilometers. Vasiliy's car is not new — it breaks after driven every k kilometers and Vasiliy needs t seconds to repair it. After repairing his car Vasiliy can drive again (but after k kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station. To drive one kilometer on car Vasiliy spends a seconds, to walk one kilometer on foot he needs b seconds (a < b). Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot. -----Input----- The first line contains 5 positive integers d, k, a, b, t (1 ≤ d ≤ 10^12; 1 ≤ k, a, b, t ≤ 10^6; a < b), where: d — the distance from home to the post office; k — the distance, which car is able to drive before breaking; a — the time, which Vasiliy spends to drive 1 kilometer on his car; b — the time, which Vasiliy spends to walk 1 kilometer on foot; t — the time, which Vasiliy spends to repair his car. -----Output----- Print the minimal time after which Vasiliy will be able to reach the post office. -----Examples----- Input 5 2 1 4 10 Output 14 Input 5 2 1 4 5 Output 13 -----Note----- In the first example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds) and then to walk on foot 3 kilometers (in 12 seconds). So the answer equals to 14 seconds. In the second example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds), then repair his car (in 5 seconds) and drive 2 kilometers more on the car (in 2 seconds). After that he needs to walk on foot 1 kilometer (in 4 seconds). So the answer equals to 13 seconds. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python d, k, a, b, t = list(map(int, input().split())) t1 = d * b t2 = d * a + ((d - 1) // k) * t t3 = max(0, d - k) * b + min(k, d) * a dd = d % k d1 = d - dd t4 = d1 * a + max(0, (d1 // k - 1) * t) + dd * b print(min([t1, t2, t3, t4])) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has decided to start home delivery from his restaurant. He hopes that he will get a lot of orders for delivery, however there is a concern. He doesn't have enough work forces for all the deliveries. For this he has came up with an idea - he will group together all those orders which have to be delivered in nearby areas. In particular, he has identified certain bidirectional roads which he calls as fast roads. They are short and usually traffic free, so the fast travel is possible along these roads. His plan is that he will send orders to locations A and B together if and only if it is possible to travel between A and B using only fast roads. Your task is, given the configuration of fast roads, identify which orders are to be sent together. -----Input----- First line of input contains an integer T, the number of test cases. Then T test cases follow. First line of each test case contains two space separated integers N and M, denoting number of locations and the number of fast roads. Then M lines follow each containing two space separated integers A and B, denoting that there is a fast road between locations A and B. Assume that locations are indexed by numbers from 0 to N-1. Next line contains an integer Q denoting the number of queries. Each of the next Q lines contain two integers X and Y. For each query you have to find out if orders meant for locations X and Y are to be sent together or not. Note that there might be multiple fast roads between same pair of locations, also there might be a fast road that links a location to itself. -----Output----- For each test case print Q lines - one for each query. Output "YO" if the orders are to be delivered together and "NO" otherwise (quotes for clarity). -----Constraints----- 1 ≤ T ≤ 100 1 ≤ N ≤ 100 1 ≤ M ≤ 1000 0 ≤ A, B, X, Y ≤ N-1 1 ≤ Q ≤ 3000 -----Example----- Input: 1 4 2 0 1 1 2 3 0 2 0 3 2 1 Output: YO NO YO -----Warning!----- There are large input and output files in this problem. Make sure you use fast enough I/O methods. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from sys import stdin, stdout from math import ceil def solve(): for _ in range(int(input())): n, m = map(int, stdin.readline().split()) par = [i for i in range(n)] for i in range(m): ta, tb = map(int, stdin.readline().strip().split()) a, b = min(ta, tb), max(ta, tb) for j in range(n): if par[j] == par[b] and j != b: par[j] = par[a] par[b] = par[a] q = int(input()) while q: q -= 1 x, y = map(int, stdin.readline().split()) if par[x] == par[y]: print("YO") else: print("NO") def __starting_point(): solve() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef Al Gorithm was reading a book about climate and oceans when he encountered the word “glaciological”. He thought it was quite curious, because it has the following interesting property: For every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ 1. Chef Al was happy about this and called such words 1-good words. He also generalized the concept: He said a word was K-good if for every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ K. Now, the Chef likes K-good words a lot and so was wondering: Given some word w, how many letters does he have to remove to make it K-good? -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each test case consists of a single line containing two things: a word w and an integer K, separated by a space. -----Output----- For each test case, output a single line containing a single integer: the minimum number of letters he has to remove to make the word K-good. -----Constraints----- - 1 ≤ T ≤ 30 - 1 ≤ |w| ≤ 105 - 0 ≤ K ≤ 105 - w contains only lowercase English letters. -----Example----- Input: 4 glaciological 1 teammate 0 possessions 3 defenselessness 3 Output: 0 0 1 2 -----Explanation----- Example case 1. The word “glaciological” is already 1-good, so the Chef doesn't have to remove any letter. Example case 2. Similarly, “teammate” is already 0-good. Example case 3. The word “possessions” is 4-good. To make it 3-good, the Chef can remove the last s to make “possession”. Example case 4. The word “defenselessness” is 4-good. To make it 3-good, Chef Al can remove an s and an e to make, for example, “defenslesness”. Note that the word doesn't have to be a valid English word. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import bisect for _ in range(int(input())): w,k=map(str, input().split()) k=int(k) n=len(w) w=list(w) w.sort() w.append('0') c=1 l=0 l1=[] l2=[] for i in range(1, n+1): if w[i]==w[i-1]: c+=1 else: a=bisect.bisect_left(l1, c) if a==l: l1.append(c) l2.append(1) l+=1 elif l1[a]==c: l2[a]=l2[a]+1 else: l1.insert(a, c) l2.insert(a, 1) l+=1 c=1 a=l1[-1]-l1[0] if a<=k: print(0) else: ans=n for i in range(l): temp=l2[i]*l1[i] for j in range(i+1, l): p=l1[j]-l1[i] if p<=k: temp+=(l2[j]*l1[j]) else: p1=p-k temp+=(l2[j]*(l1[j]-p1)) ans=min(ans, (n-temp)) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After six days, professor GukiZ decided to give more candies to his students. Like last time, he has $N$ students, numbered $1$ through $N$. Let's denote the number of candies GukiZ gave to the $i$-th student by $p_i$. As GukiZ has a lot of students, he does not remember all the exact numbers of candies he gave to the students. He only remembers the following properties of the sequence $p$: - The numbers of candies given to each of the first $K$ students ($p_1, p_2, \dots, p_K$) are known exactly. - All elements of the sequence $p$ are distinct and positive. - GukiZ didn't give more than $x$ candies to any student (the maximum value in the sequence $p$ is not greater than $x$). - For each student $i$, there is at least one other student $j$ such that $|p_i - p_j| \le D$. - The professor gave out the biggest possible total number of candies, i.e. $S = p_1 + p_2 + p_3 + \ldots + p_N$ is maximum possible. GukiZ would like to know the total number of candies $S$ he had at the beginning. However, times change and after six days, the professor is really tired, so it is possible that there is no sequence $p$ which satisfies the constraints. Can you help GukiZ find the number of candies he gave out, or tell him that he must have made a mistake? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains four space-separated integers $N$, $K$, $x$, $D$. - The second line contains $K$ distinct space-separated integers $p_1, p_2, \dots, p_K$. -----Output----- For each test case, print a single line containing one integer — the number of candies GukiZ had, or $-1$ if there is no valid sequence $p$. -----Constraints----- - $1 \le T \le 50$ - $3 \le N \le 10^9$ - $1 \le K \le \mathrm{min}(N, 2 \cdot 10^4)$ - $1 \le x \le 2 \cdot 10^9$ - $1 \le D \le 10^9$ - $1 \le p_i \le x$ for each valid $i$ - All values $p_i$ from input are distinct -----Subtasks----- Subtask #1 (15 points): $1 \leq x, N, D \leq 15$ Subtask #2 (35 points): $1 \leq x, N, D \leq 10^5$ Subtask #3 (50 points): original constraints -----Example Input----- 2 4 3 5 3 2 1 5 3 2 8 2 3 8 -----Example Output----- 12 -1 -----Explanation----- Example case 1: There are four students. We know that the first student got $p_1 = 2$ candies, the second student got $p_2 = 1$ and the third got $p_3 = 5$ candies; we don't know the number of candies given to the last student. The maximum possible amount of candies given to some student is $x=5$. The best possible option is giving $p_4=4$ candies to the last student. Then, the fourth constraint (with $D=3$) is satisfied for all students. Only the pair of students $(2, 3)$ have numbers of candies that differ by more than $3$, but still, for each student, there are at least two other students with close enough numbers of candies. Example case 2: GukiZ made some mistake in distribution and there is no valid sequence $p$. The answer is $-1$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python try: # https://www.codechef.com/LTIME63B/problems/GHMC # Finally.... I properly understood what needs to be done. def ctlt(arr, val): # find number of values in sorted arr < val if arr[0] >= val: return 0 lo = 0 hi = len(arr) while hi-lo > 1: md = (hi+lo)//2 if arr[md]<val: lo = md else: hi = md return hi for _ in range(int(input())): n,k,x,d = map(int, input().split()) z = input().strip().split() if k > 0: ps = list(map(int,z[:k])) else: ps = [x] ps.sort() if x<n or x<ps[-1] or n<k: print(-1) continue valchecked = 0 fillval = 0 valsdone = False isolbelow = True lastp = ps[0] while not valsdone and n>=k: if n == k: lo = x+d+1 # put out of range else: # find best maxfill (before val support) lo = 1 hi = x+1 while hi-lo>1: md = (hi+lo)//2 v = (x-md+1) + ctlt(ps,md) if v<n: hi = md else: lo = md valsdone = True checkto = ctlt(ps,lo)-1 if checkto >= valchecked: # support all vals for p in ps[valchecked+1:checkto+1]: if lastp+d >= p: isolbelow = False elif isolbelow: valsdone = False fillval += lastp+d n -= 1 isolbelow = (p > lastp + 2*d ) else: isolbelow = True lastp = p valchecked = checkto if valsdone and isolbelow: # check gap to maxfill if lastp + d >= lo: isolbelow = False else: valsdone = False fillval += lastp ps[checkto] += d lastp += d isolbelow = False n -= 1 if k > n: print(-1) elif k == n: print(sum(ps) + fillval) elif k == n-1 and lo > ps[-1]: print(sum(ps) + fillval + min(x,ps[-1]+d)) else: tot = (x+lo)*(x-lo+1)//2 + sum(ps[:ctlt(ps,lo)]) print(tot + fillval) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In this problem the input will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks ' (apostrophe), . (full stop), , (comma), ; (semicolon), :(colon) and white space characters (blank, newline). Your task is print the words in the text in lexicographic order (that is, dictionary order). Each word should appear exactly once in your list. You can ignore the case (for instance, "The" and "the" are to be treated as the same word). There should be no uppercase letters in the output. For example, consider the following candidate for the input text: This is a sample piece of text to illustrate this problem. The corresponding output would read as: a illustrate is of piece problem sample text this to -----Input format----- - The first line of input contains a single integer $N$, indicating the number of lines in the input. - This is followed by $N$ lines of input text. -----Output format----- - The first line of output contains a single integer $M$ indicating the number of distinct words in the given text. - The next $M$ lines list out these words in lexicographic order. -----Constraints----- - $1 \leq N \leq 10000$ - There are at most 80 characters in each line. - There are at the most 1000 distinct words in the given text. -----Sample Input----- 2 This is a sample piece of text to illustrate this problem. -----Sample Output----- 10 a illustrate is of piece problem sample text this to The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys t=int(input()) x=sys.stdin.readlines() l=[] for s in x: s=s.replace(".","") s=s.replace("'","") s=s.replace(",","") s=s.replace(":","") s=s.replace(";","") lst=[str(i) for i in s.split()] for j in lst: l.append(j) m=[] for y in l: z=y.lower() m.append(z) n=[] for k in m: if(k in n): continue else: n.append(k) print(len(n)) h=sorted(n) for j in h: print(j) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$. Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$. For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation. Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him? -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$)  — the length of arrays. The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$)  — elements of array $a$. There can be duplicates among elements. The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$)  — elements of array $b$. There can be duplicates among elements. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$. -----Output----- For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible. You can print each letter in any case (upper or lower). -----Example----- Input 5 3 1 -1 0 1 1 -2 3 0 1 1 0 2 2 2 1 0 1 41 2 -1 0 -1 -41 5 0 1 -1 1 -1 1 1 -1 1 -1 Output YES NO YES YES NO -----Note----- In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$ In the second test case we can't make equal numbers on the second position. In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case. In the last lest case, it is impossible to make array $a$ equal to the array $b$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import * mod = 1000000007 for zz in range(int(input())): n = int(input()) a = [ int(i) for i in input().split()] b = [int(i) for i in input().split()] ha = True hp = False hm = False for i in range(n): if b[i] != a[i]: if b[i] > a[i]: if (hp): pass else: ha = False break else: if (hm): pass else: ha = False break if a[i] > 0: hp = True elif a[i] < 0: hm = True if ha: print('YES') else: print('NO') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ayoub thinks that he is a very smart person, so he created a function $f(s)$, where $s$ is a binary string (a string which contains only symbols "0" and "1"). The function $f(s)$ is equal to the number of substrings in the string $s$ that contains at least one symbol, that is equal to "1". More formally, $f(s)$ is equal to the number of pairs of integers $(l, r)$, such that $1 \leq l \leq r \leq |s|$ (where $|s|$ is equal to the length of string $s$), such that at least one of the symbols $s_l, s_{l+1}, \ldots, s_r$ is equal to "1". For example, if $s = $"01010" then $f(s) = 12$, because there are $12$ such pairs $(l, r)$: $(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$. Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers $n$ and $m$ and asked him this problem. For all binary strings $s$ of length $n$ which contains exactly $m$ symbols equal to "1", find the maximum value of $f(s)$. Mahmoud couldn't solve the problem so he asked you for help. Can you help him? -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^5$)  — the number of test cases. The description of the test cases follows. The only line for each test case contains two integers $n$, $m$ ($1 \leq n \leq 10^{9}$, $0 \leq m \leq n$) — the length of the string and the number of symbols equal to "1" in it. -----Output----- For every test case print one integer number — the maximum value of $f(s)$ over all strings $s$ of length $n$, which has exactly $m$ symbols, equal to "1". -----Example----- Input 5 3 1 3 2 3 3 4 0 5 2 Output 4 5 6 0 12 -----Note----- In the first test case, there exists only $3$ strings of length $3$, which has exactly $1$ symbol, equal to "1". These strings are: $s_1 = $"100", $s_2 = $"010", $s_3 = $"001". The values of $f$ for them are: $f(s_1) = 3, f(s_2) = 4, f(s_3) = 3$, so the maximum value is $4$ and the answer is $4$. In the second test case, the string $s$ with the maximum value is "101". In the third test case, the string $s$ with the maximum value is "111". In the fourth test case, the only string $s$ of length $4$, which has exactly $0$ symbols, equal to "1" is "0000" and the value of $f$ for that string is $0$, so the answer is $0$. In the fifth test case, the string $s$ with the maximum value is "01010" and it is described as an example in the problem statement. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline t=int(input()) def calc(x): return x*(x+1)//2 for test in range(t): n,m=list(map(int,input().split())) ANS=calc(n) k=n-m q,mod=divmod(k,m+1) ANS-=calc(q+1)*mod+calc(q)*(m+1-mod) print(ANS) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are N hills in a row numbered 1 through N from left to right. Each hill has a height; for each valid i, the height of the i-th hill is Hi. Chef is initially on the leftmost hill (hill number 1). He can make an arbitrary number of jumps (including zero) as long as the following conditions are satisfied: - Chef can only jump from each hill to the next hill, i.e. from the i-th hill, he can jump to the i+1-th hill (if it exists). - It's always possible to jump to a hill with the same height as the current hill. - It's possible to jump to a taller hill if it's higher than the current hill by no more than U. - It's possible to jump to a lower hill if it's lower than the current hill by no more than D. - Chef can use a parachute and jump to a lower hill regardless of its height (as long as it's lower than the current hill). This jump can only be performed at most once. Chef would like to move as far right as possible. Determine the index of the rightmost hill Chef can reach. -----Input----- - The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains three space-separated integers N, U and D. - The second line contains N space-separated integers H1, H2, ..., HN. -----Output----- For each test case, print a single line containing one integer — the index of the rightmost reachable hill. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 100 - 1 ≤ U, D ≤ 1,000,000 - 1 ≤ Hi ≤ 1,000,000 for each valid i -----Subtasks----- Subtask #1 (100 points): original constraints -----Example----- Input: 3 5 3 2 2 5 2 6 3 5 2 3 4 4 4 4 4 5 2 7 1 4 3 2 1 Output: 3 5 1 -----Explanation----- Example case 1: Chef can jump to second hill because it's higher by no more than U=3 than first hill, to jump to third hill Chef has to use parachute because it's lower than second hill by 3 which is more than D=2, Chef can't jump to fourth hill because it's higher than third hill by 4 which is more than U=3 Example case 2: All hills are of the same height, so chef can reach the last hill with no problems. Example case 3: Chef can't jump to second hill because it's too high for him The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): N,U,D=list(map(int,input().split())) H=list(map(int,input().split())) jumps=0 paracount=0 for i in range(len(H)-1): if H[i+1]-H[i]<=U and H[i+1]>=H[i]: jumps+=1 elif H[i]>=H[i+1] and H[i]-H[i+1]<=D: jumps+=1 elif H[i]-H[i+1]>D and paracount==0: jumps+=1 paracount=1 else: break print(jumps+1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is playing a game on the non-negative x-axis. It takes him $1$ second to reach from $i^{th}$ position to $(i-1)^{th}$ position or $(i+1)^{th}$ position. The chef never goes to the negative x-axis. Also, Chef doesn't stop at any moment of time. The movement of chef can be described as follows. - At the start he is standing at $x=0$ at time $0$. - In the first round, he moves towards $x=1$ and comes back to the $x=0$ position. - In the second round, he moves towards the $x=2$ and comes back again to $x=0$. - Generalizing, in the $k^{th}$ round, he moves from $x=0$ to $x=k$ and then returns back to $x=0$ at the end of the round. This goes on as the game progresses. For Example, the path of Chef for $3^{rd}$ round is given below. $0 - 1 - 2 - 3 - 2 - 1 - 0$ The overall path followed by Chef would look somewhat like this: $0 - 1 - 0 - 1 - 2 - 1 - 0 - 1 - 2 - 3 - 2 - 1 - 0 - 1 - 2 - 3 - 4 - 3 - …$ You are given two non-negative integers $N$ and $K$. You have to tell the time at which Chef arrives at $x=N$ for the $K^{th}$ time. Note - Chef can not skip a position while visiting the positions. -----Input:----- - The first line contains $T$ the number of test cases. Then the test cases follow. - Each test case contains a single line of two integers $N$ and $K$. -----Output:----- For each test case, print a single line containing one integer -- the time taken by the chef to arrive at $x=N$ for the $K^{th}$ time by modulo $1,000,000,007$. -----Constraints----- - $1 \le T \le 10^5$ - $0 \le N \le 10^9$ - $1 \le K \le 10^9$ -----Sample Input:----- 5 0 1 1 1 2 1 1 3 4 6 -----Sample Output:----- 0 1 4 5 46 -----Explanation:----- Test Case 1: Chef starts the journey from the $N = 0$ at time $t = 0$ and it's the first time $(K = 1)$, he is here. So, the answer is $0$. Test Case 2: Chef starts the journey from the $N = 0$ at time $t = 0$ then goes to $N = 1$ at $t = 1$ and it's the first time $(K = 1)$, he is here. So, the answer is $1$. Test Case 4: The path followed by Chef to reach $1$ for the third time is given below. $0 - 1 - 0 - 1 - 2 - 1$ He reaches $1$ for the third time at $t=5$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys from random import choice,randint inp=sys.stdin.readline out=sys.stdout.write flsh=sys.stdout.flush sys.setrecursionlimit(10**9) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def MI(): return map(int, inp().strip().split()) def LI(): return list(map(int, inp().strip().split())) def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines().strip()] def LI_(): return [int(x)-1 for x in inp().strip().split()] def LF(): return [float(x) for x in inp().strip().split()] def LS(): return inp().strip().split() def I(): return int(inp().strip()) def F(): return float(inp().strip()) def S(): return inp().strip() def pf(s): return out(s+'\n') def JA(a, sep): return sep.join(map(str, a)) def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a) def main(): from math import ceil t = I() l = [] for _ in range(t): n,k=MI() if n==0: k-=1 ans = ((k)*((k+1)))%mod l.append(ans) else: # if k==1: # ans = ((((n)*((n-1)))%mod)+ n%mod)%mod # l.append(ans) # else: # k-=1 # lr = (n%mod+((ceil(k/2)%mod))%mod # ans = ((lr*((lr-1))%mod # if k%2!=0: # ans= (ans%mod + n%mod)%mod # else: # ans = ((ans%mod)+((lr+n)%mod))%mod # l.append(ans) if k%2!=0: lr = k//2 l.append(((n*n)%mod+(lr*((2*n)%mod))%mod+(lr*(lr+1))%mod)%mod) else: lr = k//2 l.append(((n*n)%mod + (lr*(2*n)%mod)%mod + (lr*(lr-1))%mod)%mod) for i in range(t): pf(str(l[i])) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. She has been collecting stones since her childhood - now she has become really good with identifying which ones are fake and which ones are not. Her King requested for her help in mining precious stones, so she has told him which all stones are jewels and which are not. Given her description, your task is to count the number of jewel stones. More formally, you're given a string J composed of latin characters where each character is a jewel. You're also given a string S composed of latin characters where each character is a mined stone. You have to find out how many characters of S are in J as well. -----Input----- First line contains an integer T denoting the number of test cases. Then follow T test cases. Each test case consists of two lines, each of which contains a string composed of English lower case and upper characters. First of these is the jewel string J and the second one is stone string S. You can assume that 1 <= T <= 100, 1 <= |J|, |S| <= 100 -----Output----- Output for each test case, a single integer, the number of jewels mined. -----Example----- Input: 4 abc abcdef aA abAZ aaa a what none Output: 3 2 1 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) for i in range(n): count = 0 k = input() x = list(k) kk = input() y = list(kk) for j in y: for jj in x: if(j==jj): count = count+1 break print(count) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef recently started working at ABC corporation. Let's number weekdays (Monday through Friday) by integers $1$ through $5$. For each valid $i$, the number of hours Chef spent working at the office on weekday $i$ was $A_i$. Unfortunately, due to the COVID-19 pandemic, Chef started working from home and his productivity decreased by a considerable amount. As per Chef's analysis, $1$ hour of work done at the office is equivalent to $P$ hours of work done at home. Now, in order to complete his work properly, Chef has to spend more hours working from home, possibly at the cost of other things like sleep. However, he does not have to do the same work on each day as he would have in the office ― for each weekday, he can start the work for this day on an earlier day and/or complete it on a later day. The only requirement is that his work does not pile up indefinitely, i.e. he can complete his work for each week during the same week. One day has $24$ hours. If Chef is unable to complete his work for a week during those five weekdays, then he has to work during the weekend too. Chef wishes to know whether he has to work on weekends or if he can complete his work by working only on weekdays. Help him answer that question. (It is possible that Chef would be unable to finish his work even if he worked all the time, but he does not want to know about that.) -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains six space-separated integers $A_1$, $A_2$, $A_3$, $A_4$, $A_5$ and $P$. -----Output----- For each test case, print a single line containing the string "Yes" if Chef has to work on weekends or "No" otherwise (without quotes). -----Constraints----- - $1 \le T \le 1,000$ - $0 \le A_i \le 24$ for each valid $i$ - $1 \le P \le 24$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 2 14 10 12 6 18 2 10 10 10 10 10 3 -----Example Output----- No Yes -----Explanation----- Example case 1: Here, $P=2$, so the number of hours Chef has to work from home to handle his workload for days $1$ through $5$ is $[28,20,24,12,36]$. If he works for full $24$ hours on each of the five weekdays, he finishes all the work, so he does not have to work on weekends. Example case 2: No matter what Chef does, he will have to work on weekends. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for t in range(int(input())): a1,a2,a3,a4,a5,p=[int(x)for x in input().rstrip().split()] if (a1+a2+a3+a4+a5)*p >120: print("Yes") else: print("No") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: DevuLand is a very strange place. There are n villages in it. Some of the villages are occupied by dinosaurs while the remaining ones by villagers. You are given the information of DevuLand by an array D of size n. If D[i] is non-negative, it means that there are D[i] villagers in that village. Otherwise, it means that are -D[i] dinosaurs in that village. It is also guaranteed that total number of villagers in DevuLand is equal to total number of dinosaurs. Once dinosaurs got very hungry and started eating villagers. Frightened villagers gathered immediately and met their Sarpanch Deviji. Deviji, being a very daring and negotiable person, met to the head of dinosaurs. Soon both parties called a truce. It was decided that the villagers will provide laddus to the dinosaurs. So everyday, each villager will take exactly one laddu to one of the dinosaurs in such a way that no dinosaur remains hungry (note that this is possible because number of villagers is the same as the number of dinosaurs). Actually, carrying laddus is a quite a tough job. Villagers have to use a bullock cart for that. It takes one unit of grass a bullock to carry a cart with 1 laddu for 1 kilometre. Laddus used to be very heavy in DevuLand, so a bullock cart can not carry more than one laddu. It is also given distance between village indexed i and j is |j - i| (the absolute value) kilometres. Now villagers sat down and found a strategy to feed laddus to dinosaurs so that they need to buy the least amount of grass from the nearby market. They are not very good in calculations, please find out what is the minimum number of units of grass they need to buy. -----Input----- First line of the input contains an integer T denoting number of test cases. For each test case, there are two lines. First line contains a single integer denoting n: number of villages. Second line contains n space separated integers denoting the array D. -----Output----- For each test case, print a single line containing the integer corresponding to answer of the problem. -----Constraints----- - 1 ≤ T ≤ 10^5 - 1 ≤ n ≤ 10^5 - -10^4 ≤ D[i] ≤ 10^4 - Sum of n over all the test cases will be ≤ 10^6 - It is guaranteed that sum of D[i] is zero for a single test case which ensures that there are equal number of villagers and dinosaurs. -----Example----- Input: 3 2 5 -5 2 -5 5 3 1 2 -3 Output: 5 5 4 -----Explanation----- Example case 1. Each villager in village 1, need to walk 1 km to reach to the dinosaur in 2nd village. Example case 2. Each villager in village 2, need to walk 1 km to reach to the dinosaur 1st village. Example case 3. Each villager in village 1, need to walk 2 km to reach to the dinosaur in 3rd village whereas Each villager in village 2, need to walk 1 km to reach to the dinosaur in 3rd village. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) curr = 0 ans = 0 for x in a: curr += x ans += abs(curr) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a simple undirected graph with N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects Vertex U_i and V_i. Also, Vertex i has two predetermined integers A_i and B_i. You will play the following game on this graph. First, choose one vertex and stand on it, with W yen (the currency of Japan) in your pocket. Here, A_s \leq W must hold, where s is the vertex you choose. Then, perform the following two kinds of operations any number of times in any order: - Choose one vertex v that is directly connected by an edge to the vertex you are standing on, and move to vertex v. Here, you need to have at least A_v yen in your pocket when you perform this move. - Donate B_v yen to the vertex v you are standing on. Here, the amount of money in your pocket must not become less than 0 yen. You win the game when you donate once to every vertex. Find the smallest initial amount of money W that enables you to win the game. -----Constraints----- - 1 \leq N \leq 10^5 - N-1 \leq M \leq 10^5 - 1 \leq A_i,B_i \leq 10^9 - 1 \leq U_i < V_i \leq N - The given graph is connected and simple (there is at most one edge between any pair of vertices). -----Input----- Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_N B_N U_1 V_1 U_2 V_2 : U_M V_M -----Output----- Print the smallest initial amount of money W that enables you to win the game. -----Sample Input----- 4 5 3 1 1 2 4 1 6 2 1 2 2 3 2 4 1 4 3 4 -----Sample Output----- 6 If you have 6 yen initially, you can win the game as follows: - Stand on Vertex 4. This is possible since you have not less than 6 yen. - Donate 2 yen to Vertex 4. Now you have 4 yen. - Move to Vertex 3. This is possible since you have not less than 4 yen. - Donate 1 yen to Vertex 3. Now you have 3 yen. - Move to Vertex 2. This is possible since you have not less than 1 yen. - Move to Vertex 1. This is possible since you have not less than 3 yen. - Donate 1 yen to Vertex 1. Now you have 2 yen. - Move to Vertex 2. This is possible since you have not less than 1 yen. - Donate 2 yen to Vertex 2. Now you have 0 yen. If you have less than 6 yen initially, you cannot win the game. Thus, the answer is 6. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python class dsu: def __init__(self, n=0): self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: x = self.leader(a) y = self.leader(b) if x == y: return x if self.parent_or_size[x] > self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: x = a while self.parent_or_size[x] >= 0: x = self.parent_or_size[x] while a != x: self.parent_or_size[a], a = x, self.parent_or_size[a] return x def size(self, a: int) -> int: return -self.parent_or_size[self.leader(a)] def groups(self): g = [[] for _ in range(self._n)] for i in range(self._n): g[self.leader(i)].append(i) return list(c for c in g if c) n, m = list(map(int, input().split())) vdata = [] # (required, gain) for _ in range(n): a, b = list(map(int, input().split())) vdata.append((max(a - b, 0), b)) to = [[] for _ in range(n)] for _ in range(m): u, v = list(map(int, input().split())) u -= 1; v -= 1 to[u].append(v) to[v].append(u) s = dsu(n) dp = vdata.copy() # (extra, tot_gain) visited = [False] * n for u in sorted(list(range(n)), key=lambda i: vdata[i][0]): req, gain = vdata[u] frm = {u} for v in to[u]: if visited[v]: frm.add(s.leader(v)) mnextra = 10 ** 18 for v in frm: e, g = dp[v] e += max(req - (e + g), 0) if e < mnextra: mnextra, mni = e, v extra, tot_gain = mnextra, sum(dp[v][1] for v in frm) for v in frm: s.merge(u, v) dp[s.leader(u)] = extra, tot_gain visited[u] = True ans = sum(dp[s.leader(0)]) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Abhiram needs to search for an antidote. He comes to know that clue for finding the antidote is carefully hidden by KrishnaMurthy in the form of a puzzle. The puzzle consists of a string S and a keywordK. Abhiram needs to find the string of position of anagrams R of the keyword in the string which is the clue. The antidote is found in the box numbered R. Help him find his clue R. Anagram: A word or phrase that is made by arranging the letters of another word or phrase in a different order. Eg: 'elvis' and 'lives' are both anagrams of each other. Note: Consider, Tac and act are not anagrams(case sensitive). -----Input:----- The first line contains a string S of length land the second line contains a keyword K. -----Output:----- Output contains a line"The antidote is found in R." Where R= string of positions of anagrams.(the position of the first word in the string is 1). -----Constraints:----- 1<=l<=500 1<=k<=50 -----Example:----- Input: cat is the act of tac cat Output: The antidote is found in 46. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python x = input().split(" ") y = input() ans = '' l = 1 for i in x: if i!=y and sorted(i) == sorted(y): ans = ans + (str)(l) l=l+1 ans+='.' print("The antidote is found in",ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- * * * * *** *** * * *** *** ***** ***** * * *** *** ***** ***** ******* ******* -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for i in range(int(input())): n=int(input()) p=1 l=n-1 for j in range(n): for k in range(l): print(" ",end='') for k in range(p): print("*",end='') print() for k in range(l): print(" ",end='') for k in range(p): print("*",end='') print() p+=2 l-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sandu, a teacher in Chefland introduced his students to a new sequence i.e. 0,1,0,1,2,0,1,2,3,0,1,2,3,4........ The Sequence starts from 0 and increases by one till $i$(initially i equals to 1), then repeat itself with $i$ changed to $i+1$ Students being curious about the sequence asks the Nth element of the sequence. Help Sandu to answer the Students -----Input:----- - The first-line will contain $T$, the number of test cases. Then the test case follows. - Each test case contains a single numbers N. -----Output:----- Print the Nth element of the sequence -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^{18}$ -----Sample Input:----- 5 8 9 20 32 109 -----Sample Output:----- 2 3 5 4 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import sqrt for _ in range(int(input())): n = int(input()) x = int(sqrt(2 * n)) while x * (x+1) // 2 <= n: x += 1 while x * (x+1) // 2 > n: x -= 1 n -= x * (x+1) // 2 print(n) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are $N$ sabotages available in the game Among Us, initially all at level $0$. $N$ imposters are allotted the task to upgrade the level of the sabotages. The $i^{th}$ imposter $(1 \leq i \leq N)$ increases the level of $x^{th}$ sabotage $(1 \leq x \leq N)$ by one level if $gcd(i,x)=i$. You need to find the number of sabotages at LEVEL 5 after all the imposters have completed their tasks. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, one integer $N$. -----Output:----- For each testcase, output in a single line the number of sabotages at LEVEL 5. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 10^{18}$ -----Sample Input:----- 1 6 -----Sample Output:----- 0 -----EXPLANATION:----- The $1^{st}$ sabotage is at level $1$, the $2^{nd}$, $3^{rd}$ and $5^{th}$ sabotages are at level $2$, the $4^{th}$ sabotage is at level $3$ and the $6^{th}$ sabotage is at level $4$. None of them reach level $5$. Hence the output is $0$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from bisect import bisect n = 32000 def primeSeive(n): prime = [True for i in range(n + 1)] primes = [] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0] = False prime[1] = False for p in range(n + 1): if prime[p]: primes.append(p) return primes arr = primeSeive(n) fin = [] for i in arr: fin.append(pow(i,4)) for _ in range(int(input())): n = int(input()) print(bisect(fin,n)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: $Jaggu$ monkey a friend of $Choota$ $Bheem$ a great warrior of $Dholakpur$. He gets everything he wants. Being a friend of $Choota$ $Bheem$ he never has to struggle for anything, because of this he is in a great debt of $Choota$ $Bheem$, he really wants to pay his debt off. Finally the time has come to pay his debt off, $Jaggu$ is on a magical tree. He wants to collect apples from different branches but he is in a hurry. $Botakpur$ has attacked on $Dholakpur$ and $Bheem$ is severely injured, as been instructed by the village witch, $Bheem$ can only be saved by the apples of the magical tree. Each apple is placed in Tree Node structure and each apple has some sweetness. Now there's a problem as $Jaggu$ is also injured so he can only slide downwards and alse is collecting apples in his hand so he can't climb. You would be given $Q$ queries. Queries are of 2 type :- - Ending Node Node of $Jaggu$ is given. $format$ - type of query node -(1 2) - Sweetness of Apple on a given node is changed. $format$ - type of query node new sweetness(2 3 10) $Note$: $Jaggu$ is always on the top of tree initially in each query.The sweetness is always positive. Help $Jaggu$ in saving $Bheem$ -----Input:----- - First line contains $N$ - (number of nodes). - Next line contains $N$ integers with space giving sweetness of apple on Nodes $(1 to N)$ - Next $N-1$ lines contain $N1$ $N2$ connected nodes. - Next line contains single integer $Q$ Number of queries -----Output:----- - For each query of type 1, print total sweetness of apples. -----Constraints----- - $1 \leq N \leq 10^4$ - $2 \leq Q \leq 10^4$ -----Sample Input:----- 10 10 12 6 8 1 19 0 5 13 17 1 2 1 3 1 4 3 10 4 8 8 9 4 5 5 7 5 6 3 1 1 2 3 20 1 8 -----Sample Output:----- 10 23 -----EXPLANATION:----- This sweetness array is : $[10,2,6,8,1,19,0,5,13,17]$ The tree is: 1 / | \ 2 3 4 / / \ 10 8 5 / / \ 9 7 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python counter = -1 def flattree(node): nonlocal counter if visited[node]==1: return else: visited[node]=1 counter += 1 i_c[node] = counter flat_tree[counter] = swt[node] for i in graph[node]: if visited[i]==0: flattree(i) counter += 1 o_c[node] = counter flat_tree[counter] = -swt[node] return def getsum(BITTree, i): s = 0 # initialize result i = i + 1 while i > 0: s += BITTree[i] i -= i & (-i) return s def upd(BITTree, n, i, v): i += 1 while i <= n: BITTree[i] += v i += i & (-i) def construct(arr, n): BITTree = [0] * (n + 1) for i in range(n): upd(BITTree, n, i, arr[i]) return BITTree from collections import defaultdict n = int(input()) swt = list(map(int, input().split())) graph = defaultdict(list) for i in range(n-1): n1, n2 = list(map(int, input().split())) graph[n1-1].append(n2-1) graph[n2-1].append(n1-1) flat_tree = [0]*(2*n+1) i_c = [0]*n o_c = [0]*n visited = [0]*n flattree(0) tre = construct(flat_tree, 2*n) q = int(input()) for i in range(q): query = list(map(int, input().split())) if query[0] == 1: node = query[1] - 1 answer = getsum(tre, i_c[node]) print(answer) else: node = query[1]-1 upd(flat_tree, (2*n), i_c[node], query[2]) upd(flat_tree, (2*n), o_c[node], -query[2]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has bought N robots to transport cakes for a large community wedding. He has assigned unique indices, from 1 to N, to each of them. How it will happen? Chef arranges the N robots in a row, in the (increasing) order of their indices. Then, he chooses the first M robots and moves them to the end of the queue. Now, Chef goes to the robot at the first position in the row and hands it one cake. He then notes this robot's index (say k) in his notebook, and goes to the kth position in the row. If the robot at this position does not have a cake, he give him one cake, notes his index in his notebook, and continues the same process. If a robot visited by Chef already has a cake with it, then he stops moving and the cake assignment process is stopped. Chef will be satisfied if all robots have a cake in the end. In order to prepare the kitchen staff for Chef's wrath (or happiness :) ), you must find out if he will be satisfied or not? If not, you have to find out how much robots have a cake, so that the kitchen staff can prepare themselves accordingly. -----Input----- - The first line of input contains a single integer T denoting the number of test cases. - The single line of each test cases contains two space separated integers N and M. -----Output----- For each of the T test cases, output a single line: - If all N robots have a cake, output "Yes" (without quotes). - Otherwise, output "No" (without quotes) followed by a space and the number of robots which have a cake. -----Constraints and Subtasks----- - 1 ≤ T ≤ 10 - 0 ≤ M < NSubtask 1: 25 points - 1 ≤ N ≤ 10^5Subtask 3: 75 points - 1 ≤ N ≤ 10^9 -----Example----- Input: 3 2 0 2 1 4 2 Output: No 1 Yes No 2 -----Explanation----- In test case 1, we have two robots indexed 1 and 2. They are arranged as (1 2). Chef goes to the first robot, gives him a cake, and moves to position 1. In the next step, he sees that robot at this position already has a has cake. So Chef stops moving, and our answer is "No 1". In test case 2, we again have two robots indexed 1 and 2. Initially, they are arranged as (1 2). Then, Chef moves robot#1 to the end of the row, and thus the arrangement becomes (2 1). Chef goes to the robot at the first position, which is robot#2. Chef hands him a cake, and moves to position 2. Then, he hands a cake to robot#1 at position 2, and moves back to the first position. Since, robot#2 at the first position already ahs a cake, Chef stops moving. All N robots have cakes, so Chef is satisfied, and our answer is "Yes". In the 3rd test case, we have the following arrangement of robots: (3 4 1 2). Only robots with indices 3 and 1 will get cakes. So our answer is "No 2". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #read input cases = int(input()) caselist = [] for i in range(0, cases): caselist.append(input()) #iterate each case for j in range(0, cases): #current case's parameters: current_input = caselist[j].split(' ') bots = int(current_input[0]) switch = int(current_input[1]) #generate botlist and cakelist botlist = list(range(switch, bots)) + list(range(0, switch)) cakelist = [False] * bots counter = 0 index = 0 for i in range(0,bots): if cakelist[index] == False: cakelist[index] = True counter += 1 index = botlist[index] else: break if counter == bots: print("Yes") else: print("No", counter) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Recently, Chef got obsessed with piano. He is a just a rookie in this stuff and can not move his fingers from one key to other fast enough. He discovered that the best way to train finger speed is to play scales. There are different kinds of scales which are divided on the basis of their interval patterns. For instance, major scale is defined by pattern T-T-S-T-T-T-S, where ‘T’ stands for a whole tone whereas ‘S’ stands for a semitone. Two semitones make one tone. To understand how they are being played, please refer to the below image of piano’s octave – two consecutive keys differ by one semitone. If we start playing from first key (note C), then we’ll play all white keys in a row (notes C-D-E-F-G-A-B-C – as you can see C and D differ for a tone as in pattern, and E and F differ for a semitone). This pattern could be played some number of times (in cycle). Each time Chef takes some type of a scale and plays using some number of octaves. Sometimes Chef can make up some scales, so please don’t blame him if you find some scale that does not exist in real world. Formally, you have a set of 12 keys (i.e. one octave) and you have N such sets in a row. So in total, you have 12*N keys. You also have a pattern that consists of letters 'T' and 'S', where 'T' means move forward for two keys (from key x to key x + 2, and 'S' means move forward for one key (from key x to key x + 1). Now, you can start playing from any of the 12*N keys. In one play, you can repeat the pattern as many times as you want, but you cannot go outside the keyboard. Repeating pattern means that if, for example, you have pattern STTST, you can play STTST as well as STTSTSTTST, as well as STTSTSTTSTSTTST, as well as any number of repeating. For this pattern, if you choose to repeat it once, if you start at some key x, you'll press keys: x (letter 'S')-> x + 1 (letter 'T')-> x + 3 (letter 'T')-> x + 5 (letter 'S') -> x + 6 (letter 'T')-> x + 8. Also 1 ≤ x, x + 8 ≤ 12*N so as to avoid going off the keyboard. You are asked to calculate number of different plays that can be performed. Two plays differ if and only if they start at different keys or patterns are repeated different number of times. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. First line of each test case contains scale’s pattern – string s consisting of letters ‘T’ and ‘S’ only. Second line contains one integer N – number of octaves he’ll be using. -----Output----- For each test case output a single number in a line corresponding to number of different scales he’ll play. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ |S| ≤ 100 - 1 ≤ n ≤ 7 -----Subtasks----- Subtask 1: T < 10 4, N = 1 Subtask 2: No additional constraints. -----Example----- Input: 2 TTTT 1 TTSTTTS 3 Output: 4 36 -----Explanation----- Example case 1. In the first case there is only one octave and Chef can play scale (not in cycle each time) starting with notes C, C#, D, D# - four together. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t =int(input()) for i in range(t): C=[ord(x)-ord('R') for x in list(input())] N=int(input()) L=sum(C) r=1 c=0 while(r*L<N*12): c+=N*12-r*L r+=1 print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- 1 1 01 11 001 1 01 11 001 101 011 111 0001 1001 1 01 11 001 101 011 111 0001 1001 0101 1101 0011 1011 0111 1111 00001 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) while(t): n=int(input()) cnt=1; for i in range(n): s="" for j in range(n): s=s+str(bin(cnt))[2:][: : -1]+" " cnt=cnt+1 print(s) t=t-1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Toad Pimple has an array of integers $a_1, a_2, \ldots, a_n$. We say that $y$ is reachable from $x$ if $x<y$ and there exists an integer array $p$ such that $x = p_1 < p_2 < \ldots < p_k=y$, and $a_{p_i}\, \&\, a_{p_{i+1}} > 0$ for all integers $i$ such that $1 \leq i < k$. Here $\&$ denotes the bitwise AND operation. You are given $q$ pairs of indices, check reachability for each of them. -----Input----- The first line contains two integers $n$ and $q$ ($2 \leq n \leq 300\,000$, $1 \leq q \leq 300\,000$) — the number of integers in the array and the number of queries you need to answer. The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 300\,000$) — the given array. The next $q$ lines contain two integers each. The $i$-th of them contains two space-separated integers $x_i$ and $y_i$ ($1 \leq x_i < y_i \leq n$). You need to check if $y_i$ is reachable from $x_i$. -----Output----- Output $q$ lines. In the $i$-th of them print "Shi" if $y_i$ is reachable from $x_i$, otherwise, print "Fou". -----Example----- Input 5 3 1 3 0 2 1 1 3 2 4 1 4 Output Fou Shi Shi -----Note----- In the first example, $a_3 = 0$. You can't reach it, because AND with it is always zero. $a_2\, \&\, a_4 > 0$, so $4$ is reachable from $2$, and to go from $1$ to $4$ you can use $p = [1, 2, 4]$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop,heapify import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline from itertools import accumulate from functools import lru_cache M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] n, q = li() queue = [-1] * 20 ans = [[-1] * 20 for i in range(n + 1)] l = li() for i, curr in enumerate(l): for j in range(20): if curr >> j & 1: for k in range(20): ans[i][k] = max(ans[i][k], ans[queue[j]][k]) ans[i][j] = i for j in range(20):queue[j] = max(queue[j], ans[i][j]) queries = [] for i in range(q):queries.append(li()) for i in range(q): a, b = queries[i] a -= 1 b -= 1 currans = 0 for j in range(20): if (l[a] >> j) & 1 and ans[b][j] >= a: currans = 1 break print('Shi' if currans else 'Fou') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). $8$ illustration by 猫屋 https://twitter.com/nekoyaliu Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact. -----Input----- The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters. -----Output----- Print a single integer — the number of subsequences "QAQ" in the string. -----Examples----- Input QAQAQYSYIOIWIN Output 4 Input QAQQQZZYNOIWIN Output 3 -----Note----- In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s=input() ans = 0 for i in range(len(s)): if s[i] == 'A': ans += s[:i].count('Q') * s[i:].count('Q') print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a frog staying to the left of the string $s = s_1 s_2 \ldots s_n$ consisting of $n$ characters (to be more precise, the frog initially stays at the cell $0$). Each character of $s$ is either 'L' or 'R'. It means that if the frog is staying at the $i$-th cell and the $i$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $i$-th cell and the $i$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $0$. Note that the frog can jump into the same cell twice and can perform as many jumps as it needs. The frog wants to reach the $n+1$-th cell. The frog chooses some positive integer value $d$ before the first jump (and cannot change it later) and jumps by no more than $d$ cells at once. I.e. if the $i$-th character is 'L' then the frog can jump to any cell in a range $[max(0, i - d); i - 1]$, and if the $i$-th character is 'R' then the frog can jump to any cell in a range $[i + 1; min(n + 1; i + d)]$. The frog doesn't want to jump far, so your task is to find the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it can jump by no more than $d$ cells at once. It is guaranteed that it is always possible to reach $n+1$ from $0$. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. The next $t$ lines describe test cases. The $i$-th test case is described as a string $s$ consisting of at least $1$ and at most $2 \cdot 10^5$ characters 'L' and 'R'. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $2 \cdot 10^5$ ($\sum |s| \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer — the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it jumps by no more than $d$ at once. -----Example----- Input 6 LRLRRLL L LLR RRRR LLLLLL R Output 3 2 3 1 7 1 -----Note----- The picture describing the first test case of the example and one of the possible answers: [Image] In the second test case of the example, the frog can only jump directly from $0$ to $n+1$. In the third test case of the example, the frog can choose $d=3$, jump to the cell $3$ from the cell $0$ and then to the cell $4$ from the cell $3$. In the fourth test case of the example, the frog can choose $d=1$ and jump $5$ times to the right. In the fifth test case of the example, the frog can only jump directly from $0$ to $n+1$. In the sixth test case of the example, the frog can choose $d=1$ and jump $2$ times to the right. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for i in range(int(input())): s='R' + input() + 'R' prev=0 ma=-1 for i in range(1,len(s)): if s[i]=='R': ma=max(ma,i-prev) prev=i print(ma) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (10^9 + 7). -----Input----- The first line contains an integer n (2 ≤ n ≤ 10^5) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p_0, p_1, ..., p_{n} - 2 (0 ≤ p_{i} ≤ i). Where p_{i} means that there is an edge connecting vertex (i + 1) of the tree and vertex p_{i}. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x_0, x_1, ..., x_{n} - 1 (x_{i} is either 0 or 1). If x_{i} is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. -----Output----- Output a single integer — the number of ways to split the tree modulo 1000000007 (10^9 + 7). -----Examples----- Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python MOD = 1000000007 n = int(input()) p = [int(x) for x in input().split()] x = [int(x) for x in input().split()] children = [[] for x in range(n)] for i in range(1,n): children[p[i-1]].append(i) #print(children) count = [(0,0) for i in range(n)] for i in reversed(list(range(n))): prod = 1 for ch in children[i]: prod *= count[ch][0]+count[ch][1] if x[i]: count[i] = (0,prod % MOD) else: tot = 0 for ch in children[i]: cur = count[ch][1]*prod // (count[ch][0]+count[ch][1]) tot += cur count[i] = (prod % MOD, tot % MOD) print(count[0][1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is playing a game with two of his friends. In this game, each player chooses an integer between $1$ and $P$ inclusive. Let's denote the integers chosen by Chef, friend 1 and friend 2 by $i$, $j$ and $k$ respectively; then, Chef's score is (((Nmodi)modj)modk)modN.(((Nmodi)modj)modk)modN.(((N\,\mathrm{mod}\,i)\,\mathrm{mod}\,j)\,\mathrm{mod}\,k)\,\mathrm{mod}\,N\,. Chef wants to obtain the maximum possible score. Let's denote this maximum score by $M$. Find the number of ways to choose the triple $(i,j,k)$ so that Chef's score is equal to $M$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $N$ and $P$. -----Output----- For each test case, print a single line containing one integer — the number of ways to obtain the maximum score. -----Constraints----- - $1 \le T \le 10^6$ - $1 \le N \le P \le 10^6$ -----Subtasks----- Subtask #1 (10 points): - $1 \le T \le 100$ - $1 \le N \le P \le 100$ Subtask #2 (90 points): original constraints -----Example Input----- 2 4 4 3 4 -----Example Output----- 9 13 -----Explanation----- Example case 1: Chef's maximum possible score is $M = 1$. All possible values of $(i, j, k)$ such that the score is $1$ are $(3, 2, 2)$, $(3, 2, 3)$, $(3, 2, 4)$, $(3, 3, 2)$, $(3, 3, 3)$, $(3, 3, 4)$, $(3, 4, 2)$, $(3, 4, 3)$, $(3, 4, 4)$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for __ in range(int(input())): n,p=list(map(int,input().split())) d=n%(n//2+1) if(d==0): t=p*p*p else: t=(p-d)*(p-d)+(p-d)*(p-n)+(p-n)*(p-n) print(t) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You're given an array of $n$ integers between $0$ and $n$ inclusive. In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation). For example, if the current array is $[0, 2, 2, 1, 4]$, you can choose the second element and replace it by the MEX of the present elements  — $3$. Array will become $[0, 3, 2, 1, 4]$. You must make the array non-decreasing, using at most $2n$ operations. It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them.  – An array $b[1 \ldots n]$ is non-decreasing if and only if $b_1 \le b_2 \le \ldots \le b_n$. The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: The MEX of $[2, 2, 1]$ is $0$, because $0$ does not belong to the array. The MEX of $[3, 1, 0, 1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not. The MEX of $[0, 3, 1, 2]$ is $4$ because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not. It's worth mentioning that the MEX of an array of length $n$ is always between $0$ and $n$ inclusive. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 200$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $n$ ($3 \le n \le 1000$) — length of the array. The second line of each test case contains $n$ integers $a_1, \ldots, a_n$ ($0 \le a_i \le n$) — elements of the array. Note that they don't have to be distinct. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $1000$. -----Output----- For each test case, you must output two lines: The first line must contain a single integer $k$ ($0 \le k \le 2n$)  — the number of operations you perform. The second line must contain $k$ integers $x_1, \ldots, x_k$ ($1 \le x_i \le n$), where $x_i$ is the index chosen for the $i$-th operation. If there are many solutions, you can find any of them. Please remember that it is not required to minimize $k$. -----Example----- Input 5 3 2 2 3 3 2 1 0 7 0 7 3 1 3 7 7 9 2 0 1 1 2 4 4 2 0 9 8 4 7 6 1 2 3 0 5 Output 0 2 3 1 4 2 5 5 4 11 3 8 9 7 8 5 9 6 4 1 2 10 1 8 1 9 5 2 4 6 3 7 -----Note----- In the first test case, the array is already non-decreasing ($2 \le 2 \le 3$). Explanation of the second test case (the element modified by each operation is colored in red): $a = [2, 1, 0]$ ; the initial MEX is $3$. $a = [2, 1, \color{red}{3}]$ ; the new MEX is $0$. $a = [\color{red}{0}, 1, 3]$ ; the new MEX is $2$. The final array is non-decreasing: $0 \le 1 \le 3$. Explanation of the third test case: $a = [0, 7, 3, 1, 3, 7, 7]$ ; the initial MEX is $2$. $a = [0, \color{red}{2}, 3, 1, 3, 7, 7]$ ; the new MEX is $4$. $a = [0, 2, 3, 1, \color{red}{4}, 7, 7]$ ; the new MEX is $5$. $a = [0, 2, 3, 1, \color{red}{5}, 7, 7]$ ; the new MEX is $4$. $a = [0, 2, 3, \color{red}{4}, 5, 7, 7]$ ; the new MEX is $1$. The final array is non-decreasing: $0 \le 2 \le 3 \le 4 \le 5 \le 7 \le 7$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def solve(): n = int(input()) a = list(map(int, input().split())) c = [0] * (n + 1) def inc(): for i in range(n - 1): if a[i] > a[i + 1]: return False return True def calc(): for i in range(n + 1): c[i] = 0 for i in a: c[i] += 1 for i in range(n + 1): if not c[i]: return i return n + 1 ans = [] while not inc(): x = calc() if x >= n: y = 0 while y < n and a[y] == y: y += 1 a[y] = x ans.append(y) else: a[x] = x ans.append(x) print(len(ans)) print(*map(lambda x: x + 1, ans)) t = int(input()) for _ in range(t): solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's call two strings $s$ and $t$ anagrams of each other if it is possible to rearrange symbols in the string $s$ to get a string, equal to $t$. Let's consider two strings $s$ and $t$ which are anagrams of each other. We say that $t$ is a reducible anagram of $s$ if there exists an integer $k \ge 2$ and $2k$ non-empty strings $s_1, t_1, s_2, t_2, \dots, s_k, t_k$ that satisfy the following conditions: If we write the strings $s_1, s_2, \dots, s_k$ in order, the resulting string will be equal to $s$; If we write the strings $t_1, t_2, \dots, t_k$ in order, the resulting string will be equal to $t$; For all integers $i$ between $1$ and $k$ inclusive, $s_i$ and $t_i$ are anagrams of each other. If such strings don't exist, then $t$ is said to be an irreducible anagram of $s$. Note that these notions are only defined when $s$ and $t$ are anagrams of each other. For example, consider the string $s = $ "gamegame". Then the string $t = $ "megamage" is a reducible anagram of $s$, we may choose for example $s_1 = $ "game", $s_2 = $ "gam", $s_3 = $ "e" and $t_1 = $ "mega", $t_2 = $ "mag", $t_3 = $ "e": [Image] On the other hand, we can prove that $t = $ "memegaga" is an irreducible anagram of $s$. You will be given a string $s$ and $q$ queries, represented by two integers $1 \le l \le r \le |s|$ (where $|s|$ is equal to the length of the string $s$). For each query, you should find if the substring of $s$ formed by characters from the $l$-th to the $r$-th has at least one irreducible anagram. -----Input----- The first line contains a string $s$, consisting of lowercase English characters ($1 \le |s| \le 2 \cdot 10^5$). The second line contains a single integer $q$ ($1 \le q \le 10^5$)  — the number of queries. Each of the following $q$ lines contain two integers $l$ and $r$ ($1 \le l \le r \le |s|$), representing a query for the substring of $s$ formed by characters from the $l$-th to the $r$-th. -----Output----- For each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise. -----Examples----- Input aaaaa 3 1 1 2 4 5 5 Output Yes No Yes Input aabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 Output No Yes Yes Yes No No -----Note----- In the first sample, in the first and third queries, the substring is "a", which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand, in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose $s_1 = $ "a", $s_2 = $ "aa", $t_1 = $ "a", $t_2 = $ "aa" to show that it is a reducible anagram. In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline S = list([ord(x)-97 for x in readline().strip()]) N = len(S) table = [[0]*26 for _ in range(N)] for i in range(N): table[i][S[i]] = 1 for i in range(1, N): for j in range(26): table[i][j] += table[i-1][j] Q = int(readline()) Ans = [None]*Q for qu in range(Q): l, r = list(map(int, readline().split())) l -= 1 r -= 1 if l == r or S[l] != S[r]: Ans[qu] = True continue K = [table[r][j] - table[l][j] for j in range(26)] if len([k for k in K if k]) <= 2: Ans[qu] = False else: Ans[qu] = True print('\n'.join(['Yes' if s else 'No' for s in Ans])) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is learning linear algebra. Recently, he learnt that for a square matrix $M$, $\mathop{\rm trace}(M)$ is defined as the sum of all elements on the main diagonal of $M$ (an element lies on the main diagonal if its row index and column index are equal). Now, Chef wants to solve some excercises related to this new quantity, so he wrote down a square matrix $A$ with size $N\times N$. A square submatrix of $A$ with size $l\times l$ is a contiguous block of $l\times l$ elements of $A$. Formally, if $B$ is a submatrix of $A$ with size $l\times l$, then there must be integers $r$ and $c$ ($1\le r, c \le N+1-l$) such that $B_{i,j} = A_{r+i-1, c+j-1}$ for each $1 \le i, j \le l$. Help Chef find the maximum trace of a square submatrix of $A$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains $N$ space-separated integers $A_{i,1}, A_{i,2}, \dots, A_{i, N}$ denoting the $i$-th row of the matrix $A$. -----Output----- For each test case, print a single line containing one integer — the maximum possible trace. -----Constraints----- - $1 \le T \le 100$ - $2 \le N \le 100$ - $1 \le A_{i,j} \le 100$ for each valid $i, j$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 1 3 1 2 5 6 3 4 2 7 1 -----Example Output----- 13 -----Explanation----- Example case 1: The submatrix with the largest trace is 6 3 2 7 which has trace equal to $6 + 7 = 13$. (This submatrix is obtained for $r=2, c=1, l=2$.) The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here T=int(input()) for k in range(0,T): N=int(input()) matrix=[] for i in range(0,N): a=list(map(int, input().split())) matrix.append(a) max_trace = [] for i in range(0,N): trace1=0 trace2=0 for j in range(0,i+1): trace1+=matrix[j][N+j-i-1] trace2+=matrix[N+j-i-1][j] max_trace.append(trace1) max_trace.append(trace2) print(max(max_trace)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest. Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible. There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x_1, x_2, ..., x_{n}, two characters cannot end up at the same position. Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting. Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally. -----Input----- The first line on the input contains a single integer n (2 ≤ n ≤ 200 000, n is even) — the number of positions available initially. The second line contains n distinct integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} ≤ 10^9), giving the coordinates of the corresponding positions. -----Output----- Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally. -----Examples----- Input 6 0 1 3 7 15 31 Output 7 Input 2 73 37 Output 36 -----Note----- In the first sample one of the optimum behavior of the players looks like that: Vova bans the position at coordinate 15; Lesha bans the position at coordinate 3; Vova bans the position at coordinate 31; Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7. In the second sample there are only two possible positions, so there will be no bans. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import os import random import sys from typing import List, Dict class Int: def __init__(self, val): self.val = val def get(self): return self.val + 111 class Unique: def __init__(self): self.s = set() def add(self, val : int): self.s.add(val) def __contains__(self, item : int) -> bool: return self.s.__contains__(item) def ceil(top : int, bottom : int) -> int: return (top + bottom - 1) // bottom def concat(l : List[int]): return "".join(map(str, l)) def get(d : Dict[int, str], val : int) -> Dict[int, str]: return d[val] #guy who wants small moves first #then guy who wants large moves #so lets say we have 4 positions # 1, 2, 3, 4 #small wants to ban edges, because if he bans 2 or 3 he is fucked #so he bans 1 # and we have 2, 3, 4 # then large bans middle so we have 2, 4 and the ans is 2 # 0, 1, 2, 3, 4, 5, 6, 7 # 0, 1, 2, 3, 4, 5, 6 # 0, 1, 2, 3, 5, 6 # 0, 1, 2, 3, 5 # 0, 1, 3, 5 # 0, 1, 3 # 0, 3 # 0, 1, 2, 3, 4, 5, 6, 7 # 0, 4 # # 0, 3 #1 5 9 19 21 22 # 5 9 19 21 22 # 5 19 21 22 # 19 21 22 # 0, 1, 3, 7, 15 # 0, 1, 7, 15 # 0, 1, 7 # 0, 7 def slowsolve(a): a.sort() small = True while len(a) > 2: if small: if a[1] - a[0] > a[-1] - a[-2]: a.pop(0) else: a.pop() small = False else: a.pop(len(a) // 2) small = True return a[1] - a[0] def solve(a): a.sort() candelete = len(a) // 2 - 1 res = 10 ** 18 for leftdelete in range(0, candelete + 1): leftrem = leftdelete rightrem = leftdelete + candelete + 1 res = min(res, a[rightrem] - a[leftrem]) return res def prt(l): return print(' '.join(l)) def rv(): return map(int, input().split()) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if os.path.exists("test.txt"): sys.stdin = open("test.txt") n, = rv() a, = rl(1) # a = sorted([random.randrange(10**2) for _ in range(6)]) # print(a) # print(solve(a), slowsolve(a)) print(solve(a)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Saket loves to play with strings. One day , while he was having fun with Cyclic Permutations of available strings to him, he observed that despite being scarce in numbers Vowels were really clingy.Being clingy means for almost every given string, there was a Cyclic Permutation in which atleast two vowels were together. So he decided to check this property for all the available strings to him. As the number of strings can be very large, help Saket determine whether the given string is clingy or not. -----Input:----- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. First line of every test case contains an integer N$N$ denoting the length of the string. Second line contains a string S$S$ of length N$N$, consisting only of uppercase english alphabets. -----Output:----- For each test case, print a single line containing "Yes" if any of the cyclic permutations of the string is clingy else print "No". -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤N≤1000$1 \leq N \leq 1000$ - String S$S$ consists of only upper case english alphabets. -----Subtasks----- - 20 points : 1≤N≤5$1 \leq N \leq 5$ - 80 points : Original$Original$ Constraints$Constraints$ -----Sample Input:----- 2 5 AUXFC 6 XBCDEF -----Sample Output:----- Yes No -----EXPLANATION:----- Example$Example$ case1:$ case 1: $ One of the cyclic permutation is the original string itself, which has "A" and "U" together. Example$Example$ case2:$ case 2: $ None of the cyclic permutation will have 2 vowels together. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for t in range(int(input())): n=int(input()) s=input().strip() c=0 flag=0 for i in range(n): if (s[i]=="A" or s[i]=="E" or s[i]=="I" or s[i]=="O" or s[i]=="U") and (s[i-1]=="A" or s[i-1]=="E" or s[i-1]=="I" or s[i-1]=="O" or s[i-1]=="U") : flag=1 if flag and n!=1: print("Yes") else: print("No") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Johnny has some difficulty memorizing the small prime numbers. So, his computer science teacher has asked him to play with the following puzzle game frequently. The puzzle is a 3x3 board consisting of numbers from 1 to 9. The objective of the puzzle is to swap the tiles until the following final state is reached: 1 2 3 4 5 6 7 8 9 At each step, Johnny may swap two adjacent tiles if their sum is a prime number. Two tiles are considered adjacent if they have a common edge. Help Johnny to find the shortest number of steps needed to reach the goal state. -----Input----- The first line contains t, the number of test cases (about 50). Then t test cases follow. Each test case consists of a 3x3 table describing a puzzle which Johnny would like to solve. The input data for successive test cases is separated by a blank line. -----Output----- For each test case print a single line containing the shortest number of steps needed to solve the corresponding puzzle. If there is no way to reach the final state, print the number -1. -----Example----- Input: 2 7 3 2 4 1 5 6 8 9 9 8 5 2 4 1 3 7 6 Output: 6 -1 -----Output details----- The possible 6 steps in the first test case are described in the following figure: The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from collections import deque primes = {2,3,5,7,11,13,17} edges = [(0,3),(0,1),(1,2),(1,4),(2,5),(3,4),(3,6),(4,5),(4,7),(5,8),(6,7),(7,8)] x = [1,2,3,4,5,6,7,8,9] avail = {tuple(x):0} q = deque([x]) while q: curr = q.popleft(); for e in edges: if curr[e[0]]+curr[e[1]] in primes: nxt = curr[0:] nxt[e[0]],nxt[e[1]] = nxt[e[1]], nxt[e[0]] nxtt = tuple(nxt) if nxtt not in avail: avail[nxtt] = avail[tuple(curr)]+1 q.append(nxt) t = int(input()) while t: inp = input() grid = [] for i in range(3): inp = input() for j in inp.strip().split(" "): grid.append(int(j)) gridt = tuple(grid) if gridt in avail: print(avail[gridt]) else: print(-1); t-= 1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a sequence $A_1, A_2, \ldots, A_N$. For each $k$ ($1 \le k \le N$), let's define a function $f(k)$ in the following way: - Consider a sequence $B_1, B_2, \ldots, B_N$, which is created by setting $A_k = 0$. Formally, $B_k = 0$ and $B_i = A_i$ for each valid $i \neq k$. - $f(k)$ is the number of ways to split the sequence $B$ into two non-empty contiguous subsequences with equal sums. Find the sum $S = f(1) + f(2) + \ldots + f(N)$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing one integer — the sum $S$. -----Constraints----- - $1 \le T \le 10$ - $2 \le N \le 2 \cdot 10^5$ - $1 \le |A_i| \le 10^9$ for each valid $i$ -----Example Input----- 2 6 1 2 1 1 3 1 3 4 1 4 -----Example Output----- 6 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin def gt(num): if num: return num return 0 for __ in range(int(stdin.readline().split()[0])): n = int(stdin.readline().split()[0]) a = list(map(int, stdin.readline().split())) cnta = dict() cnta.setdefault(0) cntb = dict() cntb.setdefault(0) for i in a: cnta[i] = gt(cnta.get(i)) + 1 asum = 0 bsum = sum(a) ans = 0 for i in range(n-1): asum += a[i] bsum -= a[i] cnta[a[i]] = gt(cnta.get(a[i])) - 1 cntb[a[i]] = gt(cntb.get(a[i])) + 1 ans += gt(cnta.get(bsum-asum)) ans += gt(cntb.get(asum-bsum)) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ashley wrote a random number generator code. Due to some reasons, the code only generates random positive integers which are not evenly divisible by 10. She gives $N$ and $S$ as input to the random number generator. The code generates a random number with number of digits equal to $N$ and sum of digits equal to $S$. The code returns -1 if no number can be generated. Print "-1" in such cases (without quotes). Else print the minimum possible product of digits of the random number generated. -----Input:----- - First line will contain a single integer $T$, the number of testcases. - Each testcase consists of two space separated integers, $N$ and $S$. -----Output:----- For each testcase, output the answer on a new line. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 18$ - $1 \leq S \leq 5 * N$ -----Sample Input:----- 2 1 5 2 2 -----Sample Output:----- 5 1 -----EXPLANATION:----- In first testcase, the only possible number of length 1 having digit sum 5 is 5. And it's product of digits is 5. In second testcase, only possible two digit number as a generator output is 11(as 20 is divisible by 10, it is never generated) and product of it's digits is 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ Author : thekushalghosh Team : CodeDiggers """ import sys,math input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s[:len(s) - 1]) def invr(): return(map(int,input().split())) ################################################################ ############ ---- THE ACTUAL CODE STARTS BELOW ---- ############ t = 1 t = inp() for tt in range(t): n,s = invr() if n == 2 and s > 1: print(s - 1) elif n > 2 and s > 1: print(0) elif n == 1: print(s) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K (odd) to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 3 5 7 -----Sample Output:----- * * ** * * ** * * ** * * ** * * * * * * ** * -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for _ in range(t): n=int(input()) l1=[] if n==1: print('*') elif n==3: print('*') print('**') print('*') else: s1="" n1=n//2 n1+=1 for i in range(1,n1+1): s1="" if i==1: s1+='*' elif i==2: s1+='**' else: s1+='*' for j in range(2,i): s1+=' ' s1+='*' l1.append(s1) for i in l1: print(i) l1.reverse() for i in range(1,len(l1)): print(l1[i]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2^{n} - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 10^18. Note the number of elements in the output array should not be more than 10^4. If no answer is possible, print - 1. -----Input----- The only line of input consists of two space separated integers X and d (1 ≤ X, d ≤ 10^9). -----Output----- Output should consist of two lines. First line should contain a single integer n (1 ≤ n ≤ 10 000)— the number of integers in the final array. Second line should consist of n space separated integers — a_1, a_2, ... , a_{n} (1 ≤ a_{i} < 10^18). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. -----Examples----- Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 -----Note----- In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python X, D = list(map(int, input().split())) cn = 1 add0 = 1 if (X&1) else 0 ans = [] for i in range(30,0,-1): if not (X & (1<<i)): continue ans += [cn]*i add0 += 1 cn += D for i in range(add0): ans.append(cn) cn += D print(len(ans)) print(' '.join(map(str, ans))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given two integer sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_M$. For any two sequences $U_1, U_2, \ldots, U_p$ and $V_1, V_2, \ldots, V_q$, we define Score(U,V)=∑i=1p∑j=1qUi⋅Vj.Score(U,V)=∑i=1p∑j=1qUi⋅Vj.Score(U, V) = \sum_{i=1}^p \sum_{j=1}^q U_i \cdot V_j \,. You should process $Q$ queries of three types: - $1$ $L$ $R$ $X$: Add $X$ to each of the elements $A_L, A_{L+1}, \ldots, A_R$. - $2$ $L$ $R$ $X$: Add $X$ to each of the elements $B_L, B_{L+1}, \ldots, B_R$. - $3$: Print $Score(A, B)$ modulo $998,244,353$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two integers, $N$ and $M$, denoting the length of $A$ and $B$ respectively. - The second line contains $N$ integers, elements of $A$. - The third line contains $M$ integers, elements of $B$. - The next line will contain an integer, $Q$, number of queries. - Each of the next $Q$ lines will contain one of $3$ kinds of updates as mentioned in the statement It’s guaranteed that each update is a valid update operation. -----Output----- For each query of the third type, print a single line containing one integer - the answer to that query. -----Constraints----- - $1 \le T \le 10$ - $2 \le N, M, Q \le 10^5$ - $0 \le |A_i|, |B_i|, |X| \le 10^5$ -----Example Input----- 1 3 4 2 -1 5 3 3 2 4 6 3 1 2 3 -2 3 1 1 3 1 2 2 4 2 3 -----Example Output----- 72 24 90 -----Explanation----- Before the first operation, $A = [2, -1, 5],\ B = [3, 3, 2, 4]$ So, for the first operation, $Score(A,\ B) = 2*3 + 2*3 + 2*2 + 2*4$ $+ (-1)*3$ $+ (-1)*3$ $+ (-1)*2$ $+$ $(-1)*4$ $+ 5*3$ $+ 5*3$ $+ 5*2$ $+ 5*4$ $= 72.$ After the second query $A = [2, -3, 3]$, $B = [3, 3, 2, 4]$ So, for the third query, $Score(A, B) = 2*3 + 2*3 + 2*2$ $+ 2*4$ $+ (-3)*3$ $+ (-3)*3$ $+ (-3)*2$ $+ (-3)*4$ $+ 3*3$ $+ 3*3$ $+ 3*2$ $+ 3*4$ $= 24$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) l,r,x = 0,0,0 ans = [] for i in range(t): (n,m) = tuple(map(int,input().split())) a = list(map(int,input().split())) b = list(map(int,input().split())) suma = sum(a) sumb = sum(b) q = int(input()) for j in range(q): l1 = list(map(int,input().split())) if l1[0] == 1: l = l1[1] r = l1[2] x = l1[3] suma = suma + (r-l+1)*x elif l1[0] == 2: l = l1[1] r = l1[2] x = l1[3] sumb = sumb + (r-l+1)*x else: ans.append((suma*sumb)%998244353) for i in range(len(ans)): print(ans[i]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are $n$ football teams in the world. The Main Football Organization (MFO) wants to host at most $m$ games. MFO wants the $i$-th game to be played between the teams $a_i$ and $b_i$ in one of the $k$ stadiums. Let $s_{ij}$ be the numbers of games the $i$-th team played in the $j$-th stadium. MFO does not want a team to have much more games in one stadium than in the others. Therefore, for each team $i$, the absolute difference between the maximum and minimum among $s_{i1}, s_{i2}, \ldots, s_{ik}$ should not exceed $2$. Each team has $w_i$ — the amount of money MFO will earn for each game of the $i$-th team. If the $i$-th team plays $l$ games, MFO will earn $w_i \cdot l$. MFO needs to find what games in what stadiums they need to host in order to earn as much money as possible, not violating the rule they set. However, this problem is too complicated for MFO. Therefore, they are asking you to help them. -----Input----- The first line contains three integers $n$, $m$, $k$ ($3 \leq n \leq 100$, $0 \leq m \leq 1\,000$, $1 \leq k \leq 1\,000$) — the number of teams, the number of games, and the number of stadiums. The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($1 \leq w_i \leq 1\,000$) — the amount of money MFO will earn for each game of the $i$-th game. Each of the following $m$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) — the teams that can play the $i$-th game. It is guaranteed that each pair of teams can play at most one game. -----Output----- For each game in the same order, print $t_i$ ($1 \leq t_i \leq k$) — the number of the stadium, in which $a_i$ and $b_i$ will play the game. If the $i$-th game should not be played, $t_i$ should be equal to $0$. If there are multiple answers, print any. -----Example----- Input 7 11 3 4 7 8 10 10 9 3 6 2 6 1 7 6 4 3 4 6 3 1 5 3 7 5 7 3 4 2 1 4 Output 3 2 1 1 3 1 2 1 2 3 2 -----Note----- One of possible solutions to the example is shown below: [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import random import math def set_color(game, color): color_count[game[0]][game[2]] -= 1 color_count[game[1]][game[2]] -= 1 game[2] = color color_count[game[0]][game[2]] += 1 color_count[game[1]][game[2]] += 1 def fix(node): minimum = math.inf maximum = 0 for i in range(k): minimum = min(minimum, color_count[node][i]) maximum = max(maximum, color_count[node][i]) if maximum - minimum <= 2: return False rand = 0 for game in games: if (game[0] == node or game[1] == node) and color_count[node][game[2]] == maximum: rand = r(1,k) set_color(game, rand % k) return True return False n, m, k = list(map(int,input().split())) games = [[0 for _ in range(4)] for _ in range(m)] color_count = [[0 for _ in range(k)] for _ in range(n)] answers = [0 for _ in range(m)] _ = list(map(int,input().split())) color = 0 r = lambda x,y : random.randint(x,y) for i in range(m): a, b = list(map(int,input().split())) color = r(1,k) % k games[i] = [a-1,b-1,color,i] color_count[games[i][0]][color] += 1 color_count[games[i][1]][color] += 1 bad = True while bad: random.shuffle(games) bad = False for i in range(n): while(fix(i)): bad = True for game in games: answers[game[3]] = game[2] + 1 for i in range(m): print(answers[i]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. -----Input----- The first line of the input contains a positive integer n (1 ≤ n ≤ 1 000 000) — the number of days in a year on Mars. -----Output----- Print two integers — the minimum possible and the maximum possible number of days off per year on Mars. -----Examples----- Input 14 Output 4 4 Input 2 Output 0 2 -----Note----- In the first sample there are 14 days in a year on Mars, and therefore independently of the day a year starts with there will be exactly 4 days off . In the second sample there are only 2 days in a year on Mars, and they can both be either work days or days off. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n=int(input()) r=n%7 d=n//7 print(2*d+max(0,r-5),2*d+min(r,2)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Uttu got to know about an interesting two-player mobile game recently and invites his friend Gangwar to try it out with him. Gangwar, however, has been playing this game since it was out 5 years ago and is a Legendary Grandmaster at it. Uttu immediately thought of somehow cheating in this game to beat Gangwar. But the most he could do was choose if he wanted to go "First" or if he wanted to go "Second" in this alternative turn based game. Help Uttu choose so that he will always win regardless of Gangwar's moves.Description of the game You are playing on a continent name Tamriel. This continent have $N$ towns numbered from $1$ to $N$ where town $1$ is the capital. These towns are connected to each other by $N-1$ roads. Any two towns are connected by some series of roads, i.e., You can go from any town to any other town using these roads. Each town $i$ some initial amout of soldiers $S_i$ in it. At every move, a player can choose a town other than the capital $i$ and move some non-zero amount of its current soldiers to a town which is one step closer towards the capital. After the first move, the moves are alternated between the players. The player who cannot make a move loses.Input - The first line contains a single integer $N$ - The second line contains a $N$ space seperated integers denoting $S_1,S_2,\dots,S_n$ - The $N-1$ subsequent lines contain two space seperated integers $u$ and $v$, denoting that the town $u$ and town $v$ are connected by a road.Output - Print "First" or "Second" based on what Uttu should choose to win.Constraints - $ 2 \leq N \leq {2}\times{10}^{5}$ - $ 1 \leq S_i \leq {10}^{9}$ for each valid $i$ - $ 1 \leq u,v \leq N$Sample Input 1 2 10 10 1 2 Sample Output 1 First Explanation 1 Uttu will move the $10$ soldiers at town $2$ to the capital (town $1$). After this Gangwar cannot make a move, so he loses.Sample Input 2 3 1 1 1 1 2 1 3 Sample Output 2 Second Explanation 2 Gangwar has options: either move the soldier at town $2$, or move the soldier at town $3$. Whatever he choses, Uttu will chose the other town's soldier to move. And then Gangwar loses. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python ''' J A I ~ S H R E E ~ R A M ''' # Title: cc-CKOJ20D.py # created on: 20-07-2020 at 20:46:04 # Creator & Template : Udit Gupta "@luctivud" # https://github.com/luctivud # https://www.linkedin.com/in/udit-gupta-1b7863135/ import math; from collections import * import sys; from functools import reduce from itertools import groupby # sys.setrecursionlimit(10**6) def get_ints(): return map(int, input().strip().split()) def get_list(): return list(get_ints()) def get_string(): return list(input().strip().split()) def printxsp(*args): return print(*args, end="") def printsp(*args): return print(*args, end=" ") DIRECTIONS = [[0, 1], [0, -1], [1, 0], [1, -1]] #up, down, right, left NEIGHBOURS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if (i!=0 or j!=0)] OrdUnicode_a = ord('a'); OrdUnicode_A = ord('A') CAPS_ALPHABETS = {chr(i+OrdUnicode_A) : i for i in range(26)} SMOL_ALPHABETS = {chr(i+OrdUnicode_a) : i for i in range(26)} MOD_JOHAN = int(1e9)+7; MOD_LIGHT = 998244353; INFINITY = float('inf') MAXN_EYEPATCH = int(1e5)+1; MAXN_FULLMETAL = 501 # Custom input output is now piped through terminal commands. def bfs(s): queue = deque() visited = set() visited.add(1) queue.append((1, 0)) while len(queue): node, dep = queue.popleft() dep += 1 for zen in tree[node]: if zen not in visited: visited.add(zen) if dep & 1: global xorsum xorsum ^= li[zen] queue.append((zen, dep)) # print(queue) # for _testcases_ in range(int(input())): n = int(input()) li = [0] + get_list() tree = defaultdict(list) for _ in range(n-1): a, b = get_ints() tree[a].append(b) tree[b].append(a) xorsum = 0 bfs(1) # print(xorsum) print("First" if xorsum else "Second") ''' THE LOGIC AND APPROACH IS MINE ( UDIT GUPTA ) Link may be copy-pasted here, otherwise. ''' ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem: Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one. To be more clear, consider all integer sequence with length k (a_1, a_2, ..., a_{k}) with $\sum_{i = 1}^{k} 2^{a_{i}} = n$. Give a value $y = \operatorname{max}_{1 \leq i \leq k} a_{i}$ to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest. For definitions of powers and lexicographical order see notes. -----Input----- The first line consists of two integers n and k (1 ≤ n ≤ 10^18, 1 ≤ k ≤ 10^5) — the required sum and the length of the sequence. -----Output----- Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second line — the required sequence. It is guaranteed that the integers in the answer sequence fit the range [ - 10^18, 10^18]. -----Examples----- Input 23 5 Output Yes 3 3 2 1 0 Input 13 2 Output No Input 1 2 Output Yes -1 -1 -----Note----- Sample 1: 2^3 + 2^3 + 2^2 + 2^1 + 2^0 = 8 + 8 + 4 + 2 + 1 = 23 Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest. Answers like (4, 1, 1, 1, 0) do not have the minimum y value. Sample 2: It can be shown there does not exist a sequence with length 2. Sample 3: $2^{-1} + 2^{-1} = \frac{1}{2} + \frac{1}{2} = 1$ Powers of 2: If x > 0, then 2^{x} = 2·2·2·...·2 (x times). If x = 0, then 2^{x} = 1. If x < 0, then $2^{x} = \frac{1}{2^{-x}}$. Lexicographical order: Given two different sequences of the same length, (a_1, a_2, ... , a_{k}) and (b_1, b_2, ... , b_{k}), the first one is smaller than the second one for the lexicographical order, if and only if a_{i} < b_{i}, for the first i where a_{i} and b_{i} differ. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import defaultdict def solve(n, k): as_bin = bin(n)[2:] cnt = defaultdict(int) cnt.update({i : 1 for i, b in enumerate(reversed(as_bin)) if b == '1'}) curr_len = len(cnt) curr_pow = len(as_bin) - 1 if curr_len > k: return None while True: new_len = curr_len + cnt[curr_pow] if new_len > k: break cnt[curr_pow - 1] += 2 * cnt[curr_pow] del cnt[curr_pow] curr_pow -= 1 curr_len = new_len i = min(cnt.keys()) while curr_len < k: cnt[i] -= 1 cnt[i - 1] += 2 curr_len += 1 i -= 1 ans = [] for i in sorted(list(cnt.keys()), reverse=True): ans.extend([i] * cnt[i]) return ans n, k = [int(v) for v in input().split()] ans = solve(n, k) if ans is None: print('No') else: print('Yes') print(' '.join(str(c) for c in ans)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Indian National Olympiad in Informatics 2015 A string is any nonempty sequence of 0s and 1s. Examples of strings are 00, 101, 111000, 1, 0, 01. The length of a string is the number of symbols in it. For example, the length of 111000 is 6. If u and v are strings, then uv is the string obtained by concatenating u and v. For example if u = 110 and v = 0010 then uv = 1100010. A string w is periodic if there exists a string v such that w = vn = vv · · · v (n times), for some n ≥ 2. Note that in this case the length of v is strictly less than that of w. For example, 110110 is periodic, because it is vv for v = 110. Given a positive integer N , find the number of strings of length N which are not periodic. Report the answer modulo M . The non-periodic strings of length 2 are 10 and 01. The non- periodic strings of length 3 are 001, 010, 011, 100, 101, and 110. -----Input format----- A single line, with two space-separated integers, N and M . -----Output format----- A single integer, the number of non-periodic strings of length N , modulo M . -----Test Data----- In all subtasks, 2 ≤ M ≤ 108. The testdata is grouped into 4 subtasks. Subtask 1 (10 marks) 1 ≤ N ≤ 4000. N is the product of two distinct prime numbers. Subtask 2 (20 marks) 1 ≤ N ≤ 4000. N is a power of a prime number. Subtask 3 (35 marks) 1 ≤ N ≤ 4000. Subtask 4 (35 marks) 1 ≤ N ≤ 150000. -----Example----- Here is the sample input and output corresponding to the example above: -----Sample input----- 3 176 -----Sample output----- 6 Note: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect! The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def offset(l, flag): x = 0 # print(l) for i in range(1, len(l)): temp = [] for j in range(i): v = getbig(l[i], l[j], fs) if v > 1: temp.append(v) if flag: x += 2**v - 2 else: x -= 2**v - 2 x += offset(temp, not flag) return x def getbig(v1, v2, factors): x = 1 for f in factors: while v1%f == 0 and v2%f == 0: v1//=f v2//=f x*=f return x def prime_factors(n): i = 2 factors = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(i) if n > 1: factors.add(n) return factors n,m = map(int, input().split()) if n == 1: print(1) else: fs = prime_factors(n) fs.discard(n) ans = 2**n-2 temp = [] for v in fs: v = n//v temp.append(v) ans -= 2**v - 2 # print(ans) ans += offset(temp, True) # print(fs) print(ans%m) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have been recently hired as a developer in CodeChef. Your first mission is to implement a feature that will determine the number of submissions that were judged late in a contest. There are $N$ submissions, numbered $1$ through $N$. For each valid $i$, the $i$-th submission was submitted at time $S_i$ and judged at time $J_i$ (in minutes). Submitting and judging both take zero time. Please determine how many submissions received their verdicts after a delay of more than $5$ minutes. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of the input contains a single integer $N$. - $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $S_i$ and $J_i$. -----Output----- For each test case, print a single line containing one integer — the number of submissions for which the judging was delayed by more than 5 minutes. -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 100$ - $1 \le S_i \le J_i \le 300$ for each valid $i$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 1 5 1 3 4 4 4 10 1 11 2 7 -----Example Output----- 2 -----Explanation----- Example case 1: The delays of the respective submissions are $2$ minutes, $0$ minutes, $6$ minutes, $10$ minutes and $5$ minutes. Only submissions $3$ and $4$ are delayed by more than $5$ minutes, hence the answer is $2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for t in range(int(input())): c=0 for i in range(int(input())): s,j=list(map(int,input().split())) if (j-s)>5: c+=1 print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given positive integers $L$ and $R$. You have to find the sum S=∑i=LR(L∧(L+1)∧…∧i),S=∑i=LR(L∧(L+1)∧…∧i),S = \sum_{i=L}^R \left(L \wedge (L+1) \wedge \ldots \wedge i\right) \,, where $\wedge$ denotes the bitwise AND operation. Since the sum could be large, compute it modulo $10^9+7$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $L$ and $R$. -----Output----- For each test case, print a single line containing one integer — the sum $S$ modulo $10^9+7$. -----Constraints----- - $1 \le T \le 10^5$ - $1 \le L \le R \le 10^{18}$ -----Example Input----- 2 1 4 4 10 -----Example Output----- 1 16 -----Explanation----- Example case 1: The sum is 1 + 1 AND 2 + 1 AND 2 AND 3 + 1 AND 2 AND 3 AND 4 = 1 + 0 + 0 + 0 = 1. Example case 2: The sum is 4 + 4 AND 5 + 4 AND 5 AND 6 + 4 AND 5 AND 6 AND 7 + … + 4 AND 5 AND … AND 10 = 4 + 4 + … + 0 = 16. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python l= [] for i in range(62): l.append(2**i) T = int(input()) flag = 0 for t in range(T): L,R = [int(i) for i in input().split()] bL = bin(L) lL = len(bL)-2 index = 1 ans = 0 temp = 0 while(index<=lL): temp = L%l[index] if temp>=l[index-1]: if(l[index]-temp<=R-L+1): ans= (ans +(l[index-1])*(l[index]-temp))%1000000007 else : ans=(ans+(l[index-1])*(R-L+1))%1000000007 index+=1 print(ans) # 4378578345 584758454958 # 18091037982636824985 8589934592 4429185025 4294967296 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given an integer N, Chef wants to find the smallest positive integer M such that the bitwise XOR of M and M+1 is N. If no such M exists output -1. -----Input----- The first line of input contain an integer T denoting the number of test cases. Each of the following T lines contains an integer N for that test case. -----Output----- For each test case, output a single line containing the number M or -1 as described above. -----Constraints----- - 1 ≤ T ≤ 5000 - 1 ≤ N ≤ 230 -----Example----- Input: 1 3 Output: 1 -----Explanation-----First Example : M desired in the problem would be 1. As bitwise XOR of 1 and 2 is equal to 3. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # from math import log2 # N = 10000 # for i in range(1,N): # # print(i) # for m in range(i): # if( (m^(m+1))==i ): # print(i) # print(m,m+1,bin(m)[2:]) # print() # break # # else: # # print(-1) # # print() T = int(input()) ans = [] for _ in range(T): N = int(input()) # x = log2(N+1) if(N==1): ans.append(2) elif('0' not in bin(N)[2:]): ans.append(N//2) else: ans.append(-1) for i in ans: print(i) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef loves to play with arrays by himself. Today, he has an array A consisting of N distinct integers. He wants to perform the following operation on his array A. - Select a pair of adjacent integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation will be equal to the smaller of them. Find out minimum sum of costs of operations needed to convert the array into a single element. -----Input----- First line of input contains a single integer T denoting the number of test cases. First line of each test case starts with an integer N denoting the size of the array A. Next line of input contains N space separated integers, where the ith integer denotes the value Ai. -----Output----- For each test case, print the minimum cost required for the transformation. -----Constraints----- - 1 ≤ T ≤ 10 - 2 ≤ N ≤ 50000 - 1 ≤ Ai ≤ 105 -----Subtasks----- - Subtask 1 : 2 ≤ N ≤ 15 : 35 pts - Subtask 2 : 2 ≤ N ≤ 100 : 25 pts - Subtask 3 : 2 ≤ N ≤ 50000 : 40 pts -----Example----- Input 2 2 3 4 3 4 2 5 Output 3 4 -----Explanation-----Test 1 : Chef will make only 1 move: pick up both the elements (that is, 3 and 4), remove the larger one (4), incurring a cost equal to the smaller one (3). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import * for t in range(int(input())): n = int(input()) numberlist = list(map(int,input().split())) numberlist.sort() print(numberlist[0]* ( len(numberlist) -1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's write all the positive integer numbers one after another from $1$ without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the $k$-th digit of this sequence. -----Input----- The first and only line contains integer $k$ ($1 \le k \le 10^{12}$) — the position to process ($1$-based index). -----Output----- Print the $k$-th digit of the resulting infinite sequence. -----Examples----- Input 7 Output 7 Input 21 Output 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python k = int(input()) if k<=9: print(k) else: num_arr = [9*(i+1)* 10**i for i in range(11)] index = 0 while True: if k<=num_arr[index]: break else: k -= num_arr[index] index += 1 digit = index+1 k += digit-1 num = k//digit offset = k%digit string_num = str(10**(digit-1)+ num-1) print(string_num[offset]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $n$ integers, now it's time to distribute them between his friends rationally... Lee has $n$ integers $a_1, a_2, \ldots, a_n$ in his backpack and he has $k$ friends. Lee would like to distribute all integers in his backpack between his friends, such that the $i$-th friend will get exactly $w_i$ integers and each integer will be handed over to exactly one friend. Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get. Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Next $3t$ lines contain test cases — one per three lines. The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$; $1 \le k \le n$) — the number of integers Lee has and the number of Lee's friends. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-10^9 \le a_i \le 10^9$) — the integers Lee has. The third line contains $k$ integers $w_1, w_2, \ldots, w_k$ ($1 \le w_i \le n$; $w_1 + w_2 + \ldots + w_k = n$) — the number of integers Lee wants to give to each friend. It's guaranteed that the sum of $n$ over test cases is less than or equal to $2 \cdot 10^5$. -----Output----- For each test case, print a single integer — the maximum sum of happiness Lee can achieve. -----Example----- Input 3 4 2 1 13 7 17 1 3 6 2 10 10 10 10 11 11 3 3 4 4 1000000000 1000000000 1000000000 1000000000 1 1 1 1 Output 48 42 8000000000 -----Note----- In the first test case, Lee should give the greatest integer to the first friend (his happiness will be $17 + 17$) and remaining integers to the second friend (his happiness will be $13 + 1$). In the second test case, Lee should give $\{10, 10, 11\}$ to the first friend and to the second friend, so the total happiness will be equal to $(11 + 10) + (11 + 10)$ In the third test case, Lee has four friends and four integers, it doesn't matter how he distributes the integers between his friends. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def solve(): n, k = map(int,input().split()) lst1 = list(map(int,input().split())) lst1.sort(reverse=True) ind = 0 ans = 0 lst2 = list(map(int,input().split())) lst2.sort() for i in range(k): lst2[i] -= 1 if lst2[i] == 0: ans += lst1[ind] ans += lst1[ind] ind += 1 lst2.sort() for i in lst2: if i != 0: ind += i - 1 ans += lst1[ind] ind += 1 print(ans) for i in range(int(input())): solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Alice and Bob are playing a fun game of tree tag. The game is played on a tree of $n$ vertices numbered from $1$ to $n$. Recall that a tree on $n$ vertices is an undirected, connected graph with $n-1$ edges. Initially, Alice is located at vertex $a$, and Bob at vertex $b$. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most $da$ from the current vertex. And in a move, Bob can jump to a vertex with distance at most $db$ from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most $10^{100}$ moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). Description of the test cases follows. The first line of each test case contains five integers $n,a,b,da,db$ ($2\le n\le 10^5$, $1\le a,b\le n$, $a\ne b$, $1\le da,db\le n-1$)  — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following $n-1$ lines describe the edges of the tree. The $i$-th of these lines contains two integers $u$, $v$ ($1\le u, v\le n, u\ne v$), denoting an edge between vertices $u$ and $v$. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$. -----Output----- For each test case, output a single line containing the winner of the game: "Alice" or "Bob". -----Example----- Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice -----Note----- In the first test case, Alice can win by moving to vertex $1$. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. [Image] In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices $1$ or $6$ is farthest from Alice. [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin from collections import deque def NC_Dij(lis,start): ret = [float("inf")] * len(lis) ret[start] = 0 q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() for nex in lis[now]: if ret[nex] > ret[now] + 1: ret[nex] = ret[now] + 1 plis[nex] = now q.append(nex) return ret,plis tt = int(stdin.readline()) for loop in range(tt): n,a,b,da,db = list(map(int,stdin.readline().split())) N = n a -= 1 b -= 1 lis = [ [] for i in range(n)] for i in range(n-1): u,v = list(map(int,stdin.readline().split())) u -= 1 v -= 1 lis[u].append(v) lis[v].append(u) if 2*da >= db: print ("Alice") continue fa,tmp = NC_Dij(lis,a) if fa[b] <= da: print ("Alice") continue mv = 0 for i in range(N): if fa[i] > fa[mv]: mv = i fv,tmp = NC_Dij(lis,mv) if max(fv) <= 2*da: print ("Alice") else: print ("Bob") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Little Elephant likes permutations. This time he has a permutation A[1], A[2], ..., A[N] of numbers 1, 2, ..., N. He calls a permutation A good, if the number of its inversions is equal to the number of its local inversions. The number of inversions is equal to the number of pairs of integers (i; j) such that 1 ≤ i < j ≤ N and A[i] > A[j], and the number of local inversions is the number of integers i such that 1 ≤ i < N and A[i] > A[i+1]. The Little Elephant has several such permutations. Help him to find for each permutation whether it is good or not. Print YES for a corresponding test case if it is good and NO otherwise. -----Input----- The first line of the input contains a single integer T, the number of test cases. T test cases follow. The first line of each test case contains a single integer N, the size of a permutation. The next line contains N space separated integers A[1], A[2], ..., A[N]. -----Output----- For each test case output a single line containing the answer for the corresponding test case. It should be YES if the corresponding permutation is good and NO otherwise. -----Constraints----- 1 ≤ T ≤ 474 1 ≤ N ≤ 100 It is guaranteed that the sequence A[1], A[2], ..., A[N] is a permutation of numbers 1, 2, ..., N. -----Example----- Input: 4 1 1 2 2 1 3 3 2 1 4 1 3 2 4 Output: YES YES NO YES -----Explanation----- Case 1. Here N = 1, so we have no pairs (i; j) with 1 ≤ i < j ≤ N. So the number of inversions is equal to zero. The number of local inversion is also equal to zero. Hence this permutation is good. Case 2. Here N = 2, and we have one pair (i; j) with 1 ≤ i < j ≤ N, the pair (1; 2). Since A[1] = 2 and A[2] = 1 then A[1] > A[2] and the number of inversions is equal to 1. The number of local inversion is also equal to 1 since we have one value of i for which 1 ≤ i < N (the value i = 1) and A[i] > A[i+1] for this value of i since A[1] > A[2]. Hence this permutation is also good. Case 3. Here N = 3, and we have three pairs (i; j) with 1 ≤ i < j ≤ N. We have A[1] = 3, A[2] = 2, A[3] = 1. Hence A[1] > A[2], A[1] > A[3] and A[2] > A[3]. So the number of inversions is equal to 3. To count the number of local inversion we should examine inequalities A[1] > A[2] and A[2] > A[3]. They both are satisfied in our case, so we have 2 local inversions. Since 2 ≠ 3 this permutations is not good. Case 4. Here we have only one inversion and it comes from the pair (2; 3) since A[2] = 3 > 2 = A[3]. This pair gives also the only local inversion in this permutation. Hence the number of inversions equals to the number of local inversions and equals to one. So this permutation is good. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin t = int(stdin.readline()) def count(n, arr): loc = 0 glob = 0 for i in range(n-1): if arr[i] > arr[i+1]: loc += 1 for i in range(n-1): for j in range(i+1, n): if glob > loc: return 0 if arr[i] > arr[j]: glob += 1; if glob == loc: return 1 return 0 for _ in range(t): n = int(stdin.readline()) arr = list(map(int, stdin.readline().split())) result = count(n, arr) if result: print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest). For any integer $k$ and positive integer $n$, let $k\bmod n$ denote the remainder when $k$ is divided by $n$. More formally, $r=k\bmod n$ is the smallest non-negative integer such that $k-r$ is divisible by $n$. It always holds that $0\le k\bmod n\le n-1$. For example, $100\bmod 12=4$ and $(-1337)\bmod 3=1$. Then the shuffling works as follows. There is an array of $n$ integers $a_0,a_1,\ldots,a_{n-1}$. Then for each integer $k$, the guest in room $k$ is moved to room number $k+a_{k\bmod n}$. After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests. -----Input----- Each test consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 10^4$) — the number of test cases. Next $2t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 2\cdot 10^5$) — the length of the array. The second line of each test case contains $n$ integers $a_0,a_1,\ldots,a_{n-1}$ ($-10^9\le a_i\le 10^9$). It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot 10^5$. -----Output----- For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower). -----Example----- Input 6 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11 Output YES YES YES NO NO YES -----Note----- In the first test case, every guest is shifted by $14$ rooms, so the assignment is still unique. In the second test case, even guests move to the right by $1$ room, and odd guests move to the left by $1$ room. We can show that the assignment is still unique. In the third test case, every fourth guest moves to the right by $1$ room, and the other guests move to the right by $5$ rooms. We can show that the assignment is still unique. In the fourth test case, guests $0$ and $1$ are both assigned to room $3$. In the fifth test case, guests $1$ and $2$ are both assigned to room $2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) l = [int(x) for x in input().split()] vals = [(x + i) % n for i, x in enumerate(l)] print("YES" if len(set(vals)) == n else "NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sereja has an array A of N positive integers : A[1], A[2], A[3], ... , A[N]. In a single operation on the array, he performs the following two steps : - Pick two indices i, j s.t. A[i] > A[j] - A[i] -= A[j] Sereja can apply these operations any number of times (possibly zero), such that the sum of resulting elements of the array is as small as possible. Help Sereja find this minimum sum. -----Input----- First line of input contains an integer T - the number of test cases. T test cases follow. First line of each test case contains the integer N. The next line contains N integers — A[1], A[2], A[3], ... , A[N]. -----Output----- For each test case, output a single line with the answer. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 105 - 1 ≤ A[i] ≤ 109 -----Example----- Input: 2 1 1 3 2 4 6 Output: 1 6 -----Explanation----- Example case 2. In this case, one possible way in which Sereja can perform the operations could be as follows. - Pick i = 2, j = 1. A[2] -= A[1]. Now the resulting array would be [2, 2, 6]. - Pick i = 3, j = 2. A[3] -= A[2]. Now the resulting array would be [2, 2, 4]. - Pick i = 3, j = 2. A[3] -= A[2]. Now the resulting array would be [2, 2, 2]. As the resulting array is [2 2 2], so the sum is 6. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def gcd(a,b): if b==0: return a else: return gcd(b,a%b) def main(): t=int(input()) while t!=0: t=t-1 n=int(input()) if n==1: print(input()) else: a=list(map(int,input().split(" "))) p=a[0] for i in range(1,n): p=gcd(p,a[i]) if p==1: break print(n*p) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Bob just learned about bitwise operators. Since Alice is an expert, she decided to play a game, she will give a number $x$ to Bob and will ask some questions: There will be 4 different kinds of queries:- - Alice gives an integer $i$ and Bob has to report the status of the $i^{th}$ bit in $x$, the answer is $"ON"$ if it is on else $"OFF"$. - Alice gives an integer $i$ and Bob has to turn on the $i^{th}$ bit in $x$. - Alice gives an integer $i$ and Bob has to turn off the $i^{th}$ bit in $x$. - Alice gives two integers $p$ and $q$ and in the binary representation of $x$ Bob has to swap the $p^{th}$ and the $q^{th}$ bits. The value of $x$ changes after any update operation. positions $i$, $p$, and $q$ are always counted from the right or from the least significant bit. If anyone of $i$, $p$, or $q$ is greater than the number of bits in the binary representation of $x$, consider $0$ at that position. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - the first line of each test case contains two space-separated integers $x, Q$. - $2Q$ lines follow. - first line is an integer, the query type. - for each query of type 1 to 3, there will be the integer $i$ - for the query of type 4, there will be two space-separated integers, the integers $p, q$ -----Output:----- For the queries of the first kind, print $"ON"$ or $"OFF"$. -----Constraints----- - $1 \leq T \leq 10^3$ - $1 \leq x \leq 10^9$ - $1 \leq Q \leq 10^3$ - $1 \leq i,p,q \leq 30$ -----Sample Input----- 1 2 2 2 1 1 1 -----Sample Output:----- ON -----EXPLANATION:----- the binary representation of 2 is 10 for query 1, we just have to update x to 11 (or 3 in decimal). for the next query, x is now 3 or 11 in binary so the answer is ON. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t=int(input()) while t>0: n,q=list(map(int,input().split())) blst=[0] for i in range(1,65): blst.append(0) i=1 while n>0: if n%2: blst[i]=1 n//=2 i+=1 while q>0: n=int(input()) if n==1: p=int(input()) if blst[p]: print('ON') else: print('OFF') elif n==2: p=int(input()) if blst[p]==0: blst[p]=1 elif n==3: p=int(input()) if blst[p]==1: blst[p]=0 else: p,r=list(map(int,input().split())) if blst[p]!=blst[r]: blst[p]+=1 blst[p]%=2 blst[r]+=1 blst[r]%=2 q-=1 t-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: $Harshad$ $Mehta$ is planning a new scam with the stocks he is given a stock of integer price S and a number K . $harshad$ has got the power to change the number $S$ at most $K$ times In order to raise the price of stock and now cash it for his benefits Find the largest price at which $harshad$ can sell the stock in order to maximize his profit -----Input:----- - First line will contain $S$ and $K$ , the price of the stock and the number K -----Output:----- Print the largest profit he can make in a single line. -----Constraints----- - S can take value upto 10^18 NOTE: use 64 int number to fit range - K can take value from [0.. 9] -----Sample Input:----- 4483 2 -----Sample Output:----- 9983 -----EXPLANATION:----- First two digits of the number are changed to get the required number. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a,b=[int(_) for _ in input().split()] if b==0: print(a) else: l=[] a=str(a) for i in range(len(a)): l.append(a[i]) for i in range(len(l)): if b==0: break if l[i]=='9': continue else: l[i]='9' b-=1 s='' for i in l: s+=i print(s) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an array $a$, consisting of $n$ integers. Each position $i$ ($1 \le i \le n$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were. For example, let $a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$, the underlined positions are locked. You can obtain the following arrays: $[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$; $[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$; $[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$; $[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$; and some others. Let $p$ be a sequence of prefix sums of the array $a$ after the rearrangement. So $p_1 = a_1$, $p_2 = a_1 + a_2$, $p_3 = a_1 + a_2 + a_3$, $\dots$, $p_n = a_1 + a_2 + \dots + a_n$. Let $k$ be the maximum $j$ ($1 \le j \le n$) such that $p_j < 0$. If there are no $j$ such that $p_j < 0$, then $k = 0$. Your goal is to rearrange the values in such a way that $k$ is minimum possible. Output the array $a$ after the rearrangement such that the value $k$ for it is minimum possible. If there are multiple answers then print any of them. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of testcases. Then $t$ testcases follow. The first line of each testcase contains a single integer $n$ ($1 \le n \le 100$) — the number of elements in the array $a$. The second line of each testcase contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^5 \le a_i \le 10^5$) — the initial array $a$. The third line of each testcase contains $n$ integers $l_1, l_2, \dots, l_n$ ($0 \le l_i \le 1$), where $l_i = 0$ means that the position $i$ is unlocked and $l_i = 1$ means that the position $i$ is locked. -----Output----- Print $n$ integers — the array $a$ after the rearrangement. Value $k$ (the maximum $j$ such that $p_j < 0$ (or $0$ if there are no such $j$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them. -----Example----- Input 5 3 1 3 2 0 0 0 4 2 -3 4 -1 1 1 1 1 7 -8 4 -2 -6 4 7 1 1 0 0 0 1 1 0 5 0 1 -4 6 3 0 0 0 1 1 6 -1 7 10 4 -8 -1 1 0 0 0 0 1 Output 1 2 3 2 -3 4 -1 -8 -6 1 4 4 7 -2 -4 0 1 6 3 -1 4 7 -8 10 -1 -----Note----- In the first testcase you can rearrange all values however you want but any arrangement will result in $k = 0$. For example, for an arrangement $[1, 2, 3]$, $p=[1, 3, 6]$, so there are no $j$ such that $p_j < 0$. Thus, $k = 0$. In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one. In the third testcase the prefix sums for the printed array are $p = [-8, -14, -13, -9, -5, 2, 0]$. The maximum $j$ is $5$, thus $k = 5$. There are no arrangements such that $k < 5$. In the fourth testcase $p = [-4, -4, -3, 3, 6]$. In the fifth testcase $p = [-1, 3, 10, 2, 12, 11]$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math from collections import deque from sys import stdin, stdout from string import ascii_letters import sys letters = ascii_letters input = stdin.readline #print = stdout.write for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) can = list(map(int, input().split())) vals = sorted([i for i in range(n) if not can[i]], key=lambda x: -arr[x]) res = [0] * n last = 0 for i in range(n): if can[i]: res[i] = arr[i] else: res[i] = arr[vals[last]] last += 1 print(*res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: We start with a permutation $a_1, a_2, \ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times. On the $i$-th iteration, we select an index $t_i$ ($1 \le t_i \le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are within the array bounds) to the right end of the array $b$. Then we move elements $a_{t_i+1}, \ldots, a_n$ to the left in order to fill in the empty space. You are given the initial permutation $a_1, a_2, \ldots, a_n$ and the resulting array $b_1, b_2, \ldots, b_k$. All elements of an array $b$ are distinct. Calculate the number of possible sequences of indices $t_1, t_2, \ldots, t_k$ modulo $998\,244\,353$. -----Input----- Each test contains multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100\,000$), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers $n, k$ ($1 \le k < n \le 200\,000$): sizes of arrays $a$ and $b$. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$): elements of $a$. All elements of $a$ are distinct. The third line of each test case contains $k$ integers $b_1, b_2, \ldots, b_k$ ($1 \le b_i \le n$): elements of $b$. All elements of $b$ are distinct. The sum of all $n$ among all test cases is guaranteed to not exceed $200\,000$. -----Output----- For each test case print one integer: the number of possible sequences modulo $998\,244\,353$. -----Example----- Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 -----Note----- $\require{cancel}$ Let's denote as $a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$ an operation over an element with index $i$: removal of element $a_i$ from array $a$ and appending element $a_{i+1}$ to array $b$. In the first example test, the following two options can be used to produce the given array $b$: $1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2$; $(t_1, t_2, t_3) = (4, 3, 2)$; $1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5$; $(t_1, t_2, t_3) = (4, 1, 2)$. In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to $4$, namely number $3$, which means that it couldn't be added to array $b$ on the second step. In the third example test, there are four options to achieve the given array $b$: $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5$; $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$; The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline T = int(readline()) MOD = 998244353 Ans = [None]*T for qu in range(T): N, K = map(int, readline().split()) A = [0] + list(map(int, readline().split())) + [0] B = list(map(int, readline().split())) C = [None]*(N+1) for i in range(1, N+1): C[A[i]] = i ans = 1 for b in B[::-1]: bi = C[b] res = 0 if A[bi-1]: res += 1 if A[bi+1]: res += 1 A[bi] = 0 ans = ans*res%MOD Ans[qu] = ans print('\n'.join(map(str, Ans))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A robot is initially at $(0,0)$ on the cartesian plane. It can move in 4 directions - up, down, left, right denoted by letter u, d, l, r respectively. More formally: - if the position of robot is $(x,y)$ then u makes it $(x,y+1)$ - if the position of robot is $(x,y)$ then l makes it $(x-1,y)$ - if the position of robot is $(x,y)$ then d makes it $(x,y-1)$ - if the position of robot is $(x,y)$ then r makes it $(x+1,y)$ The robot is performing a counter-clockwise spiral movement such that his movement can be represented by the following sequence of moves - ulddrruuulllddddrrrruuuuu… and so on. A single move takes 1 sec. You have to find out the position of the robot on the cartesian plane at $t$ second. -----Input:----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $t$. -----Output:----- For each test case, print two space-separated integers, $(x,y)$ — the position of the robot. -----Constraints----- - $1 \leq T \leq 10^6$ - $1 \leq t \leq 10^{18}$ -----Sample Input:----- 5 1 2 3 50 12233443 -----Sample Output:----- 0 1 -1 1 -1 0 2 4 -1749 812 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python z = int(input()) i = 0 while i < z: n = int(input()) p = int(n**(0.5)) if p*(p+1) < n: p += 1 # print("P", p) x, y = 0, 0 q = 0 flag = True if p*(p+1) == n: # print("Even steps, nice") q = p else: # remaining steps q = p-1 flag = False if q%2 : # odd x -= ((q+1)//2) y += ((q+1)//2) else : x += (q//2) y -= (q//2) if flag: print(x, y) else: # remaining steps l = q*(q+1) t = p*(p+1) diff = t-l # print(x, y) if x < 0: # left if n-l >= diff//2: y *= (-1) l += (diff//2) x += (n-l) else : y -= (n-l) else: # right if n-l >= diff//2: y *= (-1) y += 1 l += (diff//2) x -= (n-l) else : y += (n-l) # print("Remaining steps: ", n-l) print(x, y) i+=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Permutation $p$ is a sequence of integers $p=[p_1, p_2, \dots, p_n]$, consisting of $n$ distinct (unique) positive integers between $1$ and $n$, inclusive. For example, the following sequences are permutations: $[3, 4, 1, 2]$, $[1]$, $[1, 2]$. The following sequences are not permutations: $[0]$, $[1, 2, 1]$, $[2, 3]$, $[0, 1, 2]$. The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $p$ of length $n$. You don't know this permutation, you only know the array $q$ of prefix maximums of this permutation. Formally: $q_1=p_1$, $q_2=\max(p_1, p_2)$, $q_3=\max(p_1, p_2,p_3)$, ... $q_n=\max(p_1, p_2,\dots,p_n)$. You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $q$ for this permutation is equal to the given array). -----Input----- The first line contains integer number $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. The first line of a test case contains one integer $n$ $(1 \le n \le 10^{5})$ — the number of elements in the secret code permutation $p$. The second line of a test case contains $n$ integers $q_1, q_2, \dots, q_n$ $(1 \le q_i \le n)$ — elements of the array $q$ for secret permutation. It is guaranteed that $q_i \le q_{i+1}$ for all $i$ ($1 \le i < n$). The sum of all values $n$ over all the test cases in the input doesn't exceed $10^5$. -----Output----- For each test case, print: If it's impossible to find such a permutation $p$, print "-1" (without quotes). Otherwise, print $n$ distinct integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$). If there are multiple possible answers, you can print any of them. -----Example----- Input 4 5 1 3 4 5 5 4 1 1 3 4 2 2 2 1 1 Output 1 3 4 5 2 -1 2 1 1 -----Note----- In the first test case of the example answer $[1,3,4,5,2]$ is the only possible answer: $q_{1} = p_{1} = 1$; $q_{2} = \max(p_{1}, p_{2}) = 3$; $q_{3} = \max(p_{1}, p_{2}, p_{3}) = 4$; $q_{4} = \max(p_{1}, p_{2}, p_{3}, p_{4}) = 5$; $q_{5} = \max(p_{1}, p_{2}, p_{3}, p_{4}, p_{5}) = 5$. It can be proved that there are no answers for the second test case of the example. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for faw in range(t): n = int(input()) a = [0] + list(map(int,input().split())) nun = [] ans = [] f = True for i in range(1, n + 1): if a[i] == a[i-1]: if len(nun) == 0: f = False break else: ans.append(nun.pop()) else: ans.append(a[i]) for i in range(a[i - 1] + 1, a[i]): nun.append(i) if f: print(*ans) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is the leader of Chef's Earth Defense Organization, and his mission is to counter aliens which are threatening the earth. According to information gathered by the organization, there are $N$ alien spaceships (numbered $1$ through $N$) planning to invade the earth. The $i$-th spaceship will appear on the radar at time $C_i$. Each spaceship needs $D$ time to reach earth once it appears on the radar. Chef's organization owns a huge laser cannon which can destroy one spaceship in one shot. However, once the cannon is used once it needs some amount of cool-down time in order to be used again (first shot doesn't require cool-down time before it is used). This cool-down time, however, is configurable. It has to be set before the first shot, and cannot be changed after that. If Chef sets a lower cool-down time, that would increase the energy consumed by the cannon, and vice-versa - the higher the cool-down time, the lower the energy consumed. This might be a long battle, and Chef wants to use as little energy as possible. So Chef wants to maximize the cool-down time while still being able to destroy all spaceships before any of them arrive on earth. In particular, the $i$-th spaceship should be shot between the times $C_i$ and $C_i + D$ (both end points inclusive). -----Input:----- - The first line of input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two integers $N$ and $D$. - The second line contains $N$ space-separated integers $C_1, C_2, \ldots, C_N$. -----Output:----- For each test case, print a single line containing one real number― the maximum cool-down time possible. Your answer will be considered correct if the absolute or relative error of the answer does not exceed $10^{-6}$. -----Constraints----- - $1 \leq T \leq 1000$ - $2 \leq N \leq 10^5$ - $1 \leq C_i \leq 10^9$ for each valid $i$ - $1 \leq D \leq 10^9$ - The sum of $N$ over all test cases does not exceed $10^6$ -----Subtasks----- Subtask #1 (50 points): - $N \le 1,000$ - the sum of $N$ over all test cases does not exceed $10,000$ Subtask #2 (50 points): Original constraints -----Sample Input:----- 2 3 2 3 2 3 2 1 5 6 -----Sample Output:----- 1.5000000000 2.0000000000 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def isValid(mid): time = 0.0 for i in range(n): if time < c[i]: time = c[i] time += mid # cannon cooling elif time >= c[i] and time <= c[i] + d: time += mid # cannon cooling else: return False return True t = int(input()) while t != 0: n, d = list(map(int, input().split())) c = list(map(int, input().split()))[:n] ans = -1 c.sort() low, high = 0, 10 ** 10 while (high - low) > 0.000001: mid = (low + high) / 2 if isValid(mid): ans = mid low = mid else: high = mid print("{0:.6f}".format(ans)) t -= 1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly decreasing but he also didn’t want to waste much money so he decided to get the minimum cuts possible. Your job is to output the minimum value of cut that is possible to arrange the skyscrapers in descending order. -----Input----- *First line of input is the number of sky-scrappers in the city *Second line of input is the height of the respective sky-scrappers -----Output----- * Your output should be the minimum value of cut required to arrange these sky-scrappers in descending order. -----Example----- Input: 5 1 2 3 4 5 Output: 8 By: Chintan,Asad,Ashayam,Akanksha The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys num=int(sys.stdin.readline()) s=sys.stdin.readline().split() sky=list(map(int,s)) sky.reverse() cuts=0 change=0 t=False i=1 while i<len(sky): if sky[i]<=sky[i-1]: for j in range(i-1,-1,-1): if sky[j]<=sky[i]-(i-j): break else: change+=sky[j]-(sky[i]-(i-j)) if change>=sky[i]: change=sky[i] t=True break cuts+=change if t: del sky[i] t=False i-=1 else: for j in range(i-1,-1,-1): if sky[j]<sky[i]-(i-j): break else: sky[j]=sky[i]-(i-j) i+=1 change=0 print(cuts) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a_1... a_{|}t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya". Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey. It is guaranteed that the word p can be obtained by removing the letters from word t. -----Input----- The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a_1, a_2, ..., a_{|}t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ a_{i} ≤ |t|, all a_{i} are distinct). -----Output----- Print a single integer number, the maximum number of letters that Nastya can remove. -----Examples----- Input ababcba abb 5 3 4 1 7 6 2 Output 3 Input bbbabb bb 1 6 3 4 2 5 Output 4 -----Note----- In the first sample test sequence of removing made by Nastya looks like this: "ababcba" $\rightarrow$ "ababcba" $\rightarrow$ "ababcba" $\rightarrow$ "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba". So, Nastya will remove only three letters. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def sub(a, s): pa = 0 ps = 0 while pa < len(a) and ps < len(s): if a[pa] == s[ps]: ps += 1 pa += 1 else: pa += 1 return ps == len(s) def subword(t, ord_ar, n): t_copy = [] for i in range(len(ord_ar)): if ord_ar[i] >= n: t_copy.append(t[i]) return t_copy def check(t, p, ord_ar, n): s = subword(t, ord_ar, n) return sub(s, p) def bin_s(l, r, f): while r > l + 1: m = (r + l) // 2 if f(m): l = m else: r = m return l def main(): t = input().strip() p = input().strip() ord_ar = [0]*len(t) seq = list(map(int, input().strip().split())) for i,x in enumerate(seq): ord_ar[x-1] = i ans = bin_s(0, len(t), lambda n: check(t, p, ord_ar, n)) print(ans) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: T is playing a game with his friend, HL. There are $n$ piles of stones, the $i$-th pile initially has $a_i$ stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends. Assuming both players play optimally, given the starting configuration of $t$ games, determine the winner of each game. -----Input----- The first line of the input contains a single integer $t$ $(1 \le t \le 100)$ — the number of games. The description of the games follows. Each description contains two lines: The first line contains a single integer $n$ $(1 \le n \le 100)$ — the number of piles. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 100)$. -----Output----- For each game, print on a single line the name of the winner, "T" or "HL" (without quotes) -----Example----- Input 2 1 2 2 1 1 Output T HL -----Note----- In the first game, T removes a single stone from the only pile in his first turn. After that, although the pile still contains $1$ stone, HL cannot choose from this pile because it has been chosen by T in the previous turn. Therefore, T is the winner. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) sumA = sum(a) TWins = False for elem in a: if elem > sumA // 2: TWins = True break if TWins or sumA % 2 != 0: print("T") else: print("HL") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are n cabs in a city numbered from 1 to n. The city has a rule that only one cab can run in the city at a time. Cab picks up the customer and drops him to his destination. Then the cab gets ready to pick next customer. There are m customers in search of cab. First customer will get the taxi first. You have to find the nearest cab for each customer. If two cabs have same distance then the cab with lower number is preferred. Your task is to find out minimum distant cab for each customer. 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 two space-separated integers N and M, denoting the number of cabs and the number of customers. The next N lines contain two space-separated integers x[i] and y[i], denoting the initial position of the ith cab. Next line contains an integer M denoting number of customers. The next M lines contain four space seperated integers sx[i], sy[i], dx[i], dy[i], denoting the current location and the destination of the ith customer. Output: Output the nearest cab number for each customer. Constraints: 1<=t<=10 1<=n,m<=1000 -10^9<=x[i] , y[i] , sx[i] , sy[i] , dx[i] , dy[i]<=10^9 Example: Input: 1 3 2 1 3 3 2 3 5 2 3 3 4 5 3 4 1 Output: 1 1 Explanation: The distance of cab1 from customer1 = sqrt((1-2)^2 + (3-3)^2) = 1 The distance of cab2 from customer1 = sqrt(2) The distance of cab3 from customer1 = sqrt(5) So output for customer1 is 1 Now location of cab1 is (3,4) The distance of cab1 from customer2 = sqrt((3-5)^2 + (4-3)^2) = sqrt(5) The distance of cab2 from customer2 = sqrt(5) The distance of cab3 from customer2 = sqrt(8) So output for customer2 is 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math def dist(w,x,y,z): return math.hypot(y - w, z - x) t = int(input()) while (t>0): t = t -1 n, m = list(map(int,input().split())) a = [] for i in range(0,n): x,y = list(map(int,input().split())) a.append([x,y]) for j in range(0,m): p,q,r,s = list(map(int,input().split())) nearest = -1 distance = 10000000000 for i in range(0,n): way = dist(a[i][0],a[i][1],p,q) if way < distance: distance = way nearest = i print(nearest + 1) a[nearest][0] = r a[nearest][1] = s ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. -----Input----- The first line contains n and k (1 ≤ k ≤ n ≤ 10^5) — the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n — numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer t_{i} (0 ≤ t_{i} ≤ n - 1) — the number of courses on which the i-th depends. Then there follows the sequence of t_{i} distinct integers from 1 to n — numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values t_{i} doesn't exceed 10^5. -----Output----- Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m — the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers — numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. -----Examples----- Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 -----Note----- In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #This code is dedicated to Vlada S. class Course: def __init__(self, reqs, number): self.reqs = list(map(int, reqs.split()[1:])) self.available = False self.in_stack = False self.number = number n, k = list(map(int, input().split())) requirements = list(map(int, input().split())) courses = {} answer = "" for i in range(n): courses[i + 1]= Course(input(), i + 1) for i in range(len(requirements)): requirements[i] = courses[requirements[i]] while requirements: data = {} course = requirements.pop() if not course.available: requirements.append(course) done = True for c in course.reqs: c = courses[c] if not c.available: requirements.append(c) done = False if done: answer += " " + str(course.number) course.available = True else: if course.in_stack: print(-1) break course.in_stack = True else: print(answer.count(" ")) print(answer[1:]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases. A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $n$ stairs, then it is made of $n$ columns, the first column is $1$ cell high, the second column is $2$ cells high, $\ldots$, the $n$-th column if $n$ cells high. The lowest cells of all stairs must be in the same row. A staircase with $n$ stairs is called nice, if it may be covered by $n$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $7$ stairs looks like: [Image] Find out the maximal number of different nice staircases, that can be built, using no more than $x$ cells, in total. No cell can be used more than once. -----Input----- The first line contains a single integer $t$ $(1 \le t \le 1000)$  — the number of test cases. The description of each test case contains a single integer $x$ $(1 \le x \le 10^{18})$  — the number of cells for building staircases. -----Output----- For each test case output a single integer  — the number of different nice staircases, that can be built, using not more than $x$ cells, in total. -----Example----- Input 4 1 8 6 1000000000000000000 Output 1 2 1 30 -----Note----- In the first test case, it is possible to build only one staircase, that consists of $1$ stair. It's nice. That's why the answer is $1$. In the second test case, it is possible to build two different nice staircases: one consists of $1$ stair, and another consists of $3$ stairs. This will cost $7$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $2$. In the third test case, it is possible to build only one of two nice staircases: with $1$ stair or with $3$ stairs. In the first case, there will be $5$ cells left, that may be used only to build a staircase with $2$ stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is $1$. If Jett builds a staircase with $3$ stairs, then there are no more cells left, so the answer is $1$ again. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys import random from fractions import Fraction from math import * def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def finput(): return float(input()) def tinput(): return input().split() def linput(): return list(input()) def rinput(): return list(map(int, tinput())) def fiinput(): return list(map(float, tinput())) def rlinput(): return list(map(int, input().split())) def trinput(): return tuple(rinput()) def srlinput(): return sorted(list(map(int, input().split()))) def NOYES(fl): if fl: print("NO") else: print("YES") def YESNO(fl): if fl: print("YES") else: print("NO") def main(): n = iinput() #k = iinput() #m = iinput() #n = int(sys.stdin.readline().strip()) #n, k = rinput() #n, m = rinput() #m, k = rinput() #n, k, m = rinput() #n, m, k = rinput() #k, n, m = rinput() #k, m, n = rinput() #m, k, n = rinput() #m, n, k = rinput() #q = srlinput() #q = linput() s, t, res = 1, 1, 0 while s <= n: res += 1 n -= s t = 2 * t + 1 s = (t * (t + 1)) // 2 print(res) for i in range(iinput()): main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Allen and Bessie are playing a simple number game. They both know a function $f: \{0, 1\}^n \to \mathbb{R}$, i. e. the function takes $n$ binary arguments and returns a real value. At the start of the game, the variables $x_1, x_2, \dots, x_n$ are all set to $-1$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $i$ such that $x_i = -1$ and either setting $x_i \to 0$ or $x_i \to 1$. After $n$ rounds all variables are set, and the game value resolves to $f(x_1, x_2, \dots, x_n)$. Allen wants to maximize the game value, and Bessie wants to minimize it. Your goal is to help Allen and Bessie find the expected game value! They will play $r+1$ times though, so between each game, exactly one value of $f$ changes. In other words, between rounds $i$ and $i+1$ for $1 \le i \le r$, $f(z_1, \dots, z_n) \to g_i$ for some $(z_1, \dots, z_n) \in \{0, 1\}^n$. You are to find the expected game value in the beginning and after each change. -----Input----- The first line contains two integers $n$ and $r$ ($1 \le n \le 18$, $0 \le r \le 2^{18}$). The next line contains $2^n$ integers $c_0, c_1, \dots, c_{2^n-1}$ ($0 \le c_i \le 10^9$), denoting the initial values of $f$. More specifically, $f(x_0, x_1, \dots, x_{n-1}) = c_x$, if $x = \overline{x_{n-1} \ldots x_0}$ in binary. Each of the next $r$ lines contains two integers $z$ and $g$ ($0 \le z \le 2^n - 1$, $0 \le g \le 10^9$). If $z = \overline{z_{n-1} \dots z_0}$ in binary, then this means to set $f(z_0, \dots, z_{n-1}) \to g$. -----Output----- Print $r+1$ lines, the $i$-th of which denotes the value of the game $f$ during the $i$-th round. Your answer must have absolute or relative error within $10^{-6}$. Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is considered correct if $\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$. -----Examples----- Input 2 2 0 1 2 3 2 5 0 4 Output 1.500000 2.250000 3.250000 Input 1 0 2 3 Output 2.500000 Input 2 0 1 1 1 1 Output 1.000000 -----Note----- Consider the second test case. If Allen goes first, he will set $x_1 \to 1$, so the final value will be $3$. If Bessie goes first, then she will set $x_1 \to 0$ so the final value will be $2$. Thus the answer is $2.5$. In the third test case, the game value will always be $1$ regardless of Allen and Bessie's play. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, r = [int(x) for x in input().split()] n = 2 ** n xs = [int(x) for x in input().split()] s = sum(xs) res = [0 for _ in range(r+1)] for i in range(r): res[i] = s / n i, val = [int(x) for x in input().split()] s += val - xs[i] xs[i] = val res[r] = s / n print("\n".join(map(str, res))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has a pepperoni pizza in the shape of a $N \times N$ grid; both its rows and columns are numbered $1$ through $N$. Some cells of this grid have pepperoni on them, while some do not. Chef wants to cut the pizza vertically in half and give the two halves to two of his friends. Formally, one friend should get everything in the columns $1$ through $N/2$ and the other friend should get everything in the columns $N/2+1$ through $N$. Before doing that, if Chef wants to, he may choose one row of the grid and reverse it, i.e. swap the contents of the cells in the $i$-th and $N+1-i$-th column in this row for each $i$ ($1 \le i \le N/2$). After the pizza is cut, let's denote the number of cells containing pepperonis in one half by $p_1$ and their number in the other half by $p_2$. Chef wants to minimise their absolute difference. What is the minimum value of $|p_1-p_2|$? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains a string with length $N$ describing the $i$-th row of the grid; this string contains only characters '1' (denoting a cell with pepperonis) and '0' (denoting a cell without pepperonis). -----Output----- For each test case, print a single line containing one integer — the minimum absolute difference between the number of cells with pepperonis in the half-pizzas given to Chef's friends. -----Constraints----- - $1 \le T \le 1,000$ - $2 \le N \le 1,000$ - $N$ is even - the sum of $N \cdot N$ over all test cases does not exceed $2 \cdot 10^6$ -----Example Input----- 2 6 100000 100000 100000 100000 010010 001100 4 0011 1100 1110 0001 -----Example Output----- 2 0 -----Explanation----- Example case 1: Initially, $|p_1-p_2| = 4$, but if Chef reverses any one of the first four rows from "100000" to "000001", $|p_1-p_2|$ becomes $2$. Example case 2: Initially, $|p_1-p_2| = 0$. We cannot make that smaller by reversing any row. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n=int(input()) l1=[] l2=[] for i in range(n): s=input() a=s[ :n//2].count('1') b=s[n//2: ].count('1') if a>b: l1.append(a-b) elif a<b: l2.append(b-a) p=sum(l1) q=sum(l2) if p==q: print(0) elif p>q: diff=p-q flag=0 for i in range(diff//2, 0, -1): a=diff-i if (i in l1) or (a in l1): print(abs(a-i)) flag=1 break if flag==0: print(diff) else: diff=q-p flag=0 for i in range(diff//2, 0, -1): a=diff-i if (i in l2) or (a in l2): print(abs(a-i)) flag=1 break if flag==0: print(diff) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Richik$Richik$ has just completed his engineering and has got a job in one of the firms at Sabrina$Sabrina$ which is ranked among the top seven islands in the world in terms of the pay scale. Since Richik$Richik$ has to travel a lot to reach the firm, the owner assigns him a number X$X$, and asks him to come to work only on the day which is a multiple of X$X$. Richik joins the firm on 1-st day but starts working from X-th day. Richik$Richik$ is paid exactly the same amount in Dollars as the day number. For example, if Richik$Richik$ has been assigned X=3$X = 3$, then he will be paid 3$3$ dollars and 6$6$ dollars on the 3rd$3rd$ and 6th$6th$ day on which he comes for work. On N−th$N-th$ day, the owner calls up Richik$Richik$ and asks him not to come to his firm anymore. Hence Richik$Richik$ demands his salary of all his working days together. Since it will take a lot of time to add, Richik$Richik$ asks help from people around him, let's see if you can help him out. -----Input:----- - First line will contain T$T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, two integers X,N$X, N$. -----Output:----- For each testcase, output in a single line which is the salary which Richik$Richik$ demands. -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤X<=N≤107$1 \leq X<=N \leq 10^7$ -----Sample Input:----- 1 3 10 -----Sample Output:----- 18 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for i in range(t): x,n=[int(g) for g in input().split()] sal=0 day=x while day<n: sal=sal+day day+=x print(sal) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef likes to play with array elements. His teacher has given him an array problem. But now he is busy as Christmas is coming. So, he needs your help. Can you help him to solve this problem. You are given an array $(A1,A2,A3……AN)$ of length $N$. You have to create an another array using the given array in the following ways: For each valid i, the ith element of the output array will be the sum of the ith element and (A[i])th element if $A[i]$ is less equal $N$. Other wise for each valid i following the step below i) Divide the value of $A[i]$ by 2 untill it will be less than$N$. ii) then find the difference ($D$) between $N$ and $A[i]$. iii) the ith element of the output array will be $Dth$ element. -----Input:----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A1,A2,…,AN$. -----Output:----- - For each testcase, print new array in each line. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^5$ - $1\leq A1,A2.....AN \leq 10^7$ -----Sample Input:----- 2 5 2 4 5 7 9 4 5 4 2 3 -----Sample Output:----- 6 11 14 4 2 4 7 6 5 -----EXPLANATION:----- For 1st test case: A1 = 2+4 =6, A2 = 4+7 =11 , A3 = 5+9 =14 , A4 > N (5) ,So A4/2 = 3 then A4 = A[5 -3] , A4=A[2]=4, And A5 =A[1]=2. Then array becomes 6,11,14,4,2. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def index(n,val): while(val >= n): val = val//2 return n - val t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int,input().split())) new = [0 for i in range(n)] for i in range(n): if arr[i]<=n : new[i] = arr[i] + arr[arr[i]-1] else: new[i] = arr[index(n,arr[i]) - 1] print(*new) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree. The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1. Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) — the numbers of the nodes that are connected by the i-th edge. It is guaranteed that the given graph is a tree. -----Output----- Print a single real number — the expectation of the number of steps in the described game. The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 6}. -----Examples----- Input 2 1 2 Output 1.50000000000000000000 Input 3 1 2 1 3 Output 2.00000000000000000000 -----Note----- In the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1 × (1 / 2) + 2 × (1 / 2) = 1.5 In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1 × (1 / 3) + (1 + 1.5) × (2 / 3) = (1 / 3) + (5 / 3) = 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # https://codeforces.com/problemset/problem/280/C from collections import defaultdict, deque import sys nodes = int(sys.stdin.readline()) edges = defaultdict(list) for line in sys.stdin: a, b = line.split() a = int(a) b = int(b) edges[a].append(b) edges[b].append(a) bfs = deque([(1, 1)]) depths = {} while bfs: nid, depth = bfs.popleft() if nid in depths: continue depths[nid] = depth for n2 in edges[nid]: bfs.append((n2, depth + 1)) print(sum(1.0 / d for d in sorted(depths.values(), reverse=True))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N. We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M). AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized: - Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}. Find the maximum possible number of i such that p_i = i after operations. -----Constraints----- - 2 ≤ N ≤ 10^5 - 1 ≤ M ≤ 10^5 - p is a permutation of integers from 1 through N. - 1 ≤ x_j,y_j ≤ N - x_j ≠ y_j - If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M p_1 p_2 .. p_N x_1 y_1 x_2 y_2 : x_M y_M -----Output----- Print the maximum possible number of i such that p_i = i after operations. -----Sample Input----- 5 2 5 3 1 4 2 1 3 5 4 -----Sample Output----- 2 If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline class UnionFind(object): def __init__(self, n): self._par = list(range(n)) self.size = [1]*n def root(self, v): if self._par[v] == v: return v self._par[v] = self.root(self._par[v]) return self._par[v] def unite(self, u, v): u, v = self.root(u), self.root(v) if u==v: return False if self.size[u] > self.size[v]: u, v = v, u self.size[v] += self.size[u] self._par[u] = v def is_connected(self, u, v): return self.root(u)==self.root(v) n, m = map(int, readline().split()) P = list(map(lambda x:int(x)-1, readline().split())) uf = UnionFind(n) for _ in range(m): x, y = map(lambda x:int(x)-1, readline().split()) uf.unite(x,y) ans = 0 for i in range(n): if uf.is_connected(i, P[i]): ans += 1 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef wants to gift pairs to his friends this new year. But his friends like good pairs only. A pair (a , b) is called a good pair if 1 <= a < b <= N such that GCD(a*b , P) = 1. Since Chef is busy in preparation for the party, he wants your help to find all the good pairs. ————————————————————————————————————— INPUT • The first line of the input contains a single integer T. • The first and only line of each test case contain two integer N,P. ———————————————————————————————————————— OUTPUT For each test case, print a single line containing one integer — the total number of good pairs ———————————————————————————————————————— CONSTRAINTS • 1 ≤ T≤ 50 • 2 ≤ N,P ≤10^5 ————————————————————————————————————— Example Input 2 2 3 3 3 ———————————————————————————————————————— Example Output 1 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def G(x, y): while(y): x, y = y, x % y return x # t=int(input()) # l=list(map(int,input().split())) for _ in range(int(input())): n,p=map(int,input().split()) c=0 for i in range(1,n+1): if G(i,p)==1: c+=1 ans=c*(c-1)//2 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is an event in DUCS where boys get a chance to show off their skills to impress girls. The boy who impresses the maximum number of girls will be honoured with the title “Charming Boy of the year”. There are $N$ girls in the department. Each girl gives the name of a boy who impressed her the most. You need to find the name of a boy who will be honoured with the title. If there are more than one possible winners, then the one with the lexicographically smallest name is given the title. It is guaranteed that each boy participating in the event has a unique name. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains an integer $N$ denoting the number of girls. - The second line contains $N$ space-separated strings $S_1, S_2, \ldots, S_N$, denoting the respective names given by the girls. -----Output----- For each test case, print a single line containing a string — the name of the boy who impressed the maximum number of girls. In case of a tie, print the lexicographically smallest name. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N \leq 10^5$ - $1 \leq |S_i| \leq 10$, for each valid $i$ $(|S_i|$ is the length of the string $S_i)$ - For each valid $i$, $S_i$ contains only lowercase English alphabets - Sum of $N$ over all the test cases is $\leq 10^6$ -----Subtasks----- - 30 points: $1 \leq N \leq 100$ - 70 points: original constraints -----Sample Input----- 2 10 john berry berry thomas thomas john john berry thomas john 4 ramesh suresh suresh ramesh -----Sample Output----- john ramesh The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import Counter for _ in range(int(input())): n=int(input()) l=[i for i in input().split()] ll=[] c=Counter(l) cc=[] m=0 for l,count in c.most_common(len(l)-1): if m==0: ll.append(l) cc.append(count) if m==count: ll.append(l) cc.append(count) if count<m: break m=count k=set(cc) leng=len(list(k)) if leng==1: sor=sorted(ll) print(sor[0]) else: print(ll[0]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic. Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 100$), the number of pairs of people. The second line contains $2n$ integers $a_1, a_2, \dots, a_{2n}$. For each $i$ with $1 \le i \le n$, $i$ appears exactly twice. If $a_j = a_k = i$, that means that the $j$-th and $k$-th people in the line form a couple. -----Output----- Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions. -----Examples----- Input 4 1 1 2 3 3 2 4 4 Output 2 Input 3 1 1 2 2 3 3 Output 0 Input 3 3 1 2 3 1 2 Output 3 -----Note----- In the first sample case, we can transform $1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4$ in two steps. Note that the sequence $1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4$ also works in the same number of steps. The second sample case already satisfies the constraints; therefore we need $0$ swaps. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) xs = [int(x) for x in input().split()] seen = {} res = 0 while xs: j = xs.index(xs[0], 1) res += j - 1 xs = xs[1:j] + xs[j+1:] print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Harsh, like usual, started studying 6 months before for his end semester examinations. He was going to complete his 8th revision of the whole syllabus, when suddenly Pranav showed up in his room with the last year's question paper for their algorithms course. This paper contains a problem which both of them couldn't solve. Frustrated he asked you for help. But you declined him and instead try to do this problem instead: You are given an array $A_1,A_2,\dots,A_N$, a positive integer $K$, and a function $F(x)=\displaystyle\sum_{i=1}^{N}{\left|{\left({x-A_i}\right)^K}\right|}$. Find the smallest integer $x$ such that $F(x)$ is minimum.Input - The first line contains two space-seperated integers , $N$ and $K$ - The second line contains $N$ space-seperated integers $A_1,A_2,\dots,A_N$. Output In the first and only line print the smallest integer $x$ such that $F(x)$ is minimumConstraints - $1 \leq N \leq {10}^{5}$ - $1 \leq K \leq {3}$ - $1 \leq A_i \leq {5}\times{10}^{4}$ for each valid $i$Sample Input 1 3 1 6 1 7 Sample Output 1 6 Explanation 1 $F(6) = \displaystyle\sum_{i=1}^{N}{\left|{\left({6-A_i}\right)^K}\right|} \\ F(6) = \left|{\left({6-6}\right)^1}\right| + \left|{\left({6-1}\right)^1}\right| + \left|{\left({6-7}\right)^1}\right| \\ F(6) = 0 + 5+ 1 \\ F(6) = 6 $ Here $6$ is the minumum value for $F(x)$ for any integer value of $x$.Sample Input 2 3 2 6 1 7 Sample Output 2 5 Explanation 2 $F(5) = \displaystyle\sum_{i=1}^{N}{\left|{\left({5-A_i}\right)^K}\right|} \\F(5) = \left|{\left({5-6}\right)^2}\right| + \left|{\left({5-1}\right)^2}\right| + \left|{\left({5-7}\right)^2}\right| \\F(5) = 1 + 16 + 4 \\F(5) = 21$ Here $21$ is the minumum value for $F(x)$ for any integer value of $x$.Sample Input 3 3 3 6 1 7 Sample Output 3 4 Explanation 3 $F(4) = \displaystyle\sum_{i=1}^{N}{\left|{\left({4-A_i}\right)^K}\right|} \\F(4) = \left|{\left({4-6}\right)^3}\right| + \left|{\left({4-1}\right)^3}\right| + \left|{\left({4-7}\right)^3}\right| \\F(4) = 8 + 27 + 27 \\F(4) = 62 $ Here $62$ is the minumum value for $F(x)$ for any integer value of $x$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] n,k = ip() x = ip() x.sort() if k == 1: a = x[n//2] b = x[n//2-1] else: s = sum(x) a = s//n b = a + 1 sa = sum([abs((a-i)**k) for i in x]) sb = sum([abs((b-i)**k) for i in x]) if sa < sb: print(a) else: print(b) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have $n$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $i$-th gift consists of $a_i$ candies and $b_i$ oranges. During one move, you can choose some gift $1 \le i \le n$ and do one of the following operations: eat exactly one candy from this gift (decrease $a_i$ by one); eat exactly one orange from this gift (decrease $b_i$ by one); eat exactly one candy and exactly one orange from this gift (decrease both $a_i$ and $b_i$ by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither $a_i$ nor $b_i$ can become less than zero). As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $a_1 = a_2 = \dots = a_n$ and $b_1 = b_2 = \dots = b_n$ (and $a_i$ equals $b_i$ is not necessary). Your task is to find the minimum number of moves required to equalize all the given gifts. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 1000$) — 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 gifts. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the number of candies in the $i$-th gift. The third line of the test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 10^9$), where $b_i$ is the number of oranges in the $i$-th gift. -----Output----- For each test case, print one integer: the minimum number of moves required to equalize all the given gifts. -----Example----- Input 5 3 3 5 6 3 2 3 5 1 2 3 4 5 5 4 3 2 1 3 1 1 1 2 2 2 6 1 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 3 10 12 8 7 5 4 Output 6 16 0 4999999995 7 -----Note----- In the first test case of the example, we can perform the following sequence of moves: choose the first gift and eat one orange from it, so $a = [3, 5, 6]$ and $b = [2, 2, 3]$; choose the second gift and eat one candy from it, so $a = [3, 4, 6]$ and $b = [2, 2, 3]$; choose the second gift and eat one candy from it, so $a = [3, 3, 6]$ and $b = [2, 2, 3]$; choose the third gift and eat one candy and one orange from it, so $a = [3, 3, 5]$ and $b = [2, 2, 2]$; choose the third gift and eat one candy from it, so $a = [3, 3, 4]$ and $b = [2, 2, 2]$; choose the third gift and eat one candy from it, so $a = [3, 3, 3]$ and $b = [2, 2, 2]$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) ma = min(a) mb = min(b) ops = 0 for xa, xb in zip(a, b): da = xa - ma db = xb - mb ops += max(da, db) print(ops) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Harish has decided to go to Arya's hotel this morning. We all know he is crazy for masala dosas. And as usual he is always hungry. He decided to order all the masala dosas at once. But then he realised that he did not have enough money to buy all of them. So he decided to share the amount with his friend Ozil. But both of them are fans of even numbers. Both of them says they want to eat even number of dosas. Ozil is ready to put the share if and only if , he is sure that he can get even number of dosas. So given N number of dosas can you please help Harish to decide, if he will be able to get all the dosas at once from the hotel. -----Input----- The first line of input contains an integer T which denotes the number of test files. Next T lines contains an integer N where N is the total number of dosas. -----Output----- Print "YES" if both can get even number of dosas. If it is not possible print "NO". -----Constraints----- - 1 ≤ T ≤ 10^6 - 1 ≤ N ≤ 10^18 -----Subtasks----- Subtask #1 : (20 points) - 1 ≤ T ≤ 10 - 1 ≤ N≤ 100 Subtask 2 : (80 points) - 1 ≤ T ≤ 10^6 - 1 ≤ N≤ 10^18 -----Example----- Input: 2 16 27 Output: YES NO The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(eval(input())): n=eval(input()) if n%2: print('NO') else: print('YES') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: 10^{10^{10}} participants, including Takahashi, competed in two programming contests. In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th. The score of a participant is the product of his/her ranks in the two contests. Process the following Q queries: - In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's. -----Constraints----- - 1 \leq Q \leq 100 - 1\leq A_i,B_i\leq 10^9(1\leq i\leq Q) - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: Q A_1 B_1 : A_Q B_Q -----Output----- For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's. -----Sample Input----- 8 1 4 10 5 3 3 4 11 8 9 22 40 8 36 314159265 358979323 -----Sample Output----- 1 12 4 11 14 57 31 671644785 Let us denote a participant who was ranked x-th in the first contest and y-th in the second contest as (x,y). In the first query, (2,1) is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def i1(): return int(input()) def i2(): return [int(i) for i in input().split()] q=i1() import math y=[] for i in range(q): y.append(i2()) for a,b in y: x=a*b c=int(math.sqrt(x)) if c**2==x: c-=1 z=2*c if c>0 and (x//c)==c: z-=1 if c>0 and x%c==0 and (x//c-1)==c: z-=1 if a<=c: z-=1 if b<=c: z-=1 print(z) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have a string $s$ consisting of $n$ characters. Each character is either 0 or 1. You can perform operations on the string. Each operation consists of two steps: select an integer $i$ from $1$ to the length of the string $s$, then delete the character $s_i$ (the string length gets reduced by $1$, the indices of characters to the right of the deleted one also get reduced by $1$); if the string $s$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed. For example, if you have a string $s =$ 111010, the first operation can be one of the following: select $i = 1$: we'll get 111010 $\rightarrow$ 11010 $\rightarrow$ 010; select $i = 2$: we'll get 111010 $\rightarrow$ 11010 $\rightarrow$ 010; select $i = 3$: we'll get 111010 $\rightarrow$ 11010 $\rightarrow$ 010; select $i = 4$: we'll get 111010 $\rightarrow$ 11110 $\rightarrow$ 0; select $i = 5$: we'll get 111010 $\rightarrow$ 11100 $\rightarrow$ 00; select $i = 6$: we'll get 111010 $\rightarrow$ 11101 $\rightarrow$ 01. You finish performing operations when the string $s$ becomes empty. What is the maximum number of operations you can perform? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of each test case contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the string $s$. The second line contains string $s$ of $n$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, print a single integer — the maximum number of operations you can perform. -----Example----- Input 5 6 111010 1 0 1 1 2 11 6 101010 Output 3 1 1 1 3 -----Note----- In the first test case, you can, for example, select $i = 2$ and get string 010 after the first operation. After that, you can select $i = 3$ and get string 1. Finally, you can only select $i = 1$ and get empty string. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from itertools import groupby def main(): N = int(input()) S = input() C = [len(list(x[1])) for x in groupby(S)] M = len(C) dup_idx = [] for i, c in enumerate(C): if c > 1: dup_idx.append(i) dup_idx.reverse() curr = 0 while dup_idx: i = dup_idx[-1] if i < curr: dup_idx.pop() continue C[i] -= 1 if C[i] == 1: dup_idx.pop() curr += 1 ans = curr + (M-curr+1)//2 print(ans) def __starting_point(): for __ in [0]*int(input()): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of n × m rooms, and the rooms are arranged in n rows (numbered from the top to the bottom starting from 1) and m columns (numbered from the left to the right starting from 1). The room in the i-th row and j-th column is denoted by (i, j). A player starts in the room (1, 1) and wants to reach the room (n, m). Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting (i, j) and (i, j + 1) is locked, then we can't go from (i, j) to (i, j + 1). Also, one can only travel between the rooms downwards (from the room (i, j) to the room (i + 1, j)) or rightwards (from the room (i, j) to the room (i, j + 1)) provided the corresponding door is not locked. [Image] This image represents a maze with some doors locked. The colored arrows denotes all the possible paths while a red cross denotes a locked door. ZS the Coder considers a maze to have difficulty x if there is exactly x ways of travelling from the room (1, 1) to the room (n, m). Two ways are considered different if they differ by the sequence of rooms visited while travelling. Your task is to create a maze such that its difficulty is exactly equal to T. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right? -----Input----- The first and only line of the input contains a single integer T (1 ≤ T ≤ 10^18), the difficulty of the required maze. -----Output----- The first line should contain two integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the maze respectively. The next line should contain a single integer k (0 ≤ k ≤ 300) — the number of locked doors in the maze. Then, k lines describing locked doors should follow. Each of them should contain four integers, x_1, y_1, x_2, y_2. This means that the door connecting room (x_1, y_1) and room (x_2, y_2) is locked. Note that room (x_2, y_2) should be adjacent either to the right or to the bottom of (x_1, y_1), i.e. x_2 + y_2 should be equal to x_1 + y_1 + 1. There should not be a locked door that appears twice in the list. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. -----Examples----- Input 3 Output 3 2 0 Input 4 Output 4 3 3 1 2 2 2 3 2 3 3 1 3 2 3 -----Note----- Here are how the sample input and output looks like. The colored arrows denotes all the possible paths while a red cross denotes a locked door. In the first sample case: [Image] In the second sample case: [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python corr = lambda x, y: 1 <= x <= n and 1 <= y <= m T = int(input()) a = [] while T: a.append(T % 6) T //= 6 L = len(a) n = m = L * 2 + 2 ans = [(1, 2, 2, 2), (2, 1, 2, 2)] f = [[1] * 9 for i in range(7)] f[1][2] = f[2][2] = f[2][6] = f[3][5] = 0 f[4][5] = f[4][6] = f[5][2] = f[5][5] = f[5][6] = 0 p = [0] * 9 p[1] = 3, 1, 3, 2 p[2] = 4, 1, 4, 2 p[3] = 4, 2, 5, 2 p[4] = 4, 3, 5, 3 p[5] = 1, 3, 2, 3 p[6] = 1, 4, 2, 4 p[7] = 2, 4, 2, 5 p[8] = 3, 4, 3, 5 for i in range(L): bit = a[L - i - 1] for j in range(1, 9): if not f[bit][j]: continue x1, y1, x2, y2 = p[j]; D = 2 * i x1 += D; y1 += D; x2 += D; y2 += D if corr(x2, y2): ans.append((x1, y1, x2, y2)) for i in range(L - 1): x1, y1 = 5 + i * 2, 1 + i * 2 x2, y2 = 1 + i * 2, 5 + i * 2 ans.append((x1, y1, x1 + 1, y1)) ans.append((x1, y1 + 1, x1 + 1, y1 + 1)) ans.append((x2, y2, x2, y2 + 1)) ans.append((x2 + 1, y2, x2 + 1, y2 + 1)) print(n, m) print(len(ans)) [print(*i) for i in ans] ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10^{k}. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10^{k}. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 10^3 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10^{k}. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. -----Input----- The only line of the input contains two integer numbers n and k (0 ≤ n ≤ 2 000 000 000, 1 ≤ k ≤ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. -----Output----- Print w — the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10^{k}. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). -----Examples----- Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 -----Note----- In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s = input().split() k = int(s[1]) s = s[0] if s.count('0') < k: if s.count('0') > 0: print(len(s) - 1) else: print(len(s)) return have = 0 its = 0 for i in range(len(s) - 1, -1, -1): its += 1 if s[i] == '0': have += 1 if have == k: print(its - have) return ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It's autumn now, the time of the leaf fall. Sergey likes to collect fallen leaves in autumn. In his city, he can find fallen leaves of maple, oak and poplar. These leaves can be of three different colors: green, yellow or red. Sergey has collected some leaves of each type and color. Now he wants to create the biggest nice bouquet from them. He considers the bouquet nice iff all the leaves in it are either from the same type of tree or of the same color (or both). Moreover, he doesn't want to create a bouquet with even number of leaves in it, since this kind of bouquets are considered to attract bad luck. However, if it's impossible to make any nice bouquet, he won't do anything, thus, obtaining a bouquet with zero leaves. Please help Sergey to find the maximal number of leaves he can have in a nice bouquet, which satisfies all the above mentioned requirements. Please note that Sergey doesn't have to use all the leaves of the same color or of the same type. For example, if he has 20 maple leaves, he can still create a bouquet of 19 leaves. -----Input----- IThe first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows." The first line of each test case contains three space-separated integers MG MY MR denoting the number of green, yellow and red maple leaves respectively. The second line contains three space-separated integers OG OY OR denoting the number of green, yellow and red oak leaves respectively. The third line of each test case contains three space-separated integers PG PY PR denoting the number of green, yellow and red poplar leaves respectively. -----Output----- For each test case, output a single line containing the maximal amount of flowers in nice bouquet, satisfying all conditions or 0 if it's impossible to create any bouquet, satisfying the conditions. -----Constraints----- - 1 ≤ T ≤ 10000 - Subtask 1 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤ 5 - Subtask 2 (50 points): 0 ≤ MG, MY, MR, OG, OY, OR, PG, PY, PR ≤ 109 -----Example----- Input:1 1 2 3 3 2 1 1 3 4 Output:7 -----Explanation----- Example case 1. We can create a bouquet with 7 leaves, for example, by collecting all yellow leaves. This is not the only way to create the nice bouquet with 7 leaves (for example, Sergey can use all but one red leaves), but it is impossible to create a nice bouquet with more than 7 leaves. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for t in range(int(input())): l1=list(map(int,input().split())) l2=list(map(int,input().split())) l3=list(map(int,input().split())) max=0 g=l1[0]+l2[0]+l3[0] y=l1[1]+l2[1]+l3[1] r=l1[2]+l2[2]+l3[2] if g%2==0: g-=1 if y%2==0: y-=1 if r%2==0: r-=1 if max<g: max=g if max<r: max=r if max<y: max=y m=l1[0]+l1[1]+l1[2] o=l2[0]+l2[1]+l2[2] p=l3[0]+l3[1]+l3[2] if m%2==0: m-=1 if o%2==0: o-=1 if p%2==0: p-=1 if max<m: max=m if max<o: max=o if max<p: max=p print(max) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a random uniform player among $n-1$ players except himself. The game stops when one person will have all the biscuits. As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time. For convenience, as the answer can be represented as a rational number $\frac{p}{q}$ for coprime $p$ and $q$, you need to find the value of $(p \cdot q^{-1})\mod 998\,244\,353$. You can prove that $q\mod 998\,244\,353 \neq 0$. -----Input----- The first line contains one integer $n\ (2\le n\le 100\,000)$: the number of people playing the game. The second line contains $n$ non-negative integers $a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$, where $a_i$ represents the number of biscuits the $i$-th person own at the beginning. -----Output----- Print one integer: the expected value of the time that the game will last, modulo $998\,244\,353$. -----Examples----- Input 2 1 1 Output 1 Input 2 1 2 Output 3 Input 5 0 0 0 0 35 Output 0 Input 5 8 4 2 0 1 Output 801604029 -----Note----- For the first example, in the first second, the probability that player $1$ will give the player $2$ a biscuit is $\frac{1}{2}$, and the probability that player $2$ will give the player $1$ a biscuit is $\frac{1}{2}$. But anyway, the game will stop after exactly $1$ second because only one player will occupy all biscuits after $1$ second, so the answer is $1$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python MOD = 998244353 n = int(input()) a = list(map(int, input().split())) tot = sum(a) def inv(x): return pow(x, MOD - 2, MOD) l = [0, pow(n, tot, MOD) - 1] for i in range(1, tot): aC = i cC = (n - 1) * (tot - i) curr = (aC + cC) * l[-1] curr -= tot * (n - 1) curr -= aC * l[-2] curr *= inv(cC) curr %= MOD l.append(curr) out = 0 for v in a: out += l[tot - v] out %= MOD zero = l[tot] out -= (n - 1) * zero out *= inv(n) print(out % MOD) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: For her next karate demonstration, Ada will break some bricks. Ada stacked three bricks on top of each other. Initially, their widths (from top to bottom) are W1,W2,W3. Ada's strength is S. Whenever she hits a stack of bricks, consider the largest k≥0 such that the sum of widths of the topmost k bricks does not exceed S; the topmost k bricks break and are removed from the stack. Before each hit, Ada may also decide to reverse the current stack of bricks, with no cost. Find the minimum number of hits Ada needs in order to break all bricks if she performs the reversals optimally. You are not required to minimise the number of reversals. Input The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. The first and only line of each test case contains four space-separated integers S, W1, W2 and W3.Output For each test case, print a single line containing one integer ― the minimum required number of hits.Constraints - 1≤T≤64 - 1≤S≤8 - 1≤Wi≤2 for each valid i it is guaranteed that Ada can break all bricksExample Input 3 3 1 2 2 2 1 1 1 3 2 2 1 Example Output 2 2 2 Explanation Example case 1: Ada can reverse the stack and then hit it two times. Before the first hit, the widths of bricks in the stack (from top to bottom) are (2,2,1). After the first hit, the topmost brick breaks and the stack becomes (2,1). The second hit breaks both remaining bricks. In this particular case, it is also possible to hit the stack two times without reversing. Before the first hit, it is (1,2,2). The first hit breaks the two bricks at the top (so the stack becomes (2)) and the second hit breaks the last brick. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python T = int(input()) for _ in range(T): W = list(map(int, input().strip().split())) S = W[0] W = W[1:] W = W[::-1] i = 0 c = 0 flag = 0 while (len(W) != 0 or flag != 1) and i<len(W): k = i su = 0 while su <= S and k<len(W)-1: su += W[k] k += 1 if su-W[k-1]<=S: c += 1 else: flag = 1 i += 1 print(c-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After learning a lot about space exploration, a little girl named Ana wants to change the subject. Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it: You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $(i,j)$ is considered the same as the pair $(j,i)$. -----Input----- The first line contains a positive integer $N$ ($1 \le N \le 100\,000$), representing the length of the input array. Eacg of the next $N$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $1\,000\,000$. -----Output----- Output one number, representing how many palindrome pairs there are in the array. -----Examples----- Input 3 aa bb cd Output 1 Input 6 aab abcac dffe ed aa aade Output 6 -----Note----- The first example: aa $+$ bb $\to$ abba. The second example: aab $+$ abcac $=$ aababcac $\to$ aabccbaa aab $+$ aa $=$ aabaa abcac $+$ aa $=$ abcacaa $\to$ aacbcaa dffe $+$ ed $=$ dffeed $\to$ fdeedf dffe $+$ aade $=$ dffeaade $\to$ adfaafde ed $+$ aade $=$ edaade $\to$ aeddea The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #!/usr/bin/env python3 """ Created on Wed Feb 28 11:47:12 2018 @author: mikolajbinkowski """ import sys N = int(input()) string_count = {} for _ in range(N): s = str(input()) char_count = {} for c in s: char_count[c] = char_count.get(c, 0) + 1 s0 = [] for a in 'abcdefghijklmnopqrstuvwxyz': if char_count.get(a, 0) % 2 == 1: s0.append(a) s1 = ''.join(s0) string_count[s1] = string_count.get(s1, 0) + 1 pairs = 0 for s, v in list(string_count.items()): pairs += v * (v-1) // 2 for i in range(len(s)): pairs += v * string_count.get(s[:i] + s[i+1:], 0) print(pairs) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- 0 01 10 012 101 210 0123 1012 2101 3210 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n=int(input()) if n==1: print("0") else: s=[] for i in range(n): s.append(str(i)) print(''.join(s)) p=1 for i in range(n-1): s.pop(n-1) s=[str(p)]+s print(''.join(s)) p+=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers p_{i}, a_{i} and b_{i}, where p_{i} is the price of the i-th t-shirt, a_{i} is front color of the i-th t-shirt and b_{i} is back color of the i-th t-shirt. All values p_{i} are distinct, and values a_{i} and b_{i} are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color c_{j}. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. -----Input----- The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1 000 000 000), where p_{i} equals to the price of the i-th t-shirt. The following line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3), where a_{i} equals to the front color of the i-th t-shirt. The following line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3), where b_{i} equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers. The following line contains sequence c_1, c_2, ..., c_{m} (1 ≤ c_{j} ≤ 3), where c_{j} equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. -----Output----- Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. -----Examples----- Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) p = [int(i) for i in input().split()] a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] s = [] for i in range(n): s.append([p[i], a[i], b[i]]) s = sorted(s) m = int(input()) c = [int(i) for i in input().split()] idx = [0]*4 ans = [] for i in range(m): ci = c[i] while idx[ci] < n: if s[idx[ci]][1] == ci or s[idx[ci]][2] == ci: s[idx[ci]][1] = 0 s[idx[ci]][2] = 0 ans.append(s[idx[ci]][0]) break idx[ci]+=1 if idx[ci] == n: ans.append(-1) print(*ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $1 \le x \le s$, buy food that costs exactly $x$ burles and obtain $\lfloor\frac{x}{10}\rfloor$ burles as a cashback (in other words, Mishka spends $x$ burles and obtains $\lfloor\frac{x}{10}\rfloor$ back). The operation $\lfloor\frac{a}{b}\rfloor$ means $a$ divided by $b$ rounded down. It is guaranteed that you can always buy some food that costs $x$ for any possible value of $x$. Your task is to say the maximum number of burles Mishka can spend if he buys food optimally. For example, if Mishka has $s=19$ burles then the maximum number of burles he can spend is $21$. Firstly, he can spend $x=10$ burles, obtain $1$ burle as a cashback. Now he has $s=10$ burles, so can spend $x=10$ burles, obtain $1$ burle as a cashback and spend it too. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. The next $t$ lines describe test cases. Each test case is given on a separate line and consists of one integer $s$ ($1 \le s \le 10^9$) — the number of burles Mishka initially has. -----Output----- For each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally. -----Example----- Input 6 1 10 19 9876 12345 1000000000 Output 1 11 21 10973 13716 1111111111 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math from decimal import Decimal import heapq import copy import heapq from collections import deque def na(): n = int(input()) b = [int(x) for x in input().split()] return n,b def nab(): n = int(input()) b = [int(x) for x in input().split()] c = [int(x) for x in input().split()] return n,b,c def dv(): n, m = list(map(int, input().split())) return n,m def da(): n, m = list(map(int, input().split())) a = list(map(int, input().split())) return n,m, a def dva(): n, m = list(map(int, input().split())) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] return n,m,b def eratosthenes(n): sieve = list(range(n + 1)) for i in sieve: if i > 1: for j in range(i + i, len(sieve), i): sieve[j] = 0 return sorted(set(sieve)) def lol(lst,k): k=k%len(lst) ret=[0]*len(lst) for i in range(len(lst)): if i+k<len(lst) and i+k>=0: ret[i]=lst[i+k] if i+k>=len(lst): ret[i]=lst[i+k-len(lst)] if i+k<0: ret[i]=lst[i+k+len(lst)] return(ret) def nm(): n = int(input()) b = [int(x) for x in input().split()] m = int(input()) c = [int(x) for x in input().split()] return n,b,m,c def dvs(): n = int(input()) m = int(input()) return n, m def fact(n): tc = [] ans = {} d = 2 while d * d <= n: if n % d == 0: tc.append(d) n //= d else: d += 1 if n > 1: tc.append(n) for i in tc: ans[i] = ans.get(i, 0) + 1 return ans for i in range(int(input())): s = int(input()) ans = 0 while s >= 10: d = s // 10 ans += d * 10 s += d s -= d * 10 ans += s print(ans) ```