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: 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:----- 5 1 2 3 4 5 -----Sample Output:----- 1 1 32 1 32 654 1 32 654 10987 1 32 654 10987 1514131211 -----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()) for i in range(n): for j in range(n): if i>=j: print(int((i+1)*(i+2)/2)-j,end='') print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Two integers A and B are the inputs. Write a program to find GCD and LCM of A and B. -----Input----- The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer A and B. -----Output----- Display the GCD and LCM of A and B separated by space respectively. The answer for each test case must be displayed in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A,B ≤ 1000000 -----Example----- Input 3 120 140 10213 312 10 30 Output 20 840 1 3186456 10 30 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 GCD(x, y): while y: x, y = y, x % y return x def LCM(x, y): lcm = (x*y)//GCD(x,y) return lcm t = int(input()) while t>0: x,y = list(map(int,input().split())) print(GCD(x,y),LCM(x,y)) t -=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Cyael is a teacher at a very famous school in Byteland and she is known by her students for being very polite to them and also to encourage them to get good marks on their tests. Then, if they get good marks she will reward them with candies :) However, she knows they are all very good at Mathematics, so she decided to split the candies evenly to all the students she considers worth of receiving them, so they don't fight with each other. She has a bag which initially contains N candies and she intends to split the candies evenly to K students. To do this she will proceed as follows: while she has more than K candies she will give exactly 1 candy to each student until she has less than K candies. On this situation, as she can't split candies equally among all students she will keep the remaining candies to herself. Your job is to tell how many candies will each student and the teacher receive after the splitting is performed. -----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 will consist of 2 space separated integers, N and K denoting the number of candies and the number of students as described above. -----Output----- For each test case, output a single line containing two space separated integers, the first one being the number of candies each student will get, followed by the number of candies the teacher will get. -----Constraints----- - T<=100 in each test file - 0 <= N,K <= 233 - 1 -----Example-----Input: 2 10 2 100 3 Output: 5 0 33 1 -----Explanation----- For the first test case, all students can get an equal number of candies and teacher receives no candies at all For the second test case, teacher can give 33 candies to each student and keep 1 candy to herselfUpdate: There may be multiple whitespaces before, after or between the numbers in input. 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 try: t = int(input()) for _ in range(t): n, k = map(int, input().split()) if k == 0: print(0, n) else: print(n//k, n%k) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is a private detective. He was asked to investigate a case of murder in the city of Frangton. Chef arrived in Frangton to find out that the mafia was involved in the case. Chef spent some time watching for people that belong to the clan and was able to build a map of relationships between them. He knows that a mafia's organizational structure consists of a single Don, heading a hierarchical criminal organization. Each member reports exactly to one other member of the clan. It's obvious that there are no cycles in the reporting system of the mafia. There are N people in the clan, for simplicity indexed from 1 to N, and Chef knows who each of them report to. Member i reports to member Ri. Now, Chef needs to identfy all potential killers to continue his investigation. Having considerable knowledge about the mafia's activities, Chef knows that the killer must be a minor criminal, that is, one of the members who nobody reports to. Please find the list of potential killers for Chef. Since Don reports to nobody, his Ri will be equal to 0. -----Input----- The first line of input contains one integer N. Next line has N space-separated integers, the ith integer denotes Ri — the person whom the ith member reports to. -----Output----- Output a list of space-separated integers in ascending order — the indices of potential killers. -----Constraints----- - 1 ≤ N ≤ 105 - 1 ≤ Ri ≤ N except for Don, whose Ri equals to 0. - It is guaranteed that there are no cycles in the reporting structure. -----Subtasks----- - Subtask #1 [50 points]: N ≤ 10000 - Subtask #2 [50 points]: No additional constraints -----Example----- Input: 6 0 1 1 2 2 3 Output: 4 5 6 -----Explanation----- The reporting structure: The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = eval(input()) r = list(map(int, input().split())) tree = dict() i = 1 for j in r: c = tree.get(j) if c: tree[j].append(i) else: tree[j] = [i] if not tree.get(i): tree[i] = [] i += 1 s = [] for elem in tree: if not tree[elem]: s.append(str(elem)) print(' '.join(s)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Wet Shark once had 2 sequences: {a_n}= {a_1, a_2, a_3, ... , a_(109)} {b_n} = {b_1, b_2, b_3, ... , b_(109)} However, he only kept one element from each sequence. Luckily, both the elements that Wet Shark kept have the same index in Wet Shark's sequences: that is, he took a_i and b_i for some 1 ≤ i ≤ 109. Right after Wet Shark loses his sequences, he finds that he actually needs them to break the code of Cthulhu to escape a labyrinth. Cthulhu's code is a single floating point number Q. However, the code verifier is faulty. If Wet Shark enters any code c such that |c - Q| ≤ 0.01 , Cthulhu's code checker will allow him to escape. Wet Shark now starts to panic, and consults Dry Dolphin for help via ultrasonic waves. After the Dry Dolphin Sequence Processing Factory processes data of Wet Shark's sequences, the machines give Wet Shark the following 2 relations his sequences follow for all 1 ≤ n < 109, where x = sqrt(2) and y = sqrt(3). Wet Shark is now clueless on how to compute anything, and asks you for help. Wet Shark has discovered that Cthulhu's code is actually defined as Q = (a_k + b_k) / (2^s), where s is a predetermined number, k is the index of another element in Wet Shark's sequence, and a_k, b_k are precisely the kth elements of Wet Shark's sequences {a_n} and {b_n}, respectively. Given k, i, and the 2 elements of the arrays Wet Shark has lost, find any value of the code c that will allow Wet Shark to exit Cthulhu's labyrinth. -----Input----- The first line of input contains 3 space separated integers i, k, s — the common index of the two elements Wet Shark kept, the index of Wet Shark's array needed to break Cthulhu's code, and the number s described in the problem statement, respectively. It is guaranteed that Cthulhu's code, Q, is between -109 and 109 (both inclusive). The second line of the input contains 2 space separated integers a_i and b_i, representing the ith element of sequence {a_n} and the ith element of sequence {b_n}, respectively. -----Output----- Output any number c that will crack Cthulhu's code. Recall that if Wet Shark enters any code c such that |c - Q| ≤ 0.01 , Cthulhu's code checker will allow him to exit the labyrinth. ----- Constraints ----- - SUBTASK 1: 20 POINTS - 1 ≤ i ≤ 103 - 1 ≤ k ≤ 103 - -103 ≤ s ≤ 103 - 1 ≤ a_i, b_i ≤ 103 - SUBTASK 2: 80 POINTS - 1 ≤ i ≤ 1010 - 1 ≤ k ≤ 1010 - -1010 ≤ s ≤ 1010 - 1 ≤ a_i, b_i ≤ 1010 It is guaranteed that -1010 ≤ Q ≤  1010. -----Example----- Input: 1 1 5 4 5 Output: 0.28125 -----Explanation----- Example case 1. In this case, a_1 = 4, b_1 = 5, and s = 5. Cthulhu's code in this case is (a_1 + b_1) / (2s) = 9/32 = 0.28125. 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 main(): #print("enter i, k, s") IN = '11 6 5' z = IN.split() z = input().split() i = int(z[0]) k = int(z[1]) s = int(z[2]) #print("enter a_i and b_i") IN = '4 5' z = IN.split() z = input().split() a_i = int(z[0]) b_i = int(z[1]) #print( "i = %d k = %d s = %d " % (i, k, s) ) #print( "a_i = %d b_i = %d" % (a_i, b_i) ) x = math.sqrt(2) y = math.sqrt(3) #print(x,y) # Obtaining the k-th element when k >= i if(i<=k): diff = k-i #if both k and i are odd or even if(k-i)%2==0: #print("#1") ans = (a_i + b_i) * math.pow(2,2*(k-i)-s) #diff = int(diff/2) #ans = (a_i + b_i) * math.pow(2,4*diff-s) #if i and k are of different parities then obtaining first # a_(i+1) and b_(i+1) else: #print("#2") ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,2*(k-(i+1))-s ) diff = int(diff/2) ans = (2*x*a_i + 2*x*y*b_i) * math.pow(2,4*diff - s) #print("1: ", (2*x*a_i + 2*x*y*b_i)) #print("2: ", math.pow(2,4*diff - 2- s)) #print("2 sol: ", math.pow(2,4*int(diff)-s)) #print("diff: ",diff) # Obtaining the k_th element when k < i else: diff = i-k #if both k and i are odd or even if(i-k)%2==0: #print("#3") ans = (a_i + b_i) / math.pow(2,2*(i-k)+s) #diff = int(diff/2) #ans = (a_i + b_i) / math.pow(2,4*diff+s) #if i and k are of different parities then obtaining first # a_(i+1) and b_(i+1) else: #print("#4") ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,2*(i+1-k)+s) diff = int(diff/2) ans = (2*x*a_i + 2*x*y*b_i) / math.pow(2,4*diff + 4 + s) print(ans) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given a number $n$, give the last digit of sum of all the prime numbers from 1 to $n$ inclusive. -----Input:----- - First line contains number of testcase $t$. - Each testcase contains of a single line of input, number $n$. -----Output:----- Last digit of sum of every prime number till n. -----Constraints----- - $1 \leq T \leq 10$ - $2 \leq N \leq 10^6$ -----Sample Input:----- 1 10 -----Sample Output:----- 7 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 N = 10**6 sum_arr = [0] * (N + 1) def lprime(): arr = [0] * (N + 1) arr[0] = 1 arr[1] = 1 for i in range(2, math.ceil(math.sqrt(N) + 1)): if arr[i] == 0: for j in range(i * i, N + 1, i): arr[j] = 1 curr_prime_sum = 0 for i in range(1, N + 1): if arr[i] == 0: curr_prime_sum += i sum_arr[i] = curr_prime_sum n=int(input()) lprime() for _ in range(n): x=int(input()) print(sum_arr[x]%10) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef solved so many hard questions, now he wants to solve some easy problems for refreshment. Chef asks Cheffina for the new question. Cheffina challanges the chef to print the total number of 1's in the binary representation of N(natural number). -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, $N$. -----Output:----- For each test case, output in a single line answer. -----Constraints----- - $1 \leq T \leq 10^6$ - $1 \leq N \leq 10^6$ -----Sample Input:----- 2 2 5 -----Sample Output:----- 1 2 -----EXPLANATION:----- For 1) Binary representation of 2 is 10. i.e. only one 1 present in it. For 2) Binary representation of 5 is 101, i.e. two 1's present in it. 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()) print(bin(n).count("1")) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The only difference between easy and hard versions is constraints. You are given a sequence $a$ consisting of $n$ positive integers. Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are three block palindromes but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not. Your task is to choose the maximum by length subsequence of $a$ that is a three blocks palindrome. You have to answer $t$ independent test cases. Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — 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 2000$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 26$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $26$. It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$ ($\sum n \le 2000$). -----Output----- For each test case, print the answer — the maximum possible length of some subsequence of $a$ that is a three blocks palindrome. -----Example----- Input 6 8 1 1 2 2 3 2 1 1 3 1 3 3 4 1 10 10 1 1 26 2 2 1 3 1 1 1 Output 7 2 4 1 1 3 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 from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == "\n": return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): def f(a,b): if a == b: return len(d[a]) da = d[a] db = d[b] res = 0 for x in range(len(da) >> 1): l = da[x] r = da[-1-x] i = bisect.bisect_left(db,l) j = bisect.bisect_left(db,r) y = max(0,j-i) s = 2*(x+1)+y if res < s: res = s return res t = I() for _ in range(t): n = I() a = LI() m = max(a) d = [[] for i in range(m)] for i in range(n): ai = a[i]-1 d[ai].append(i) ans = 1 for a in range(m): if not d[a]: continue for b in range(m): if not d[b]: continue res = f(a,b) if ans < res: ans = res print(ans) return #Solve def __starting_point(): solve() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: During Quarantine Time Chef is at home and he was quite confused about what to cook so, he went to his son and asked about what would he prefer to have? He replied, cakes. Now, chef cook $N$ number of cake and number of layers for every cake is different. After cakes are baked, Chef arranged them in a particular order and then generates a number by putting number of layers of cakes as digit in sequence (e.g., if chef arranges cakes with layers in sequence $2$, $3$ and $5$ then generated number is $235$). Chef has to make his son powerful in mathematics, so he called his son and ask him to arrange the cakes in all the possible ways and every time when different sequence is generated he has to note down the number. At the end he has to find sum of all the generated numbers. So, help him to complete this task. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - The first line of each test case contains a single integer $N$ denoting number of cakes. - The second line contains $N$ space-separated integers $L1$ $L2$ … $LN$ layers of the cake. -----Output:----- For each test case, print a single line containing sum of all the possible numbers which is generated by arranging cake in different sequence. -----Constraints :----- - $1 \leq T \leq 2*10^5$ - $1 \leq N, L1, L2, L3,…, LN \leq 9$ -----Sample Input:----- 1 3 2 3 5 -----Sample Output:----- 2220 -----Explanation:----- Sum of all possibilities : $235 + 532 + 253 + 352 + 523 + 325 = 2220 $ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #cook your recipe from math import factorial test_cases = int(input()) for _ in range(test_cases): n = int(input()) sum1 = 0 final_sum = 0 num = list(map(int, input().split())) rep_time = factorial(n - 1) rep_count = dict() for i in num: if i in rep_count: rep_count[i] +=1 else: rep_count[i] =1 for j in rep_count: if rep_count[j] ==1: sum1 += j * factorial(n - rep_count[j]) else: sum1 += j * factorial(n-1)/ factorial(n - rep_count[j]) for k in range(n): final_sum += sum1 * (10**k) print(int(final_sum)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: Either this person does not go on the trip, Or at least $k$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $a$ and $b$ are friends and $b$ and $c$ are friends, it does not necessarily imply that $a$ and $c$ are friends. For each day, find the maximum number of people that can go on the trip on that day. -----Input----- The first line contains three integers $n$, $m$, and $k$ ($2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$, $1 \le k < n$) — the number of people, the number of days and the number of friends each person on the trip should have in the group. The $i$-th ($1 \leq i \leq m$) of the next $m$ lines contains two integers $x$ and $y$ ($1\leq x, y\leq n$, $x\ne y$), meaning that persons $x$ and $y$ become friends on the morning of day $i$. It is guaranteed that $x$ and $y$ were not friends before. -----Output----- Print exactly $m$ lines, where the $i$-th of them ($1\leq i\leq m$) contains the maximum number of people that can go on the trip on the evening of the day $i$. -----Examples----- Input 4 4 2 2 3 1 2 1 3 1 4 Output 0 0 3 3 Input 5 8 2 2 1 4 2 5 4 5 2 4 3 5 1 4 1 3 2 Output 0 0 0 3 3 4 4 5 Input 5 7 2 1 5 3 2 2 5 3 4 1 2 5 3 1 3 Output 0 0 0 0 3 4 4 -----Note----- In the first example, $1,2,3$ can go on day $3$ and $4$. In the second example, $2,4,5$ can go on day $4$ and $5$. $1,2,4,5$ can go on day $6$ and $7$. $1,2,3,4,5$ can go on day $8$. In the third example, $1,2,5$ can go on day $5$. $1,2,3,5$ can go on day $6$ and $7$. 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 def solve(adj, m, k, uv): n = len(adj) nn = [len(a) for a in adj] q = deque() for i in range(n): if nn[i] < k: q.append(i) while q: v = q.popleft() for u in adj[v]: nn[u] -= 1 if nn[u] == k-1: q.append(u) res = [0]*m nk = len([1 for i in nn if i >= k]) res[-1] = nk for i in range(m-1, 0, -1): u1, v1 = uv[i] if nn[u1] < k or nn[v1] < k: res[i - 1] = nk continue if nn[u1] == k: q.append(u1) nn[u1] -= 1 if not q and nn[v1] == k: q.append(v1) nn[v1] -= 1 if not q: nn[u1] -= 1 nn[v1] -= 1 adj[u1].remove(v1) adj[v1].remove(u1) while q: v = q.popleft() nk -= 1 for u in adj[v]: nn[u] -= 1 if nn[u] == k - 1: q.append(u) res[i - 1] = nk return res n, m, k = map(int, input().split()) a = [set() for i in range(n)] uv = [] for i in range(m): u, v = map(int, input().split()) a[u - 1].add(v - 1) a[v - 1].add(u - 1) uv.append((u-1, v-1)) res = solve(a, m, k, uv) print(str(res)[1:-1].replace(' ', '').replace(',', '\n')) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given a positive integer K > 2, with prime factorization: K = p1^a1 * p2^a2 ... * pn^an Compute the following: S = a1*p1 + a2*p2 ... + an*pn. -----Input----- A list of <100 integers, one on each line, all less than $2*10^{18}$. -----Output----- For each integer compute the super factor sum and output it on a single line. -----Example----- Input: 6 7 Output: 5 7 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 os yash=(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,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997) def fix(m): for ai in yash: if m%ai==0: return ai return m def rabin_miller(a,i,n): if i==0: return 1 x=rabin_miller(a,i/2,n) if x==0: return 0 y=(x*x)%n if (y==1)and(x!=1)and(x!=n-1): return 0 if i%2!=0: y=(a*y)%n return y def gcd(x,y): if y==0: return x return gcd(y,x%y) def brent_rho(n): if (n<=3)or(rabin_miller(random.randint(2,n-2),n-1,n)==1): return n y,r,q,m=1,1,1,203 while 1: x=y for i in range(1,r+1): y=(y*y+1)%n k=0 while 1: ys=y for i in range(1,min(m,r-k)+1): y=(y*y+1)%n q=(q*abs(x-y))%n g=gcd(q,n) k+=m if (k>=r)or(g>1): break r*=2 if g>1: break if g==n: while 1: ys=(ys*ys+1)%n g=gcd(abs(x-ys),n) if g>1: break if g==n: return n return brent_rho(g) def divsum2(n): if n==1: return 0 d=brent_rho(n) d=fix(d) assert (d<=3)or(rabin_miller(random.randint(2,d-2),d-1,d)==1) f,m=0,n while m%d==0: m/=d f = f + 1; return (f*d)+(divsum2(m)) try: while(1): z=eval(input()) print(divsum2(z)) except: os.sys.exit(0); ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name. There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account? Formally, we assume that two words denote the same name, if using the replacements "u" [Image] "oo" and "h" [Image] "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements. For example, the following pairs of words denote the same name: "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" $\rightarrow$ "kuuper" and "kuooper" $\rightarrow$ "kuuper". "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" $\rightarrow$ "khoon" and "kkkhoon" $\rightarrow$ "kkhoon" $\rightarrow$ "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name. -----Input----- The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive. -----Output----- Print the minimal number of groups where the words in each group denote the same name. -----Examples----- Input 10 mihail oolyana kooooper hoon ulyana koouper mikhail khun kuooper kkkhoon Output 4 Input 9 hariton hkariton buoi kkkhariton boooi bui khariton boui boi Output 5 Input 2 alex alex Output 1 -----Note----- There are four groups of words in the first example. Words in each group denote same name: "mihail", "mikhail" "oolyana", "ulyana" "kooooper", "koouper" "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: "hariton", "kkkhariton", "khariton" "hkariton" "buoi", "boooi", "boui" "bui" "boi" In the third example the words are equal, so they denote the same name. 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()) s = set() for a in range(n): name = input() name = name.replace('u', 'oo') while (name.count('kh') > 0): name = name.replace('kh', 'h') s.add(name) print(len(s)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The only difference between easy and hard versions is constraints. Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you. There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free. Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$. Calculate the minimum number of coins you have to spend so that everyone votes for you. -----Input----- The first line contains one integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of voters. The next $n$ lines contains the description of voters. $i$-th line contains two integers $m_i$ and $p_i$ ($1 \le p_i \le 10^9, 0 \le m_i < n$). It is guaranteed that the sum of all $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you. -----Example----- Input 3 3 1 5 2 10 2 8 7 0 1 3 1 1 1 6 1 1 1 4 1 4 1 6 2 6 2 3 2 8 2 7 4 4 5 5 Output 8 0 7 -----Note----- In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: ${3} \rightarrow {1, 3} \rightarrow {1, 2, 3}$. In the second example you don't need to buy votes. The set of people voting for you will change as follows: ${1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}$. In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: ${2, 5} \rightarrow {1, 2, 3, 4, 5} \rightarrow {1, 2, 3, 4, 5, 6}$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys def I(): return sys.stdin.readline().rstrip() class Heap: def __init__( self ): self.l = [ -1 ] self.n = 0 def n( self ): return self.n def top( self ): return self.l[ 1 ] def ins( self, x ): self.l.append( x ) n = len( self.l ) - 1 i = n while i > 1: j = i // 2 if self.l[ j ] > self.l[ i ]: self.l[ j ], self.l[ i ] = self.l[ i ], self.l[ j ] i = j else: break def pop( self ): r = self.l[ 1 ] l = self.l.pop() n = len( self.l ) - 1 if n: self.l[ 1 ] = l i = 1 while True: j = i * 2 k = j + 1 if k < len( self.l ) and self.l[ i ] > max( self.l[ j ], self.l[ k ] ): if self.l[ j ] == min( self.l[ j ], self.l[ k ] ): self.l[ i ], self.l[ j ] = self.l[ j ], self.l[ i ] i = j else: self.l[ i ], self.l[ k ] = self.l[ k ], self.l[ i ] i = k elif k < len( self.l ) and self.l[ i ] > self.l[ k ]: self.l[ i ], self.l[ k ] = self.l[ k ], self.l[ i ] i = k elif j < len( self.l ) and self.l[ i ] > self.l[ j ]: self.l[ i ], self.l[ j ] = self.l[ j ], self.l[ i ] i = j else: break return r t = int( I() ) for _ in range( t ): n = int( I() ) voter = [ list( map( int, I().split() ) ) for _ in range( n ) ] h = Heap() d = {} for m, p in voter: if m not in d: d[ m ] = [] d[ m ].append( p ) need = {} c = 0 sk = sorted( d.keys() ) for m in sk: need[ m ] = max( 0, m - c ) c += len( d[ m ] ) c = 0 ans = 0 for m in sk[::-1]: for p in d[ m ]: h.ins( p ) while c < need[ m ]: c += 1 ans += h.pop() print( ans ) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist? - The vertices are numbered 1,2,..., n. - The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i. - If the i-th character in s is 1, we can have a connected component of size i by removing one edge from the tree. - If the i-th character in s is 0, we cannot have a connected component of size i by removing any one edge from the tree. If such a tree exists, construct one such tree. -----Constraints----- - 2 \leq n \leq 10^5 - s is a string of length n consisting of 0 and 1. -----Input----- Input is given from Standard Input in the following format: s -----Output----- If a tree with n vertices that satisfies the conditions does not exist, print -1. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. -----Sample Input----- 1111 -----Sample Output----- -1 It is impossible to have a connected component of size n after removing one edge from a tree with n vertices. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s = input() if s[0] == '0' or s[-2] == '0' or s[-1] == '1': # 's' should be like "1xx...x0" print((-1)) elif s[:-1] != s[-2::-1]: print((-1)) else: half = len(s) // 2 one_indices = [i+1 for i in range(1, half) if s[i] == '1'] # not including 0 or larger than n//2 parents = [0] * (len(s) + 1) parent_index = 1 for index in one_indices: for i in range(parent_index, index): parents[i] = index parent_index = index root = parent_index + 1 parents[parent_index] = root for index in range(root + 1, len(s) + 1): parents[index] = root for node, parent in enumerate(parents): if parent == 0: # This means node is 0 or the root of the tree. continue print((node, parent)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an array $a$ of length $n$. A subsequence of this array is valid, if it satisfies these two conditions: - There shouldn't be any two even numbers within a distance of $K$, both which have been chosen in the subsequence. i.e. there shouldn't be two indices $i, j$ such that $a_i$ and $a_j$ are even, $|i - j| \leq K$ and $a_i$ and $a_j$ are in the subsequence. - Similarly, there shouldn't be any two odd numbers within a distance of $K$, both which have been chosen in the subsequence The sum of a subsequence is the sum of all the numbers in it. Your task is find the maximum sum possible in a valid subsequence of the given array. Print this maximum sum. -----Input----- - The first line of the input contains an integer $T$ denoting the number of test cases. The description of the test cases follows. - The first line of each test case contains two space-separated integers $n, k$. - The second line of each test case contains $n$ space-separated integers denoting the array $a$. -----Output----- For each test case, output an integer corresponding to the answer of the problem. -----Constraints----- - $1 \le T \le 10^5$ - $1 \le n \leq 10^5$ - $1 \le k \leq n$ - $1 \le a_i \leq 10^9$ - Sum of $n$ over all the test cases doesn't exceed $10^6$ -----Example Input----- 3 1 1 3 2 1 2 2 5 2 1 2 3 4 6 -----Example Output----- 3 2 11 -----Explanation:----- Testcase 2: Only one of the two 2s can be chosen. Hence the answer is 2. Testcase 3: The subsequence containing the second, third and fifth numbers is a valid subsequence, and its sum is 2+3+6 = 11. You can check that this is the maximum possible, and hence is the answer. 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 math def main(arr,k): x=[] y=[] for e in arr: if e%2==0: x.append(e) y.append(0) else: x.append(0) y.append(e) a=[0]*n b=[0]*n a[0]=x[0] b[0]=y[0] for i in range(1,n): if i<k: a[i]=max(x[i],a[i-1]) b[i]=max(y[i],b[i-1]) else: a[i]=max(x[i]+a[i-k-1],a[i-1]) b[i]=max(y[i]+b[i-k-1],b[i-1]) print(a[-1]+b[-1]) return for i in range(int(input())): n,k=list(map(int,input().split())) arr=list(map(int,input().split())) (main(arr,k)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages. At first day Mister B read v_0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v_0 pages, at second — v_0 + a pages, at third — v_0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v_1 pages per day. Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time. Help Mister B to calculate how many days he needed to finish the book. -----Input----- First and only line contains five space-separated integers: c, v_0, v_1, a and l (1 ≤ c ≤ 1000, 0 ≤ l < v_0 ≤ v_1 ≤ 1000, 0 ≤ a ≤ 1000) — the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading. -----Output----- Print one integer — the number of days Mister B needed to finish the book. -----Examples----- Input 5 5 10 5 4 Output 1 Input 12 4 12 4 1 Output 3 Input 15 1 100 0 0 Output 15 -----Note----- In the first sample test the book contains 5 pages, so Mister B read it right at the first day. In the second sample test at first day Mister B read pages number 1 - 4, at second day — 4 - 11, at third day — 11 - 12 and finished the book. In third sample test every day Mister B read 1 page of the book, so he finished in 15 days. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python read = lambda: map(int, input().split()) c, v0, v1, a, l = read() cur = 0 cnt = 0 while cur < c: cur = max(0, cur - l) cur += min(v1, v0 + a * cnt) cnt += 1 print(cnt) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his k minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making no more than one swap each minute. Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the k minutes that they have. We denote as p_{i} the label of the cow in the i-th stall. The messiness of an arrangement of cows is defined as the number of pairs (i, j) such that i < j and p_{i} > p_{j}. -----Input----- The first line of the input contains two integers n and k (1 ≤ n, k ≤ 100 000) — the number of cows and the length of Farmer John's nap, respectively. -----Output----- Output a single integer, the maximum messiness that the Mischievous Mess Makers can achieve by performing no more than k swaps. -----Examples----- Input 5 2 Output 10 Input 1 10 Output 0 -----Note----- In the first sample, the Mischievous Mess Makers can swap the cows in the stalls 1 and 5 during the first minute, then the cows in stalls 2 and 4 during the second minute. This reverses the arrangement of cows, giving us a total messiness of 10. In the second sample, there is only one cow, so the maximum possible messiness is 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # You lost the game. n,k = map(int, input().split()) r = 0 for i in range(min(k,n//2)): r += (n-2*i-1) + (n-2*i-2) print(r) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Salmon loves to be a tidy person. One day, when he looked at the mess that he made after playing with his rubber ducks, he felt awful. Now he wants to clean up his mess, by placing his ducks into boxes. Each rubber duck has a color. There are a total of $N+1$ colors, numbered from $0$ to $N$. Salmon wants to place his $N*K$ ducks into $N$ boxes, each of which can fit $K$ ducks. Each duck should be placed inside a box. Salmon is very particular when it comes to how many colors he can place in each box. Since Salmon doesn't like lots of colors mixing together he only wants to have a maximum of $2$ distinct colors per box. Please help Salmon achieve this goal! It can be shown that there will always be at least one valid solution under given constraints. If there are multiple correct solutions, you may output any one of them. -----Input:----- - The first line contains an integer $T$, denoting the number of testcases. $T$ testcases will follow, each containing two lines. - The first line of each testcase contains two space-separated integers $N$ and $K$. - The second line of each testcase contains $N+1$ space-separated integers. The $i+1$-th integer denotes the number of ducks with color-$i$ where $0 \leq i \leq N$ -----Output:----- - Output $N$ lines for each testcase. - The $i$-th line of a testcase should contain $4$ space-separated integers $c1, m1, c2, m2$ respectively which denotes that that are $m1$ ducks of color-$c1$ and $m2$ ducks of color-$c2$ inside the $i$-th box where $0 \leq m1,m2 \leq K$ and $0 \leq c1,c2 \leq N$. - Note that even if you have only one color to put inside the $i$-th box, you should still output $4$ space-separated integers and keep either $m1$ or $m2$ as $0$. And $0 \leq c1,c2 \leq N$. - The output should be valid and should satisfy Salmon's goal. -----Constraints----- - $T=10$ - $2 \leq N \leq 10^5$ - $2 \leq K \leq 10^5$ - Total ducks for each test case is exactly $N*K$ - There can be a color with $0$ ducks -----Subtasks----- - Subtask 1 [20 points]: $2 \leq N \leq 10$, $K=2$ - Subtask 2 [30 points]: $N=2$, $K=5$ - Subtask 3 [50 points]: original constraints -----Sample Input:----- 1 2 4 3 4 1 -----Sample Output:----- 2 1 1 3 1 1 0 3 -----Explanation:----- - In the given testcase, Salmon has $N=2$ boxes, each of size $K=4$ and there are total $N*K=8$ ducks. - The first box is filled with $1$ duck of color-$2$ and $3$ ducks of color-$1$ and the second box is filled with $1$ duck of color-$1$ and $3$ ducks of color-$0$. - Each duck is inside a box and each box has at most two distinct colors. Also each box contains exactly $K=4$ ducks. 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,k=map(int,input().split()) c=[int(i) for i in input().split()] i=0 m=0 if(n==2 and k==5): c1=c c.sort() d=dict() for i in range(len(c)): for j in range(len(c1)): if(c[i]==c1[j]): d[i]=j c1[j]=-1 break while(m<n): if (i==n): print(d[n],k,d[n-1],0) c[n]-=k m+=1 else: if(c[i]>=k): print(d[i],k,d[i+1],0) c[i]=c[i]-k m+=1 elif(c[i]==0): i+=1 else: for j in range(i+1,n+1): if(c[i]+c[j]>=k): print(d[i],c[i],d[j],k-c[i]) c[j]-=k-c[i] c[i]=0 m+=1 break else: while(m<n): if (i==n): print(n,k,n-1,0) c[n]-=k m+=1 else: if(c[i]>=k): print(i,k,i+1,0) c[i]=c[i]-k m+=1 elif(c[i]==0): i+=1 else: for j in range(i+1,n+1): if(c[i]+c[j]>=k): print(i,c[i],j,k-c[i]) c[j]-=k-c[i] c[i]=0 m+=1 break ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Gru has not been in the limelight for a long time and is, therefore, planning something particularly nefarious. Frustrated by his minions' incapability which has kept him away from the limelight, he has built a transmogrifier — a machine which mutates minions. Each minion has an intrinsic characteristic value (similar to our DNA), which is an integer. The transmogrifier adds an integer K to each of the minions' characteristic value. Gru knows that if the new characteristic value of a minion is divisible by 7, then it will have Wolverine-like mutations. Given the initial characteristic integers of N minions, all of which are then transmogrified, find out how many of them become Wolverine-like. -----Input Format:----- The first line contains one integer, T, which is the number of test cases. Each test case is then described in two lines. The first line contains two integers N and K, as described in the statement. The next line contains N integers, which denote the initial characteristic values for the minions. -----Output Format:----- For each testcase, output one integer in a new line, which is the number of Wolverine-like minions after the transmogrification. -----Constraints:----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 100 - 1 ≤ K ≤ 100 - All initial characteristic values lie between 1 and 105, both inclusive. -----Example----- Input: 1 5 10 2 4 1 35 1 Output: 1 -----Explanation:----- After transmogrification, the characteristic values become {12,14,11,45,11}, out of which only 14 is divisible by 7. So only the second minion becomes Wolverine-like. 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())): yy=input() y=[int(e) for e in yy.split()] zz=input() z=[int(e) for e in zz.split()] count=0 for i in z: a=i+y[1] if a%7==0: count+=1 print(count) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mark loves eating chocolates and also likes to be fit. Given the calorie count for every chocolate he eats, find what he has to do to burn the calories. The name of the chocolates along with its calorie count are given as follows: Calories per one whole bar: Dairy milk (D) 238 Twix (T) 244 Milky Bar (M) 138 Bounty (B) 279 Crunchie (C) 186 The exercises preferred by him and the calories burnt are as follows: Calories burnt per km: Running 50 Cycling 5 Walking 0.5 Find the number of kilometers he has to run, cycle or walk to burn all of the calories. Priority given to the exercises is as follows: Running > Cycling > Walking -----Input:----- - It is a one line string consisting of the names(initial letter) of all the chocolates he has eaten. -----Output:----- Print three lines. First line representing how much he ran(in km), second line representing how much he cycled(in km), third line representing how much he walked(in km). -----Constraints----- - 1 <= length of input string <= 10. -----Sample Input:----- DDTM -----Sample Output:----- 17 1 6 -----EXPLANATION:----- Calorie intake = 238 + 238 + 244 + 138 = 858 ( 17km x 50 ) + ( 1km x 5 ) + ( 6km x 0.5 ) = 858. 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 d = { 'D': 238, 'T': 244, 'M': 138, 'B': 279, 'C': 186 } s = list(input()) totalCal = 0 for i in range(len(s)): if s[i] == 'D': totalCal += d['D'] if s[i] == 'T': totalCal += d['T'] if s[i] == 'M': totalCal += d['M'] if s[i] == 'B': totalCal += d['B'] if s[i] == 'C': totalCal += d['C'] R = totalCal // 50 Rm = totalCal % 50 C = Rm // 5 Cm = Rm % 5 x = totalCal - (R * 50 + C * 5) # print(totalCal - R * 50 + C * 5) W = int(x * 4 * 0.5) # print(R * 50 + C * 5 + W * 0.5) print(R) print(C) print(W) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef Watson uses a social network called ChefBook, which has a new feed consisting of posts by his friends. Each post can be characterized by f - the identifier of the friend who created the post, p - the popularity of the post(which is pre-calculated by ChefBook platform using some machine learning algorithm) and s - the contents of the post which is a string of lower and uppercase English alphabets. Also, Chef has some friends, which he has marked as special. The algorithm used by ChefBook for determining the order of posts in news feed is as follows: - Posts of special friends should be shown first, irrespective of popularity. Among all such posts the popular ones should be shown earlier. - Among all other posts, popular posts should be shown earlier. Given, a list of identifiers of Chef's special friends and a list of posts, you have to implement this algorithm for engineers of ChefBook and output the correct ordering of posts in the new feed. -----Input----- First line contains N, number of special friends of Chef and M, the number of posts. Next line contains N integers A1, A2, ..., AN denoting the identifiers of special friends of Chef. Each of the next M lines contains a pair of integers and a string denoting f, p and s, identifier of the friend who created the post, the popularity of the post and the contents of the post, respectively. It is guaranteed that no two posts have same popularity, but the same friend might make multiple posts. -----Output----- Output correct ordering of posts in news feed in M lines. Output only the contents of a post. -----Constraints----- - 1 ≤ N, M ≤ 103 - 1 ≤ Ai, f, p ≤ 105 - 1 ≤ length(s) ≤ 100 -----Example----- Input: 2 4 1 2 1 1 WhoDoesntLoveChefBook 2 2 WinterIsComing 3 10 TheseViolentDelightsHaveViolentEnds 4 3 ComeAtTheKingBestNotMiss Output: WinterIsComing WhoDoesntLoveChefBook TheseViolentDelightsHaveViolentEnds ComeAtTheKingBestNotMiss -----Explanation----- First we should show posts created by friends with identifiers 1 and 2. Among the posts by these friends, the one with more popularity should be shown first. Among remaining posts, we show those which are more popular first. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys ans=0 n,m=list(map(int,input().split())) aaaaa=100 li=list(map(int,input().split())) non_special,special=[],[] for i in range(m): ans+=1 f,p,s=list(map(str,input().split())) f=int(f) poww=pow(1,2) p=int(p) if f not in li: ans+=1 non_special.append((p,s)) ans-=1 else: ans+=1 special.append((p,s)) non_special.sort(reverse=True) aaaa=pow(1,2) special.sort(reverse=True) for temp in range(len(special)): ans+=1 print(special[temp][1]) for temp in non_special: ans+=1 print(temp[1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: As lockdown is going on so no is allowed to go outside , so Chef has come with an innovative idea for food home delivery using drone. But there is an issue with it , the drone can move forward or backward a fix number of steps $x$ . All the houses and chef restaurant are all in a straight line . Homes which need delivery are located at $H[i]$ and chef is located at $y$ coordinate . If Drone is at a location $R$, then it can move to $R-x$ or $R+x$ . Help chef find maximum value of $x$ to complete all the deliveries as he is busy managing the orders. -----Input:----- - First line will contain $n$ and $R$, number of houses that need delivery and the correct coordinate of chef (Drone). - Second line contains $n$ integers , the coordinate of all homes that need delivery. -----Output:----- - The maximum value of $x$ , so that drone delivers to all houses. -----Constraints----- - $1 \leq n \leq 1000$ - $1 \leq R \leq 10^9$ - $1 \leq hi \leq 10^9$ - $1 \leq x \leq 10^9$ -----Sample Input:----- 3 1 3 5 11 -----Sample Output:----- 2 -----EXPLANATION:----- Chef's drone is at 1 initially and he needs to visit 3,5,11 , so optimal solution will be (maximum value of x ) equal to 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 import math try: n,d=map( int,input().split() ) a=list(map(int,input().split())) a.sort() z=abs(a[0]-d) for j in range(n): x=abs(a[j]-d) z=math.gcd(x,z) print(z) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sebi goes to school daily with his father. They cross a big highway in the car to reach to the school. Sebi sits in front seat beside his father at driving seat. To kill boredom, they play a game of guessing speed of other cars on the highway. Sebi makes a guess of other car's speed being SG kph, his father FG kph. The highway is usually empty, so the drivers use cruise control, i.e. vehicles run at a constant speed. There are markers on the highway at a gap of 50 meters. Both father-son duo wants to check the accuracy of their guesses. For that, they start a timer at the instant at which their car and the other car (which speed they are guessing) are parallel to each other (they need not to be against some marker, they can be in between the markers too). After some T seconds, they observe that both the cars are next to some markers and the number of markers in between the markers of their car and the other car is D - 1 (excluding the markers next to both the cars). Also, they can observe these markers easily because the other car is faster than their. Speed of Sebi's father's car is S. Using this information, one can find the speed of the other car accurately. An example situation when Sebi's father starts the timer. Notice that both the car's are parallel to each other. Example situation after T seconds. The cars are next to the markers. Here the value of D is 1. The green car is Sebi's and the other car is of blue color. Sebi's a child, he does not know how to find the check whose guess is close to the real speed of the car. He does not trust his father as he thinks that he might cheat. Can you help to resolve this issue between them by telling whose guess is closer. If Sebi's guess is better, output "SEBI". If his father's guess is better, output "FATHER". If both the guess are equally close, then output "DRAW". -----Input----- The first line of the input contains an integer T denoting the number of test cases. Each of the next T lines contain five space separated integers S, SG, FG, D, T corresponding to the Sebi's car speed, Sebi's guess, his father's guess, D as defined in the statement and the time at which both the cars at against the markers (in seconds), respectively. -----Output----- Output description. For each test case, output a single line containing "SEBI", "FATHER" or "DRAW" (without quotes) denoting whose guess is better. -----Constraints----- - 1 ≤ T ≤ 10000 - 0 ≤ S ≤ 130 - 0 ≤ SG, FG ≤ 300 - 1 ≤ D ≤ 30 - 1 ≤ T ≤ 300 - The other car speed doesn't exceed 300 kph. -----Example----- Input: 2 100 180 200 20 60 130 131 132 1 72 Output: SEBI FATHER -----Explanation----- Example case 1. There are total 20 - 1 = 19 markers in between the Sebi's car and the other car. So, the distance between those cars at time T is 20 * 50 = 1000 meters = 1 km. As T = 60 seconds, i.e. 1 minutes. So, the other car goes 1 km more than Sebi's car in 1 minute. So, the other car will go 60 km more than Sebi's car in 1 hour. So, its speed is 60 kmph more than Sebi's car, i.e. 160 kmph. Sebi had made a guess of 180 kmph, while his father of 200 kmph. Other car's real speed is 160 kmph. So, Sebi's guess is better than his father. Hence he wins the game. Example case 2. The situation of this example is depicted in the image provided in the statement. You can find the speed of other car and see that Father's guess is more accurate. 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 n=int(input()) for i in range(n): S, SG, FG, D, T = map(int, input().split()) speed = (D*180)/T + S if abs(SG-speed) == abs(FG-speed): print('DRAW') elif abs(SG-speed) > abs(FG-speed): print('FATHER') else: print('SEBI') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In Chefland, types of ingredients are represented by integers and recipes are represented by sequences of ingredients that are used when cooking. One day, Chef found a recipe represented by a sequence $A_1, A_2, \ldots, A_N$ at his front door and he is wondering if this recipe was prepared by him. Chef is a very picky person. He uses one ingredient jar for each type of ingredient and when he stops using a jar, he does not want to use it again later while preparing the same recipe, so ingredients of each type (which is used in his recipe) always appear as a contiguous subsequence. Chef is innovative, too, so he makes sure that in each of his recipes, the quantity of each ingredient (i.e. the number of occurrences of this type of ingredient) is unique ― distinct from the quantities of all other ingredients. Determine whether Chef could have prepared the given recipe. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing the string "YES" if the recipe could have been prepared by Chef or "NO" otherwise (without quotes). -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 10^3$ - $1 \le A_i \le 10^3$ for each valid $i$ -----Example Input----- 3 6 1 1 4 2 2 2 8 1 1 4 3 4 7 7 7 8 1 7 7 3 3 4 4 4 -----Example Output----- YES NO NO -----Explanation----- Example case 1: For each ingredient type, its ingredient jar is used only once and the quantities of all ingredients are pairwise distinct. Hence, this recipe could have been prepared by Chef. Example case 2: The jar of ingredient $4$ is used twice in the recipe, so it was not prepared by Chef. 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()) arr=list(map(int,input().split())) d={} s=set() flag=0 for i in range(n): if arr[i] in list(d.keys()): d[arr[i]]+=1 else: d[arr[i]]=1 curr_ele=arr[i] if (curr_ele in s) and arr[i-1]!=arr[i]: flag=1 break else: s.add(arr[i]) c=list(d.values()) if len(c)!=len(set(c)): flag=1 if flag==1: print("NO") else: print("YES") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The round carousel consists of $n$ figures of animals. Figures are numbered from $1$ to $n$ in order of the carousel moving. Thus, after the $n$-th figure the figure with the number $1$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $i$-th figure equals $t_i$. [Image] The example of the carousel for $n=9$ and $t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color. Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $k$ distinct colors, then the colors of figures should be denoted with integers from $1$ to $k$. -----Input----- The input contains one or more test cases. The first line contains one integer $q$ ($1 \le q \le 10^4$) — the number of test cases in the test. Then $q$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $n$ ($3 \le n \le 2 \cdot 10^5$) — the number of figures in the carousel. Figures are numbered from $1$ to $n$ in order of carousel moving. Assume that after the $n$-th figure the figure $1$ goes. The second line of the test case contains $n$ integers $t_1, t_2, \dots, t_n$ ($1 \le t_i \le 2 \cdot 10^5$), where $t_i$ is the type of the animal of the $i$-th figure. The sum of $n$ over all test cases does not exceed $2\cdot10^5$. -----Output----- Print $q$ answers, for each test case print two lines. In the first line print one integer $k$ — the minimum possible number of distinct colors of figures. In the second line print $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le k$), where $c_i$ is the color of the $i$-th figure. If there are several answers, you can print any. -----Example----- Input 4 5 1 2 1 2 2 6 1 2 2 1 2 2 5 1 2 1 2 3 3 10 10 10 Output 2 1 2 1 2 2 2 2 1 2 1 2 1 3 2 3 2 3 1 1 1 1 1 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 = lambda: sys.stdin.readline().rstrip() T = int(input()) for _ in range(T): N = int(input()) A = [int(a) for a in input().split()] if max(A) == min(A): print(1) print(*([1] * N)) elif N % 2 == 0: print(2) print(*([1, 2] * (N // 2))) else: for i in range(N): if A[i-1] == A[i]: print(2) print(*(([1, 2] * N)[:i][::-1] + ([1, 2] * N)[:N-i])) break else: print(3) print(*([3] + [1, 2] * (N // 2))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Little Elephant from the Zoo of Lviv has an array A that consists of N positive integers. Let A[i] be the i-th number in this array (i = 1, 2, ..., N). Find the minimal number x > 1 such that x is a divisor of all integers from array A. More formally, this x should satisfy the following relations: A[1] mod x = 0, A[2] mod x = 0, ..., A[N] mod x = 0, where mod stands for the modulo operation. For example, 8 mod 3 = 2, 2 mod 2 = 0, 100 mod 5 = 0 and so on. If such number does not exist, output -1. -----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 the array A for the corresponding test case. The second 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. -----Constraints----- 1 ≤ T ≤ 100000 1 ≤ N ≤ 100000 The sum of values of N in each test file does not exceed 100000 1 ≤ A[i] ≤ 100000 -----Example----- Input: 2 3 2 4 8 3 4 7 5 Output: 2 -1 -----Explanation----- Case 1. Clearly 2 is a divisor of each of the numbers 2, 4 and 8. Since 2 is the least number greater than 1 then it is the answer. Case 2. Let's perform check for several first values of x. x4 mod x7 mod x5 mod x20113112403154206415740584759475 As we see each number up to 9 does not divide all of the numbers in the array. Clearly all larger numbers also will fail to do this. So there is no such number x > 1 and 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 from math import sqrt,gcd for _ in range(int(input())): n=int(input()) ar=[int(x) for x in input().split()] g=ar[0] for i in range(1,n): g=gcd(g,ar[i]) f=g for i in range(2,int(sqrt(g))+1): if g%i==0: f=i break if g!=1: print(f) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: ZCO is approaching, and you want to be well prepared! There are $N$ topics to cover and the $i^{th}$ topic takes $H_i$ hours to prepare (where $1 \le i \le N$). You have only $M$ days left to prepare, and you want to utilise this time wisely. You know that you can't spend more than $S$ hours in a day preparing, as you get tired after that. You don't want to study more than one topic in a day, and also, don't want to spend more than two days on any topic, as you feel that this is inefficient. Given these constraints, can you find the maximum number of topics you can prepare, if you choose the topics wisely? -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - The first line of each test case contains three space-separated integers: $N$, $M$ and $S$, denoting the number of topics, the number of days remaining and the number of hours you can study in a day. - The second line of each test case contains $N$ space-separated integers $H_i$, denoting the number of hours needed to prepare for the $i^{th}$ topic. -----Output:----- For each testcase, output in a single line: the maximum number of topics you can prepare. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 10^5$ - $1 \leq M \leq 10^5$ - $1 \leq S \leq 16$ - $1 \leq H_i \leq 50$ -----Subtasks----- - 30 points : Every topic takes the same number of hours to prepare (i.e. all $H_i$ are equal). - 70 points : Original constraints. -----Sample Input:----- 2 5 4 10 10 24 30 19 40 5 4 16 7 16 35 10 15 -----Sample Output:----- 2 4 -----Explanation:----- Testcase 1: You can choose topics $1$ and $4$. Topic $1$ will consume a single day , while topic $4$ will consume two days. Thus, you'll be able to prepare these two topics within the 4 remaining days. But you can check that you cannot do any better. Testcase 2: You can choose topics $1$, $2$, $4$, and $5$. Each of them will consume one day each. Thus you'll be able to cover $4$ topics. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math T=int(input()) for i in range(T): N,M,S=input().split() N=int(N) M=int(M) S=int(S) ls=list(map(int,input().split())) maxx=max(ls) if S<17 and maxx<=50: ls.sort() total_sum = M * S count = 0 sum = 0 for i in ls: if i / S > 2: continue else: sum = sum + math.ceil(i / S) * S if sum <= total_sum: count = count + 1 print(count) # cook your dish here ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have a large electronic screen which can display up to $998244353$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $7$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $10$ decimal digits: [Image] As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $1$, you have to turn on $2$ segments of the screen, and if you want to display $8$, all $7$ segments of some place to display a digit should be turned on. You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $n$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $n$ segments. Your program should be able to process $t$ different test cases. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then the test cases follow, each of them is represented by a separate line containing one integer $n$ ($2 \le n \le 10^5$) — the maximum number of segments that can be turned on in the corresponding testcase. It is guaranteed that the sum of $n$ over all test cases in the input does not exceed $10^5$. -----Output----- For each test case, print the greatest integer that can be displayed by turning on no more than $n$ segments of the screen. Note that the answer may not fit in the standard $32$-bit or $64$-bit integral data type. -----Example----- Input 2 3 4 Output 7 11 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 = int(input()) if(n%2): print("7"+"1"*((n-3)//2)) else: print("1"*(n//2)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Polo, the Penguin, likes numbers. He says that the goodness of a number is itself multiplied by the number of digits in it's decimal representation. For example, the goodness of the integer 474 is 474*3 = 1422. Help him to count the sum of goodness of all integers from L to R, inclusive. Since the answer can be too large, output it modulo 1,000,000,007 (10^9+7). -----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 only line of each test case contains the pair of integers L and R, separated by a single space. -----Output----- For each test case, output a single line containing the answer to the corresponding test case. -----Constraints----- - 1 ≤ T ≤ 1,000 - 1 ≤ L ≤ R ≤ 1,000,000,000 (10^9) -----Example----- Input: 1 9 12 Output: 75 -----Explanation----- Example case 1. The answer is 9*1 + 10*2 + 11*2 + 12*2 = 75. 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 from math import sqrt,ceil,log10 def get_sum(a,b,digits): sum=((b+a)*(b-a+1))//2 return sum*digits def solve(): mod=10**9+7 thehighlimiter={i: 10 ** i - 1 for i in range(12)} thelowlimiter={i: 10**i for i in range(12)} for _ in range(int(input())): l,r=map(int, stdin.readline().strip().split()) low=len(str(l)) high=len(str(r)) ans=0 if low==high: ans=get_sum(l,r,low) else: ans+=get_sum(l,((10**low)-1),low) ans+=get_sum((10**(high-1)),r,high) for i in range(low+1,high): ans+=get_sum(10**(i-1),(10**i)-1,i) print(ans%mod) def __starting_point(): solve() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Lucy had recently learned the game, called Natural Numbers. The rules of the game are really simple. There are N players. At the same time, every player says one natural number. Let's call the number said by the i-th player Ai. The person with the smallest unique number (that is, the smallest number that was not said by anybody else) wins. Sometimes, there is a case when there are no unique numbers at all. Then the game is obviously a draw, so nobody wins it. Sometimes, it's hard to determine the winner, especially, when the number of players is enormous. So in this problem, your assignment will be: given the names of the players and the numbers every of them have said. Please, tell the name of the winner, or determine that nobody wins. -----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 every test case consists of a single integer N - the number of players. Then, N lines will follow. Each of these N lines will consist of the player's name and the number Ai said by her, separated by a single space. -----Output----- For each test case, output a single line containing an answer to the corresponding test case - the name of the winner, or a string "Nobody wins.", if nobody wins the game. -----Example----- Input: 2 5 Kouta 1 Yuka 1 Mayu 3 Lucy 2 Nana 5 2 Lucy 2 Nana 2 Output: Lucy Nobody wins. -----Scoring----- Subtask 1 (17 points): T = 10000, 1 <= N <= 10, 1 <= Ai <= 10 Subtask 2 (19 points): T = 10000, 1 <= N <= 10, 1 <= Ai <= 2*109 Subtask 3 (30 points): T = 100, 1 <= N <= 1000, 1<= Ai <= 2*109 Subtask 4 (34 points): T = 10, 1 <= N <= 10000, 1 <= Ai <= 2*109 You can safely assume that in all the test cases the length of any name will not exceed five letters. All the players' names are unique. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python try: t = int(input()) while t: t -= 1 n = int(input()) arr = [] obj = {} for i in range(n): x,y = input().split() y = int(y) arr.append([x, y]) if y in obj: obj[y].append(x) else: obj[y] = [x] arr.sort(key = lambda i: i[1], reverse = True) while len(arr) and len(obj[arr[-1][1]]) > 1: arr.pop() if len(arr) == 0: print('Nobody wins.') else: print(arr.pop()[0]) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. -----Input----- The first line contains an integer n (1 ≤ n ≤ 5·10^5) — the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant x_{i} 0 ≤ x_{i} ≤ 1023. -----Output----- Output an integer k (0 ≤ k ≤ 5) — the length of your program. Next k lines must contain commands in the same format as in the input. -----Examples----- Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 & 1 & 3 & 5 Output 1 & 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 -----Note----- You can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from operator import __or__, __and__, __xor__ from sys import stdin, stdout n, b, c = int(stdin.readline()), 0, 1023 m = {'|': __or__, '&': __and__, '^': __xor__} for i in range(n): t, v = [i for i in stdin.readline().split()] b = m[t](b, int(v)) c = m[t](c, int(v)) x, o, a = 0, 0, 1023 for i in range(10): if ((b >> i) & 1) and ((c >> i) & 1): o |= 1 << i elif not ((b >> i) & 1) and not ((c >> i) & 1): a -= 1 << i elif ((b >> i) & 1) and not ((c >> i) & 1): x |= 1 << i stdout.write('3\n| ' + str(o) + '\n^ ' + str(x) + '\n& ' + str(a)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef’s girlfriend is angry with him because he forgot her birthday. Chef decided to please her by gifting her a Love Graph. Chef has $N$ vertices: $V_1, V_2, \dots, V_N$. Love Graph is an undirected multigraph with no self-loops and can be constructed by performing the following operations:- - Choose an integer $i$ ($1 \leq i \leq N$) - Choose another integer $j \space \space \{ (i \neq j) \text{ and } (1 \leq j \leq N) \}$ - Make an edge between $V_i$ and $V_j$ - Set $i = j$ - Repeat steps $2, 3$ and $4$ in order $M-1$ more times. Find the number of ways in which Chef can construct a Love Graph. Since the answer can be very 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 line of each test case contains two space-separated integers $N$ and $M$. -----Output----- For each test case, print a single line containing one integer — the number of ways in which Chef can construct a Love Graph modulo $10^9+7$. -----Constraints----- - $1 \leq T \leq 10^5$ - $2 \leq N \leq 10^9$ - $1 \leq M \leq 10^{18}$ -----Subtasks----- - 30 points: - $1 \leq T \leq 100$ - $2 \leq N \leq 10$ - $1 \leq M \leq 10$ - 70 points: original constraints -----Sample Input----- 1 2 1 -----Sample Output----- 2 -----Explanation----- There are two ways of constructing Love Graph. In first way, we pick Vertex 1 and then join with Vertex 2. In second way, we pick Vertex 2 and then join with Vertex 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def fastpow(base, power): result = 1 while power > 0: if power % 2 == 0: power = power // 2 base = base * base else: power = power - 1 result = result * base power = power // 2 base = base * base return result t=int(input()) for i in range(t): a=list(map(int,input().split())) n,r=a[0],a[1] w=(n*(fastpow(n-1,r)))%((10**9)+7) print(w) ```
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$. You should select a (not necessarily contiguous) subsequence of $A$ and reverse it. In other words, if you select a subsequence $A_{i_1}, A_{i_2}, \ldots, A_{i_K}$ ($1 \le i_1 < \ldots < i_K \le N$), then for each valid $j$, the $i_j$-th element of the resulting sequence is equal to the $i_{K+1-j}$-th element of the original sequence; all other elements are the same as in the original sequence. In the resulting sequence, you want to calculate the maximum sum of a contiguous subsequence (possibly an empty sequence, with sum $0$). Find its maximum possible value and a subsequence which you should select in order to obtain this maximum value. If there are multiple solutions, you may find any one of them. -----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 two lines. - The first of these lines should contain a single integer ― the maximum possible sum of a contiguous subsequence. - The second line should contain an integer $K$ followed by a space and $K$ space-separated integers $i_1, i_2, \ldots, i_K$. -----Constraints----- - $1 \le T \le 2,000$ - $2 \le N \le 10^5$ - $|A_i| \le 10^9$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $2 \cdot 10^6$ -----Example Input----- 2 5 -4 2 -4 3 -5 3 -3 -2 -1 -----Example Output----- 5 2 2 3 0 0 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 = int(input()) a = list(map(int,input().split())) ans = 0 count = 0 for i in a: if i>0: ans+=i count+=1 res = [] for i in range(count): if a[i]<=0: res.append(i+1) for i in range(count,n): if a[i]>0: res.append(i+1) print(ans) print(len(res),*res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vasya has ordered a pizza delivery. The pizza can be considered a perfect circle. There were $n$ premade cuts in the pizza when it was delivered. Each cut is a straight segment connecting the center of the pizza with its boundary. Let $O$ be the center of the pizza, $P_i$ be the endpoint of the $i$-th cut lying on the boundary, and $R$ be the point of the boundary straight to the right of $O$. Then the counterclockwise-measured angle $\angle ROP_i$ is equal to $a_i$ degrees, where $a_i$ is an integer between $0$ and $359$. Note that angles between $0$ and $180$ angles correspond to $P_i$ in the top half of the pizza, while angles between $180$ and $360$ angles correspond to the bottom half. Vasya may cut his pizza a few more times, and the new cuts still have to be straight segments starting at the center. He wants to make the pizza separated into several equal slices, with each slice being a circular sector with no cuts inside of it. How many new cuts Vasya will have to make? -----Input:----- The first line of input contains $T$ , i.e number of test cases per file. The first line of each test case contains a single integer $n-$ the numbers of premade cuts ($2 \leq n \leq 360$). The second lines contains $n$ integers $a_1, \ldots, a_n-$ angles of the cuts $1, \ldots, n$ respectively ($0 \leq a_1 < \ldots, a_{n - 1} < 360$). -----Output:----- Print a single integer$-$ the smallest number of additional cuts Vasya has to make so that the pizza is divided into several equal slices. -----Constraints----- - $1 \leq T \leq 36$ - $2 \leq n \leq 360$ - $0 \leq a_1 < \ldots, a_{n - 1} < 360$ -----Sample Input:----- 3 4 0 90 180 270 2 90 210 2 0 1 -----Sample Output:----- 0 1 358 -----EXPLANATION:----- In the first sample the pizza is already cut into four equal slices. In the second sample the pizza will be cut into three equal slices after making one extra cut at $330$ degrees. In the third sample Vasya will have to cut his pizza into $360$ pieces of $1$ degree angle each. 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 a == 0: return b return(gcd(b % a, a)) t = int(input()) for T in range(t): n = int(input()) l = [int(x) for x in input().split()] ang = [] for i in range(1, n): ang.append(l[i] - l[i - 1]) ang.append(360 - (l[-1] - l[0])) ang.sort() if ang == ang[::-1]: print(0) continue g = ang[0] for i in range(1, n): g = gcd(g, ang[i]) total = 360 // g - len(ang) print(total) ## print(g, ang, total) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers. There are $k$ boxes numbered from $1$ to $k$. The $i$-th box contains $n_i$ integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, $k$ integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box. Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be? -----Input----- The first line contains a single integer $k$ ($1 \leq k \leq 15$), the number of boxes. The $i$-th of the next $k$ lines first contains a single integer $n_i$ ($1 \leq n_i \leq 5\,000$), the number of integers in box $i$. Then the same line contains $n_i$ integers $a_{i,1}, \ldots, a_{i,n_i}$ ($|a_{i,j}| \leq 10^9$), the integers in the $i$-th box. It is guaranteed that all $a_{i,j}$ are distinct. -----Output----- If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output $k$ lines. The $i$-th of these lines should contain two integers $c_i$ and $p_i$. This means that Ujan should pick the integer $c_i$ from the $i$-th box and place it in the $p_i$-th box afterwards. If there are multiple solutions, output any of those. You can print each letter in any case (upper or lower). -----Examples----- Input 4 3 1 7 4 2 3 2 2 8 5 1 10 Output Yes 7 2 2 3 5 1 10 4 Input 2 2 3 -2 2 -1 5 Output No Input 2 2 -10 10 2 0 -20 Output Yes -10 2 -20 1 -----Note----- In the first sample, Ujan can put the number $7$ in the $2$nd box, the number $2$ in the $3$rd box, the number $5$ in the $1$st box and keep the number $10$ in the same $4$th box. Then the boxes will contain numbers $\{1,5,4\}$, $\{3, 7\}$, $\{8,2\}$ and $\{10\}$. The sum in each box then is equal to $10$. In the second sample, it is not possible to pick and redistribute the numbers in the required way. In the third sample, one can swap the numbers $-20$ and $-10$, making the sum in each box equal to $-10$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): k = int(input()) n = [] a = [] for i in range(k): line = [int(x) for x in input().split()] ni = line[0] ai = [] n.append(ni) a.append(ai) for j in range(ni): ai.append(line[1 + j]) answer, c, p = solve(k, n, a) if answer: print("Yes") for i in range(k): print(c[i], p[i] + 1) else: print("No") def solve(k, n, a): asum, sums = calc_sums(k, n, a) if asum % k != 0: return False, None, None tsum = asum / k num_map = build_num_map(k, n, a) masks = [None]*(1 << k) simple = [False]*(1 << k) for i in range(k): for j in range(n[i]): found, mask, path = find_cycle(i, j, i, j, k, n, a, sums, tsum, num_map, 0, dict()) if found: simple[mask] = True masks[mask] = path for i in range(1 << k): if not simple[i]: continue mask = i zeroes_count = 0 for u in range(k): if (1 << u) > mask: break if (mask & (1 << u)) == 0: zeroes_count += 1 for mask_mask in range(1 << zeroes_count): mask_child = 0 c = 0 for u in range(k): if (1 << u) > mask: break if (mask & (1 << u)) == 0: if (mask_mask & (1 << c)) != 0: mask_child = mask_child | (1 << u) c += 1 if masks[mask_child] and not masks[mask_child | mask]: masks[mask_child | mask] = {**masks[mask_child], **masks[mask]} if (mask_child | mask) == ((1 << k) - 1): c = [-1] * k p = [-1] * k d = masks[(1 << k) - 1] for key, val in list(d.items()): c[key] = val[0] p[key] = val[1] return True, c, p if masks[(1 << k) - 1]: c = [-1] * k p = [-1] * k d = masks[(1 << k) - 1] for key, val in list(d.items()): c[key] = val[0] p[key] = val[1] return True, c, p return False, None, None def build_num_map(k, n, a): result = dict() for i in range(k): for j in range(n[i]): result[a[i][j]] = (i, j) return result def find_cycle(i_origin, j_origin, i, j, k, n, a, sums, tsum, num_map, mask, path): if (mask & (1 << i)) != 0: if i == i_origin and j == j_origin: return True, mask, path else: return False, None, None mask = mask | (1 << i) a_needed = tsum - (sums[i] - a[i][j]) if a_needed not in num_map: return False, None, None i_next, j_next = num_map[a_needed] path[i_next] = (a[i_next][j_next], i) return find_cycle(i_origin, j_origin, i_next, j_next, k, n, a, sums, tsum, num_map, mask, path) def calc_sums(k, n, a): sums = [0] * k for i in range(k): for j in range(n[i]): sums[i] = sums[i] + a[i][j] asum = 0 for i in range(k): asum = asum + sums[i] return asum, sums def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Someone gave Alyona an array containing n positive integers a_1, a_2, ..., a_{n}. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all. Formally, after applying some operations Alyona will get an array of n positive integers b_1, b_2, ..., b_{n} such that 1 ≤ b_{i} ≤ a_{i} for every 1 ≤ i ≤ n. Your task is to determine the maximum possible value of mex of this array. Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in the Alyona's array. The second line of the input contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the elements of the array. -----Output----- Print one positive integer — the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. -----Examples----- Input 5 1 3 3 3 6 Output 5 Input 2 2 1 Output 3 -----Note----- In the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5. To reach the answer to the second sample case one must not decrease any of the array elements. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python x=int(input()) l=list(map(int, input().split(' '))) l.sort() a=1 for i in l: if i>=a: a+=1 print(a) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sereja has a string A consisting of n lower case English letters. Sereja calls two strings X and Y each of length n similar if they can be made equal by applying the following operation at most once in each of them. - Chose any two position i, j in the string (i can be equal to j too). Swap the characters at position i with character at position j. For example strings "abcd" and "acbd" are similar, strings "ab" and "ab" are similar, but strings "abcde" and "bcdea" are not similar. Note that strings "abc" and "cab" are also similar, as you can swap 'a' and 'c' in the first string to get "cba" and 'a' and 'b' in the second string to get "cba". Now Sereja is interested in finding number of ordered pairs of non similar strings X and Y such that they can be constructed from a given string A by permutation of its characters. As answer could be large, please output your answer modulo (109 + 7). Note A string s (of size n) is said to be constructed from string t (also of size n) by permutation of its characters if there exists a permutation P (of length n), such that s[i] = t[P[i]] for each i from 1 to n. -----Input----- - First line contain integer T - number of test cases. - For each of the next T lines: - Each line contains a string A as defined in the problem. -----Output----- For each test case, output answer modulo 1000000007 (109 + 7) in separate line. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ n ≤ 10^5 -----Constraints----- - Subtask #1: 1 ≤ n ≤ 10 (25 points) - Subtask #2: 1 ≤ n ≤ 100 (25 points) - Subtask #3: 1 ≤ n ≤ 1000 (25 points) - Subtask #4: original constraints (25 points) -----Example----- Input: 2 z abcd Output: 0 144 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 egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modin(a, m): g, x, y = egcd(a, m) return x % m # def gcdexten(a,b,x,y): # if a == 0: # x = 0 # y = 1 # return b # x1 = y1 = 0 # gcd = gcdexten(b%a,a,x1,y1) # x = y1 - (b/a) * x1 # y = x1 # return gcd # def modin(a): # m = 10**9 + 7 # x = y = 0 # g = gcdexten(a,m,x,y) # res = (x%m + m)%m # return res # void modInverse(int a, int m) # { # int x, y; # int g = gcdExtended(a, m, &x, &y); # if (g != 1) # cout << "Inverse doesn't exist"; # else # { # // m is added to handle negative x # int res = (x%m + m) % m; # cout << "Modular multiplicative inverse is " << res; # } # } # int gcdExtended(int a, int b, int *x, int *y) # { # // Base Case # if (a == 0) # { # *x = 0, *y = 1; # return b; # } # int x1, y1; // To store results of recursive call # int gcd = gcdExtended(b%a, a, &x1, &y1); # // Update x and y using results of recursive # // call # *x = y1 - (b/a) * x1; # *y = x1; # return gcd; # } def combi(a,b): mod = 10**9 + 7 if a < b: return 0 if a == 1: return 1 if b < a/2: b = a - b temp = 1 for i in range(b + 1,a + 1): temp = (temp * i%mod)%mod denom = modin(math.factorial(a-b),mod) # print denom return (temp%mod * denom%mod)%mod for _ in range(eval(input())): mod = 10**9 + 7 string1 = input() n = len(string1) dict1 = {} count = 0 alpha = set() for ele in string1: if ele in dict1: dict1[ele] += 1 else: dict1[ele] = 1 alpha.add(ele) count += 1 count_list = [] total = 1 rem = n for ele in alpha: total = (total % mod) * (combi(rem,dict1[ele]) % mod)%mod rem -= dict1[ele] count_list.append(dict1[ele]) sum_list = [n - count_list[0]] for i in range(1,count): sum_list.append(sum_list[i - 1] - count_list[i]) sub_2 = 0 sub = 0 for i in count_list: sub_2 += (n - i) * i sub_2 /= 2 # print sub_2 sub_3 = 0 for i in range(count): for j in range(i + 1,count): sub_3 += count_list[i] * count_list[j] * sum_list[j] sub_3 = 2 * sub_3 sub_4_4 = 0 for i in range(count): for j in range(i + 1,count): for k in range(j + 1,count): sub_4_4 += count_list[i] * count_list[j] * count_list[k] * sum_list[k] sub_4_4 *= 3 sub_4_2 = 0 for i in range(count): for j in range(i + 1,count): sub_4_2 += (count_list[i] * (count_list[i] - 1) * count_list[j] * (count_list[j] - 1))/4 sub_4_3 = 0 for i in range(count): temp = 0 for j in range(count): if j != i: temp += count_list[j] * (n - count_list[i] - count_list[j]) temp /= 2 sub_4_3 += ((count_list[i] * (count_list[i] - 1)) * temp)/2 # print sub_4_3 sub_4_3 *= 2 # sub_4 = ((sub_4_2%mod + sub_4_3%mod) + sub_4_4%mod)%mod # sub_tot = ((sub_2%mod + sub_3%mod)%mod + sub_4%mod)%mod sub_4 = sub_4_3 + sub_4_4 + sub_4_2 sub_tot = sub_2 + sub_3 + sub_4 # print((total * (total - 1)) - (total * sub_tot%mod))%mod # print ((total)* (total - 1 - (((sub_3 + sub_2)%mod + (sub_4_4 +sub_4_3)%mod)%mod + sub_4_2%mod)))% mod print((total * (total - (sub_tot + 1)%mod)%mod)%mod) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: "Don't Drink and Drive, but when you do, Better Call Saul." Once Jesse and Walter were fighting over extra cash, and Saul decided to settle it with a game of stone piles whose winner gets the extra money. The game is described as follows : There are N$N$ piles of stones with A$A$1$1$,$,$ A$A$2$2$,$,$ ...$...$ A$A$N$N$ stones in each pile. Jesse and Walter move alternately, and in one move, they remove one pile entirely. After a total of X$X$ moves, if the Sum of all the remaining piles is odd, Walter wins the game and gets the extra cash, else Jesse is the winner. Walter moves first. Determine the winner of the game if both of them play optimally. -----Input:----- - The first line will contain T$T$, number of testcases. T$T$ testcases follow : - The first line of each testcase contains two space-separated integers N,X$N, X$. - The second line of each testcase contains N$N$ space-separated integers A$A$1$1$,$,$ A$A$2$2$,$,$ ...,$...,$A$A$N$N$. -----Output:----- For each test case, print a single line containing the string "Jesse" (without quotes), if Jesse wins the game or "Walter" (without quotes) if Walter wins. -----Constraints----- - 1≤T≤104$1 \leq T \leq 10^4$ - 2≤N≤105$2 \leq N \leq 10^5$ - 1≤X≤N−1$1 \leq X \leq N-1$ - 1≤A$1 \leq A$i$i$ ≤100$ \leq 100$ - The sum of N$N$ over all test cases does not exceed 106$10^6$ -----Sample Input:----- 2 5 3 4 4 4 3 4 7 4 3 3 1 1 1 2 4 -----Sample Output:----- Jesse Walter -----EXPLANATION:----- - For Test Case 1 : Playing optimally, Walter removes 4. Jesse removes 3 and then Walter removes 4. Jesse wins as 4+4=8$4 + 4 = 8$ is even. - For Test Case 2 : Playing optimally, Walter removes 4, Jesse removes 3, Walter removes 2 and Jesse removes 1. Walter wins as 3+3+1=7$3 + 3 + 1 = 7$ is odd. 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): k,x=map(int,input().split()) l=list(map(int,input().split())) f,e,o=0,0,0 for i in l: if(i%2==0): e+=1 else: o+=1 if(o<=x//2): f=1 elif(e<=x//2): if((k-x)%2!=0): f=0 else: f=1 else: if(x%2==0): f=1 else: f=0 if(f==1): print('Jesse') else: print('Walter') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Tara was completing an Algorithms assignment and got stuck on a question. She thought of who can help her, and got reminded of Kabir who has good problem solving skills. The question is: Given N$N$ the number of elements in the sequence A1$A_1$,A2$A_2$ … An$A_n$. Find out the prime factor which occurred maximum number of times among the largest prime factor corresponding to each element. if there are more than one such prime factors print the largest one. You are friends with Kabir, help him to solve the problem for Tara. -----Input:----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T test cases follows. - First line of each test case contains N$N$, the number of elements in the sequence. - Second line contains N space separated elements A1$A_1$,A2$A_2$ … An$A_n$. -----Output:----- - For each test case, print a single line, the number which occurs maximum number of times from the largest prime factor corresponding to each element. -----Constraints----- - 1≤T≤10$1 \leq T \leq 10$ - 1≤N≤105$1 \leq N \leq 10^5$ - 2≤A[i]≤105$2 \leq A[i] \leq 10^5$ -----Sample Input:----- 1 7 3 2 15 6 8 5 10 -----Sample Output:----- 5 -----EXPLANATION:----- The largest prime factors of numbers are: 3 2 5 3 2 5 5 , of which 5 is most frequent. 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 store=[0]*(10**5+1) def sieve(): for i in range(2,10**5+1): if(store[i]==0): store[i]=1 for j in range(i,10**5+1,i): store[j]=i sieve() # print(store) for _ in range(int(input())): n=int(input()) li=[int(x) for x in input().split()] dp=[0]*(10**5+1) for i in li: dp[store[i]]+=1 max_re=0 res=0 for i in li: if(dp[store[i]]==max_re): if(store[i]>res): res=store[i] elif(dp[store[i]]>max_re): max_re=dp[store[i]] res=store[i] print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. -----Input----- The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: Binary number of exactly m bits. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. -----Output----- In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers. -----Examples----- Input 3 3 a := 101 b := 011 c := ? XOR b Output 011 100 Input 5 1 a := 1 bb := 0 cx := ? OR a d := ? XOR ? e := d AND bb Output 0 0 -----Note----- In the first sample if Peter chooses a number 011_2, then a = 101_2, b = 011_2, c = 000_2, the sum of their values is 8. If he chooses the number 100_2, then a = 101_2, b = 011_2, c = 111_2, the sum of their values is 15. For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys def calc(b0, b1, q): if q == 0: return b0 ^ b1 if q == 1: return b0 | b1 if q == 2: return b0 & b1 n, m = list(map(int,sys.stdin.readline().split())) arr1 = {} opt = ['XOR', 'OR', 'AND'] arr2 = [] for j in range(n): a, b = list(map(str,sys.stdin.readline().split(" := "))) b = b.split() if len(b) == 1: s = b[0] arr1[a] = s else: c = b[0] d = b[2] q = opt.index(b[1]) arr2.append((a, c, d, q)) mins = '' maxs = '' d0 = {'?':0} d1 = {'?':1} for i in range(m): for a, b in list(arr1.items()): d0[a] = int(b[i]) d1[a] = int(b[i]) s0 = 0 s1 = 0 for a, c, d, q in arr2: b00 = d0[c] b01 = d0[d] b10 = d1[c] b11 = d1[d] c0 = calc(b00, b01, q) c1 = calc(b10, b11, q) s0 += (1 if c0 else 0) s1 += (1 if c1 else 0) d0[a] = c0 d1[a] = c1 if s1 < s0: mins += "1" else: mins += "0" if s1 > s0: maxs += "1" else: maxs += "0" sys.stdout.write("{0}\n{1}".format(mins,maxs)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher. Neko has two integers $a$ and $b$. His goal is to find a non-negative integer $k$ such that the least common multiple of $a+k$ and $b+k$ is the smallest possible. If there are multiple optimal integers $k$, he needs to choose the smallest one. Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it? -----Input----- The only line contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$). -----Output----- Print the smallest non-negative integer $k$ ($k \ge 0$) such that the lowest common multiple of $a+k$ and $b+k$ is the smallest possible. If there are many possible integers $k$ giving the same value of the least common multiple, print the smallest one. -----Examples----- Input 6 10 Output 2 Input 21 31 Output 9 Input 5 10 Output 0 -----Note----- In the first test, one should choose $k = 2$, as the least common multiple of $6 + 2$ and $10 + 2$ is $24$, which is the smallest least common multiple possible. 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 gcd a, b = list(map(int, input().split())) if b < a: a, b = b, a if a == b: print(0) return c = b - a i = 1 ans = a * b // gcd(a, b) def get(x): A = (a + x - 1) // x * x B = A - a + b return A * B // gcd(A, B), A r = 0 while i * i <= c: if c % i == 0: A, AA = get(i) B, BB = get(c // i) if A < ans: ans = A r = AA - a if B < ans: ans = B r = BB - a if A == ans: r = min(r, AA - a) if B == ans: r = min(r, BB - a) i += 1 print(r) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Shashank is playing a game with his friends. There are n sticks located in a row at points $a_1,a_2, ...,a_n$. Each stick has a height- $h_i$. A person can chop a stick down, after which it takes over one of the regions [$a_i$ - $h_i$, $a_i$] or [$a_i$, $a_i$ + $h_i$]. The stick that is not chopped remains at the point $a_i$. A person can chop a stick in a particular direction if the region to be taken up by the chopped stick does not overlap with an already existing point. The winner $($s$)$ of the game will be one or more people who can answer the question: What is the maximum number of sticks that can be chopped? Shashank wants to win the game and hence he needs needs your help in finding out what is the maximum number of sticks that can be chopped down. -----Input:----- - The first line of each input contains a single integer n. - n lines follow. Each of the n lines contain a pair of integers: $a_i,h_i$. -----Output:----- Output in a single line answer- the maximum number of sticks that can be chopped down. -----Constraints----- - $1 \leq n \leq 10^5$ - $1 \leq a_i,h_i \leq 10^9$ - The pairs are given in the order of ascending $a_i$. No two sticks are located at the same point. -----Sample Input 1:----- 5 1 2 2 1 5 10 10 9 19 1 -----Sample Input 2:----- 5 1 2 2 1 5 10 10 9 20 1 -----Sample Output 1:----- 3 -----Sample Output 2:----- 4 -----EXPLANATION:----- In the first example you can fell the sticks as follows: - chop the stick 1 to the left — now it will take over the region $[ - 1;1]$ - chop the stick 2 to the right — now it will take over the region $[2;3]$ - spare the stick 3— it will take over the point $5$ - spare the stick 4— it will take over the point $10$ - chop the stick 5 to the right — now it will take over the region $[19;20]$ 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 n=int(input()) counts=dict() z=0 upper=None for i in range(0,n): a,h= [int(num) for num in input().split()] counts[a]=h for key,count in counts.items(): c=0 x=key-count y=key+count c1=0 c2=0 for j in counts.keys(): if j==key: continue else: if x<=j<=key: c1=0 break else: c1=1 for j in counts.keys(): if j==key: continue else: if key<=j<=y: c2=0 break else: c2=1 if c2==0 and c1==1: if upper is None: z=z+c1 upper=key else: if x>=upper: z=z+c1 upper=key else: z=z+c2 upper=key elif c2==1 and c1==0: if upper is None: z=z+c2 upper=y else: if upper<=key: z=z+c2 upper=y else: z=z+c1 upper=y elif c2==1 and c1==1: if upper is None: z=z+c1 upper=key else: if x>=upper: z=z+c1 upper=key else: if upper<=key: z=z+c2 upper=y else: z=z+0 upper=y else: z=z+0 upper=key if len(counts)==1: print(1) else: print(z) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given positive integers $N$ and $D$. You may perform operations of the following two types: - add $D$ to $N$, i.e. change $N$ to $N+D$ - change $N$ to $\mathop{\mathrm{digitsum}}(N)$ Here, $\mathop{\mathrm{digitsum}}(x)$ is the sum of decimal digits of $x$. For example, $\mathop{\mathrm{digitsum}}(123)=1+2+3=6$, $\mathop{\mathrm{digitsum}}(100)=1+0+0=1$, $\mathop{\mathrm{digitsum}}(365)=3+6+5=14$. You may perform any number of operations (including zero) in any order. Please find the minimum obtainable value of $N$ and the minimum number of operations required to obtain this value. -----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 $D$. -----Output----- For each test case, print a single line containing two space-separated integers — the minimum value of $N$ and the minimum required number of operations. -----Constraints----- - $1 \le T \le 10$ - $1 \le N, D \le 10^{10}$ -----Subtasks----- Subtask #1 (30 points): $1 \le N, D \le 100$ Subtask #2 (70 points): original constraints -----Example Input----- 3 2 1 9 3 11 13 -----Example Output----- 1 9 3 2 1 4 -----Explanation----- Example case 1: The value $N=1$ can be achieved by 8 successive "add" operations (changing $N$ to $10$) and one "digit-sum" operation. Example case 2: You can prove that you cannot obtain $N=1$ and $N=2$, and you can obtain $N=3$. The value $N=3$ can be achieved by one "add" and one "digitsum" operation, changing $9$ to $12$ and $12$ to $3$. Example case 3: $N=1$ can be achieved by operations "add", "add", "digitsum", "digitsum": $11 \rightarrow 24 \rightarrow 37 \rightarrow 10 \rightarrow 1$. 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 T=int(input()) def break_down(num): count=0 while(len(num)!=1): temp=0 for i in range(0,len(num)): temp=temp+int(num[i]) num=str(temp) count=count+1 return (int(num),count) def digit_sum(num): temp=0 for i in range(0,len(num)): temp=temp+int(num[i]) num=temp return (num) while(T): queue=deque() count_n=0 count_d=0 T=T-1 N,d=[i for i in input().split()] n,count_n=break_down(N) D,count_D=break_down(d) dic={} if(D==1 or D==2 or D==4 or D==5 or D==7 or D==8): mini=1 elif(D==3 or D==6): mini=min(digit_sum(str(n+3)),digit_sum(str(n+6)),digit_sum(str(n+9))) else: mini=n queue.append((int(N),0)) ele=int(N) count=0 while(len(queue)!=0): ele,count=queue.popleft() if(ele==mini): break else: if(len(str(ele))==1): temp1=ele+int(d) queue.append((temp1,count+1)) else: temp2=digit_sum(str(ele)) temp1=ele+int(d) queue.append((temp2,count+1)) queue.append((temp1,count+1)) print(ele,count) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given $n$ intervals on the $X$ axis. Each interval $i$ is specified by its ends $[L_i, R_i]$. You want to color each interval either blue or yellow. After coloring all the intervals, the $X$ axis will will have $4$ colors: - White, the part of $X$ axis contained in no interval - Blue, the part of $X$ axis contained in atleast one blue colored interval and no yellow colored interval. - Yellow, the part of $X$ axis contained in atleast one yellow colored interval and no blue colored interval. - Green, the part of $X$ axis contained in at least one blue colored interval and at least one yellow colored interval. You want to color the intervals so that the total length of the part colored green is maximized. If there are multiple ways to color which maximize the green part, you can output any of them. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - The first line of each testcase contains $n$, the number of intervals. - The $i^{\text{th}}$ of the next $n$ lines contains two integers $L_i$ and $R_i$ describing the $i^{\text{th}}$ interval. -----Output:----- For each testcase, output a single string on a new line, whose $i^{\text{th}}$ character is $0$ if you color the $i^{\text{th}}$ interval blue, and $1$ if you color it yellow. -----Constraints----- - $ 1 \leq T \leq 10^5 $ - $ 1 \leq n \leq 10^5 $ - The sum of $n$ over all testcases doesn't exceed $10^5$. - $ 1 \leq L_i \leq R_i \leq 10^9 $ for al $ 1 \leq i \leq n$. -----Sample Input:----- 1 3 3 7 2 5 6 9 -----Sample Output:----- 100 -----Explanation:----- The intervals are $[3, 7]$, $[2, 5]$, $[6, 9]$. It is optimal to color them in yellow, blue and blue respectively. In this coloring: - $[2, 3) \cup (7, 9]$ is colored blue. - $(5, 6)$ is colored yellow. - $[3, 5] \cup [6, 7]$ is colored green, with a total length of $(5 - 3) + (7 - 6) = 3$. - Rest of the $X$ axis is colored white. Please note that colors at the endpoints of the intervals don't matter when computing the lengths, and we can ignore them. Open and closed intervals have been used in the explanation section only for clarity, and it doesn't matter whether they are open or closed. Note that 011 is also a valid output. 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 = int(input()) ls = [] rs = [] lrs = [] for i in range(n): l, r = map(int, input().split()) ls.append(l) rs.append(r) lrs.append((l, r, i)) lrs.sort() c = 0 maxi = -1 res = [-1] * n for l, r, i in lrs: if ls[i] > maxi: maxi = rs[i] res[i] = c elif rs[i] <= maxi: res[i] = 1^c else: maxi = rs[i] c ^= 1 res[i] = c print(*res, sep='') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The notorious hacker group "Sed" managed to obtain a string $S$ from their secret sources. The string contains only lowercase English letters along with the character '?'. A substring of $S$ is a contiguous subsequence of that string. For example, the string "chef" is a substring of the string "codechef", but the string "codeh" is not a substring of "codechef". A substring of $S$ is good if it is possible to choose a lowercase English letter $C$ such that the following process succeeds: - Create a string $R$, which is a copy of the substring, but with each '?' replaced by the letter $c$. Note that all occurrences of '?' must be replaced by the same letter. - For each lowercase English letter: - Compute the number of times it occurs in $S$ and the number of times it occurs in $R$; let's denote them by $A$ and $B$ respectively. The '?' characters in the original string $S$ are ignored when computing $A$. - Check the parity of $A$ and $B$. If they do not have the same parity, i.e. one of them is even while the other is odd, then this process fails. - If the parities of the number of occurrences in $S$ and $R$ are the same for each letter, the process succeeds. For different substrings, we may choose different values of $C$. Help Sed find the number of good substrings in the string $S$. -----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 a single string $S$. -----Output----- For each test case, print a single line containing one integer ― the number of good substrings. -----Constraints----- - $1 \le T \le 10^5$ - $1 \le S \le 10^5$ - $S$ contains only lowercase English letters ('a' through 'z') and '?' - the sum of $|S|$ over all test cases does not exceed $10^5$ -----Example Input----- 5 aa? a??? ???? asfhaslskfak af??avvnfed?fav?faf???? -----Example Output----- 2 6 4 2 27 -----Explanation----- Example case 1: All letters occur an even number of times in $S$. The six substrings of $S$ are "a", "a", "?", "aa", "a?" and "aa?" (note that "a" is counted twice). Which of them are good? - "a" is not good as 'a' occurs an odd number of times in this substring and there are no '?' to replace. - "?" is also not good as replacing '?' by any letter causes this letter to occur in $R$ an odd number of times. - "aa" is a good substring because each letter occurs in it an even number of times and there are no '?' to replace. - "a?" is also a good substring. We can replace '?' with 'a'. Then, $R$ is "aa" and each letter occurs in this string an even number of times. Note that replacing '?' e.g. with 'b' would not work ($R$ would be "ab", where both 'a' and 'b' occur an odd number of times), but we may choose the replacement letter $C$ appropriately. - "aa?" is not a good substring. For any replacement letter $C$, we find that $C$ occurs an odd number of times in $R$. Example case 2: We especially note that "a???" is not a good substring. Since all '?' have to be replaced by the same character, we can only get strings of the form "aaaa", "abbb", "accc", etc., but none of them match the criteria for a good substring. Example case 3: Any substring with even length is good. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def convertToParitys(s): """ This converts the string s to an int, which is a bitMap of the parity of each letter odd ? = first bit set odd a = second bit set odd b = third bit set etc """ keys = '?abcdefghijklmnopqrstuvwxyz' paritys = {c:0 for c in keys} for c in s: paritys[c] += 1 for c, v in paritys.items(): paritys[c] = v%2 out = 0 bitValue = 1 for c in keys: if paritys[c]: out += bitValue bitValue *= 2 return out def getSolutionBitMaps(s): """ these are the 27 valid bitmaps that a substring can have even ? and the parities the same 26 cases of odd ? and one bit different in the parity compared to s """ out = [] sP = convertToParitys(s) if sP%2: sP -= 1 # to remove the '?' parity #even case - out.append(sP) #odd cases - need to xor sP with 1 + 2**n n = 1 to 26 inc to flip ? bit and each of the others for n in range(1,27): out.append(sP^(1+2**n)) return out def getLeadingSubStringBitMapCounts(s): """ This calculates the bit map of each of the len(s) substrings starting with the first character and stores as a dictionary. Getting TLE calculating each individually, so calculating with a single pass """ out = {} bM = 0 keys = '?abcdefghijklmnopqrstuvwxyz' paritys = {c:0 for c in keys} values = {c:2**i for i,c in enumerate(keys)} out[bM] = out.setdefault(bM, 0) + 1 #add the null substring bMis = [] i = 0 bMis = [0] for c in s: i += 1 if paritys[c]: paritys[c] = 0 bM -= values[c] else: paritys[c] = 1 bM += values[c] out[bM] = out.setdefault(bM, 0) + 1 bMis.append(bM) return out,bMis def solve(s): out = 0 bMjCounts,bMis = getLeadingSubStringBitMapCounts(s) #print('bMjCounts') #print(bMjCounts) solutions = getSolutionBitMaps(s) #print('solutions') #print(solutions) for bMi in bMis: for bMs in solutions: if bMs^bMi in bMjCounts: out += bMjCounts[bMs^bMi] #print(i,bMi,bMs,bMs^bMi,bMjCounts[bMs^bMi]) if 0 in solutions: out -= len(s) #remove all null substrings out //= 2 # since j may be less that i each substring is counted twice return out T = int(input()) for tc in range(T): s = input() print(solve(s)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a haunted town called HauntedLand. The structure of HauntedLand can be thought of as a grid of size n * m. There is a house in each cell of the grid. Some people have fled from their houses because they were haunted. '.' represents a haunted house whereas '*' represents a house in which people are living. One day, Devu, the famous perfumer came to town with a perfume whose smell can hypnotize people. Devu can put the perfume in at most one of the houses. This takes Devu one second. Then, the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues. Two houses are said to be a adjacent to each other, if they share a corner or an edge, i.e., each house (except those on the boundaries) will have 8 adjacent houses. You want to save people from Devu's dark perfumery by sending them a message to flee from the town. So, you need to estimate the minimum amount of time Devu needs to hypnotize all the people? Note that if there are no houses inhabited by people, Devu doesn't need to put perfume in any cell. -----Input----- The first line of 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 two space separated integers n, m denoting the dimensions of the town. For each of next n lines, each line has m characters (without any space) denoting a row of houses of the town. -----Output----- For each test case, output a single integer corresponding to the answer of the problem. -----Constraints----- - 1 ≤ T ≤ 20 Subtask #1: (40 points) - 1 ≤ n, m ≤ 100Subtask #2: (60 points) - 1 ≤ n, m ≤ 1000 -----Example----- Input: 2 2 2 *... 3 4 .*..***..*.. Output: 1 2 -----Explanation----- In the first example, it will take Devu one second for putting the perfume at the only house. So, the answer is 1. In the second example, He will first put the perfume at the * at cell (1, 1) (assuming 0-based indexing). Now, it will take Devu 1 secs to put perfume. In the next second, the perfume will spread to all of its adjacent cells, thus making each house haunted. 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 math t = int(input().strip()) for _ in range(t): n, m = list(map(int, input().strip().split())) a = [] v = [-1] * 4 for i in range(n): a.append(input().strip()) for i, ai in enumerate(a): if ai.find('*') > -1: v[2] = i break if v[2] == -1: print(0) else: for i, ai in reversed(list(enumerate(a))): if ai.find('*') > -1: v[3] = i break for i in range(m): x = [ai[i] for ai in a] if '*' in x: v[0] = i break for i in reversed(range(m)): x = [ai[i] for ai in a] if '*' in x: v[1] = i break if v.count(v[0]) == len(v): print(1) else: print(int(math.ceil(max(v[3] - v[2], v[1] - v[0]) / 2.0)) + 1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given sequence a_1, a_2, ..., a_{n} of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. -----Input----- The first line contains integer number n (1 ≤ n ≤ 10^5). The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^4 ≤ a_{i} ≤ 10^4). The sequence contains at least one subsequence with odd sum. -----Output----- Print sum of resulting subseqeuence. -----Examples----- Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 -----Note----- In the first example sum of the second and the fourth elements is 3. 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()) a = list(map(int, input().split())) res = 0 new_a = [] for i in range(n): if a[i] % 2 == 0: if a[i] > 0: res += a[i] else: new_a.append(a[i]) a = new_a a.sort() res += a[-1] a.pop() while len(a) > 1: if a[-1] + a[-2] > 0: res += a[-1] + a[-2] a.pop() a.pop() else: break print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length. For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 3^2 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 2^2 = 4). For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece. -----Input----- The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process. Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively. -----Output----- For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares. -----Examples----- Input 4 2 2 1 2 2 3 2 2 2 2 2 4 Output 5 5 4 0 -----Note----- In the first query of the sample one needs to perform two breaks: to split 2 × 2 bar into two pieces of 2 × 1 (cost is 2^2 = 4), to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 1^2 = 1). In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python mem = [[[0 for i in range(51)] for j in range(31)] for k in range(31)] def f(n, m, k): if mem[n][m][k]: return mem[n][m][k] if (n*m == k) or (k == 0): return 0 cost = 10**9 for x in range(1, n//2 + 1): for z in range(k+1): cost = min(cost, m*m + f(n-x, m, k-z) + f(x, m, z)) for y in range(1, m//2 + 1): for z in range(k+1): cost = min(cost, n*n + f(n, m-y, k-z) + f(n, y, z)) mem[n][m][k] = cost return cost t = int(input()) for i in range(t): n, m, k = list(map(int, input().split())) print(f(n, m, k)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is very organised in whatever he does and likes to maintain statistics of his work. Chef has expertise in web development and hence is a regular contributor on a forum. Chef sometimes makes multiple contributions in a single day.. Each day chef makes at least 1 contribution he is assigned a shade of green. The greater the number of contribution in a single day the darker shade of green he gets assigned and vice versa. Your job is to find out the number of days chef is assigned a same shade of green and print the number of times chef is assigned a unique shade of green. -----INPUT----- The first line of input contains an integer T denoting the number of test cases. T test cases follow. The first line of each test case contains an integer N denoting the number of days chef has contributed towards the forum. The next line contains N spaced integers the number of contributions chef has made if he has made any. -----OUTPUT----- The output will contain numbers on separate lines that show the number of individual green shades chef has earned in ascending order of intensity of the shades of green. -----CONSTRAINTS----- 1 <= T <= 25 5 <= N <= 50 1 <= Ai <= 50 -----EXAMPLE-----Input: 1 7 20 6 5 3 3 1 1 Output: 1: 2 3: 2 5: 1 6: 1 20: 1 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 t=int(input()) for i in range(t): k=int(input()) l=list(map(int,input().split())) a=Counter(l) b=list(a.keys()) b.sort() for x in b: s=str(x)+': '+str(a[x]) print(s) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Kostya likes the number 4 much. Of course! This number has such a lot of properties, like: - Four is the smallest composite number; - It is also the smallest Smith number; - The smallest non-cyclic group has four elements; - Four is the maximal degree of the equation that can be solved in radicals; - There is four-color theorem that states that any map can be colored in no more than four colors in such a way that no two adjacent regions are colored in the same color; - Lagrange's four-square theorem states that every positive integer can be written as the sum of at most four square numbers; - Four is the maximum number of dimensions of a real division algebra; - In bases 6 and 12, 4 is a 1-automorphic number; - And there are a lot more cool stuff about this number! Impressed by the power of this number, Kostya has begun to look for occurrences of four anywhere. He has a list of T integers, for each of them he wants to calculate the number of occurrences of the digit 4 in the decimal representation. He is too busy now, so please help him. -----Input----- The first line of input consists of a single integer T, denoting the number of integers in Kostya's list. Then, there are T lines, each of them contain a single integer from the list. -----Output----- Output T lines. Each of these lines should contain the number of occurences of the digit 4 in the respective integer from Kostya's list. -----Constraints----- - 1 ≤ T ≤ 105 - (Subtask 1): 0 ≤ Numbers from the list ≤ 9 - 33 points. - (Subtask 2): 0 ≤ Numbers from the list ≤ 109 - 67 points. -----Example----- Input: 5 447474 228 6664 40 81 Output: 4 0 1 1 0 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 x=int(input()) for i in range(x): h=input() print(h.count('4')) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $n$ bosses in this tower, numbered from $1$ to $n$. The type of the $i$-th boss is $a_i$. If the $i$-th boss is easy then its type is $a_i = 0$, otherwise this boss is hard and its type is $a_i = 1$. During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session. Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss. Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all $n$ bosses in the given order. For example: suppose $n = 8$, $a = [1, 0, 1, 1, 0, 1, 1, 1]$. Then the best course of action is the following: your friend kills two first bosses, using one skip point for the first boss; you kill the third and the fourth bosses; your friend kills the fifth boss; you kill the sixth and the seventh bosses; your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — 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 2 \cdot 10^5$) — the number of bosses. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 1$), where $a_i$ is the type of the $i$-th boss. It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer: the minimum number of skip points your friend needs to use so you and your friend kill all $n$ bosses in the given order. -----Example----- Input 6 8 1 0 1 1 0 1 1 1 5 1 1 1 1 0 7 1 1 1 1 0 0 1 6 1 1 1 1 1 1 1 1 1 0 Output 2 2 2 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 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())) ans = [999999999] * n ans[0] = 1 if arr[0] == 1 else 0 if n > 1: ans[1] = ans[0] if n > 2: ans[2] = ans[0] for i in range(n): if i + 1 >= n: continue if arr[i + 1] == 1: ans[i + 1] = min(ans[i + 1], ans[i] + 1) if i + 2 < n: ans[i + 2] = min(ans[i + 2], ans[i] + 1) if i + 3 < n: ans[i + 3] = min(ans[i + 3], ans[i] + 1) else: ans[i + 1] = min(ans[i + 1], ans[i]) if i + 2 < n: ans[i + 2] = min(ans[i + 2], ans[i]) if i + 3 < n: ans[i + 3] = min(ans[i + 3], ans[i]) print(ans[-1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office. All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence p_{i}. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor. While Gennady treats the teeth of the i-th child, the child is crying with the volume of v_{i}. At that the confidence of the first child in the line is reduced by the amount of v_{i}, the second one — by value v_{i} - 1, and so on. The children in the queue after the v_{i}-th child almost do not hear the crying, so their confidence remains unchanged. If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of d_{j} and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of d_{j}. All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office. Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order. -----Input----- The first line of the input contains a positive integer n (1 ≤ n ≤ 4000) — the number of kids in the line. Next n lines contain three integers each v_{i}, d_{i}, p_{i} (1 ≤ v_{i}, d_{i}, p_{i} ≤ 10^6) — the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child. -----Output----- In the first line print number k — the number of children whose teeth Gennady will cure. In the second line print k integers — the numbers of the children who will make it to the end of the line in the increasing order. -----Examples----- Input 5 4 2 2 4 1 2 5 2 4 3 3 5 5 1 2 Output 2 1 3 Input 5 4 5 1 5 3 9 4 1 2 2 1 8 4 1 9 Output 4 1 2 4 5 -----Note----- In the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit. In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5, - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys n = int(input()) v = [ list(map(int, input().split())) for i in range(n)] res = [] for i in range(n): if v[i][2] >= 0: res.append(i + 1) dec = 0 for j in range(i + 1, n): if v[j][2] >= 0: if v[i][0] > 0: v[j][2] -= v[i][0] v[i][0] -= 1 v[j][2] -= dec if v[j][2] < 0: dec += v[j][1] print(len(res)) print(" ".join(map(str, res))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A tennis tournament is about to take place with $N$ players participating in it. Every player plays with every other player exactly once and there are no ties. That is, every match has a winner and a loser. With Naman's birthday approaching, he wants to make sure that each player wins the same number of matches so that nobody gets disheartened. Your task is to determine if such a scenario can take place and if yes find one such scenario. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single integer $N$ denoting number of players. -----Output:----- - If it's impossible for everyone to win the same number of matches, print "NO" (without quotes). - Otherwise print "YES" (without quotes) and then print $N$ lines , each line should consist of a string containing only 0s and 1s and should be of size $N$. - If the jth character in the ith line is 1 then it means in the match between $i$ and $j$ , $i$ wins. - You will get a WA if the output does not correspond to a valid tournament, or if the constraints are not satisfied. - You will get also WA verdict if any 2 lines have contradicting results or if a player beats himself. -----Constraints----- - $1 \leq T \leq 100$ - $2 \leq N \leq 100$ -----Subtasks----- - 10 points : $2 \leq N \leq 6$ - 90 points : Original Constraints. -----Sample Input:----- 2 3 2 -----Sample Output:----- YES 010 001 100 NO -----Explanation:----- One such scenario for $N$ = $3$ is when player $1$ beats player $2$, player $2$ to beats player $3$ and player $3$ beats player $1$. Here all players win exactly $1$ match. 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 a = int(input()) for i in range(a): n = int(input()) if n%2==0: print('NO') else: print('YES') for i1 in range(n): li = [0]*n b = str() for i2 in range((n-1)//2): li[(i1+i2+1)%n]+=1 for i3 in range(len(li)): b+=str(li[i3]) print(b) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value init_{i}, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goal_{i}, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. -----Input----- The first line contains an integer n (1 ≤ n ≤ 10^5). Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n; u_{i} ≠ v_{i}) meaning there is an edge between nodes u_{i} and v_{i}. The next line contains n integer numbers, the i-th of them corresponds to init_{i} (init_{i} is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goal_{i} (goal_{i} is either 0 or 1). -----Output----- In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer x_{i}, representing that you pick a node x_{i}. -----Examples----- Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys def dfs(tree, root, priv_root, cur_lvl, priv_lvl, diff, pick_list): if not tree: return stack = [(root, priv_root, cur_lvl, priv_lvl)] while stack: (root, priv_root, cur_lvl, priv_lvl) = stack.pop() if cur_lvl ^ diff[root]: cur_lvl ^= 1 pick_list.append(str(root)) stack += [(vertex, root, priv_lvl, cur_lvl) for vertex in tree[root] if vertex != priv_root] def main(): n = int(input()) tree = dict() for _ in range(n - 1): (u, v) = list(map(int, input().split())) tree[u] = tree.get(u, set()) | set([v]) tree[v] = tree.get(v, set()) | set([u]) init = [0] + list(map(int, input().split())) goal = [0] + list(map(int, input().split())) diff = [i ^ j for (i, j) in zip(init, goal)] pick_list = list() dfs(tree, 1, 0, 0, 0, diff, pick_list) num = len(pick_list) print(num) if num: print('\n'.join(pick_list)) def __starting_point(): return(main()) __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Bob is playing with $6$-sided dice. A net of such standard cube is shown below. [Image] He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. For example, the number of visible pips on the tower below is $29$ — the number visible on the top is $1$, from the south $5$ and $3$, from the west $4$ and $2$, from the north $2$ and $4$ and from the east $3$ and $5$. [Image] The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total. Bob also has $t$ favourite integers $x_i$, and for every such integer his goal is to build such a tower that the number of visible pips is exactly $x_i$. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips. -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 1000$) — the number of favourite integers of Bob. The second line contains $t$ space-separated integers $x_i$ ($1 \leq x_i \leq 10^{18}$) — Bob's favourite integers. -----Output----- For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity). -----Example----- Input 4 29 34 19 38 Output YES YES YES NO -----Note----- The first example is mentioned in the problem statement. In the second example, one can build the tower by flipping the top dice from the previous tower. In the third example, one can use a single die that has $5$ on top. The fourth example is impossible. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = input() a = list(map(int, input().split())) for i in a: if i % 7 == 0 or (i // 7) % 2 == 1 or i <= 14: print('NO') else: print('YES') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef's pizza is the tastiest pizza to exist, and the reason for that is his special, juicy homegrown tomatoes. Tomatoes can be grown in rectangular patches of any side lengths. However, Chef only has a limited amount of land. Consider the entire town of Chefville to be consisting of cells in a rectangular grid of positive coordinates. Chef own all cells (x,y)$(x, y)$ that satisfy x∗y≤N$x*y \leq N$ As an example if N=4$N = 4$, Chef owns the following cells: (1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(3,1),(4,1)$(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1) $ Chef can only grow tomatoes in rectangular patches consisting only of cells which belong to him. Also, if he uses a cell, he must use it entirely. He cannot use only a portion of it. Help Chef find the number of unique patches of rectangular land that he can grow tomatoes in! Since this number can be very large, output it modulo 1000000007$1000000007$. -----Input:----- - The first line of the input contains T$T$, the number of test cases. - The next T$T$ lines of input contains one integer N$N$. -----Output:----- For each testcase, output the number of ways modulo 1000000007$1000000007$. -----Constraints----- - 1≤T≤5$1 \leq T \leq 5$ - 1≤N≤1010$1 \leq N \leq 10^{10}$ -----Sample Input:----- 2 4 10000000000 -----Sample Output:----- 23 227374950 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 * def list_input(): return list(map(int,input().split())) def map_input(): return list(map(int,input().split())) def map_string(): return input().split() def g(n): return (n*(n+1)*(2*n+1))//6 def f(n): ans = 0 for i in range(1,floor(sqrt(n))+1): ans+=i*(i+floor(n/i))*(floor(n/i)+1-i) return ans-g(floor(sqrt(n))) for _ in range(int(input())): n=int(input()) print(f(n)%1000000007) ```
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:----- 3 2 3 4 -----Sample Output:----- 12 21 123 231 312 1234 2341 3412 4123 -----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 a0 in range(int(input())): n = int(input()) l = [] for i in range(1,n+1): l.append(i) for j in range(n): s = "" for k in l: s+=str(k) print(s) x = l[0] l.pop(0) l.append(x) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Johnny was asked by his math teacher to compute nn (n to the power of n, where n is an integer), and has to read his answer out loud. This is a bit of a tiring task, since the result is probably an extremely large number, and would certainly keep Johnny occupied for a while if he were to do it honestly. But Johnny knows that the teacher will certainly get bored when listening to his answer, and will sleep through most of it! So, Johnny feels he will get away with reading only the first k digits of the result before the teacher falls asleep, and then the last k digits when the teacher wakes up. Write a program to help Johnny to compute the digits he will need to read out. -----Input----- The first line contains t, the number of test cases (about 30000). Then t test cases follow. Each test case consists of one line containing two numbers n and k (1 ≤ n ≤ 109, 1 ≤ k ≤ 9). It is guaranteed that k is not more than the number of digits of nn. -----Output----- For each test case, print out one line containing two numbers, separated by a space, which are the first and the last k digits of nn. -----Example----- Input 2 4 2 9 3 Output 25 56 387 489 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 log10 from decimal import Decimal def solve(n,k): mod=10**k x=Decimal(n) y=x*(x.log10())%1 p=str(pow(10,y)) c=0 first='' for v in p: if c==k: break if v==".": continue first+=v c+=1 last=str(pow(n,n,mod)).zfill(k) return (first,last) queries=[] for _ in range(int(input())): n,k=list(map(int,input().split( ))) queries.append((n,k)) for n,k in queries: print("%s %s"%(solve(n,k))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are n beacons located at distinct positions on a number line. The i-th beacon has position a_{i} and power level b_{i}. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance b_{i} inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated. Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. -----Input----- The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers a_{i} and b_{i} (0 ≤ a_{i} ≤ 1 000 000, 1 ≤ b_{i} ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so a_{i} ≠ a_{j} if i ≠ j. -----Output----- Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. -----Examples----- Input 4 1 9 3 1 6 1 7 4 Output 1 Input 7 1 1 2 1 3 1 4 1 5 1 6 1 7 1 Output 3 -----Note----- For the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2. For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. 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()) pos_blast = [list(map(int, input().split())) for _ in range(n)] MAX_N = max(pos_blast, key=lambda x: x[0])[0] + 2 power = [0 for _ in range(MAX_N)] tower = [False for _ in range(MAX_N)] can_destroy = [0 for _ in range(MAX_N)] for pos, blast in pos_blast: pos += 1 tower[pos] = True power[pos] = blast for i in range(1, MAX_N): if not tower[i]: can_destroy[i] = can_destroy[i-1] else: can_destroy[i] = can_destroy[max(0, i - power[i] - 1)] + 1 print(n - max(can_destroy)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef and Paja are bored, so they are playing an infinite game of ping pong. The rules of the game are as follows: - The players play an infinite number of games. At the end of each game, the player who won it scores a point. - In each game, one of the players serves. Chef serves in the first game. - After every $K$ points are scored (regardless of which players scored them), i.e. whenever $K$ games have been played since the last time the serving player changed, the player that serves in the subsequent games changes: if Chef served in the game that just finished, then Paja will serve in the next game and all subsequent games until the serving player changes again; if Paja served, then Chef will serve. The players got a little too caught up in the game and they forgot who is supposed to serve in the next game. Will you help them determine that? So far, Chef has scored $X$ points and Paja has scored $Y$ points. -----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 three space-separated integers $X$, $Y$ and $K$. -----Output----- For each test case, print a single line containing the string "Chef" if Chef is supposed to serve next or "Paja" otherwise (without quotes). -----Constraints----- - $1 \le T \le 50$ - $0 \le X, Y \le 10^9$ - $1 \le K \le 10^9$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 3 1 3 3 5 7 2 38657 76322 564 -----Example Output----- Paja Chef Paja -----Explanation----- Example case 1: Chef served for the first three games, after that Paja started serving. He only served in one game, so he is supposed to serve next. 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()) while(n>0): x,y,z=map(int,input().split()) t=(x+y)//z if t%2==0: print('Chef') else: print('Paja') n-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After a long and successful day of preparing food for the banquet, it is time to clean up. There is a list of n jobs to do before the kitchen can be closed for the night. These jobs are indexed from 1 to n. Most of the cooks have already left and only the Chef and his assistant are left to clean up. Thankfully, some of the cooks took care of some of the jobs before they left so only a subset of the n jobs remain. The Chef and his assistant divide up the remaining jobs in the following manner. The Chef takes the unfinished job with least index, the assistant takes the unfinished job with the second least index, the Chef takes the unfinished job with the third least index, etc. That is, if the unfinished jobs were listed in increasing order of their index then the Chef would take every other one starting with the first job in the list and the assistant would take every other one starting with the second job on in the list. The cooks logged which jobs they finished before they left. Unfortunately, these jobs were not recorded in any particular order. Given an unsorted list of finished jobs, you are to determine which jobs the Chef must complete and which jobs his assitant must complete before closing the kitchen for the evening. -----Input----- The first line contains a single integer T ≤ 50 indicating the number of test cases to follow. Each test case consists of two lines. The first line contains two numbers n,m satisfying 0 ≤ m ≤ n ≤ 1000. Here, n is the total number of jobs that must be completed before closing and m is the number of jobs that have already been completed. The second line contains a list of m distinct integers between 1 and n. These are the indices of the jobs that have already been completed. Consecutive integers are separated by a single space. -----Output----- The output for each test case consists of two lines. The first line is a list of the indices of the jobs assigned to the Chef. The second line is a list of the indices of the jobs assigned to his assistant. Both lists must appear in increasing order of indices and consecutive integers should be separated by a single space. If either the Chef or the assistant is not assigned any jobs, then their corresponding line should be blank. -----Example----- Input: 3 6 3 2 4 1 3 2 3 2 8 2 3 8 Output: 3 6 5 1 1 4 6 2 5 7 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,m = map(int,input().split()) completed = list(map(int,input().split())) jobs = [] for i in range(1,n+1): if i not in completed: jobs.append(i) jobs.sort() chef = [] ass = [] for i in range(len(jobs)): if i%2==0: chef.append(str(jobs[i])) else: ass.append(str(jobs[i])) print(' '.join(chef)) print(' '.join(ass)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given two points $P$ and $Q$ and an opaque sphere in a three-dimensional space. The point $P$ is not moving, while $Q$ is moving in a straight line with constant velocity. You are also given a direction vector $d$ with the following meaning: the position of $Q$ at time $t$ is $Q(t) = Q(0) + d \cdot t$, where $Q(0)$ is the initial position of $Q$. It is guaranteed that $Q$ is not visible from $P$ initially (at time $t=0$). It is also guaranteed that $P$ and $Q$ do not touch the sphere at any time. Find the smallest positive time $t_v$ when $Q$ is visible from $P$, i.e. when the line segment connecting points $P$ and $Q$ does not intersect the sphere. -----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 13 space-separated integers. - The first three integers $P_x, P_y, P_z$ denote the coordinates of $P$. - The next three integers $Q_x, Q_y, Q_z$ denote the initial coordinates of $Q$. - The next three integers $d_x, d_y, d_z$ denote the components of the direction vector $d$. - The last four integers $c_x, c_y, c_z, r$ denote the coordinates of the centre of the sphere and its radius. -----Output----- For each test case, print a single line containing one real number — the time $t_v$. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$. It is guaranteed that $t_v$ exists and does not exceed $10^9$. -----Constraints----- - $1 \le T \le 10^5$ - the absolute values of coordinates of all points do not exceed $2\cdot10^9$ - $1 \le r \le 10^9$ -----Subtasks----- Subtask #1 (25 points): $P_z = Q_z = d_z = c_z = 0$ Subtask #2 (75 points): original constraints -----Example Input----- 1 3 0 0 -10 -10 0 0 10 0 0 -3 0 3 -----Example Output----- 1.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 epi=10**-2 def vision(t): a1=x0+(dx*t)-x1 a2=y0+(dy*t)-y1 a3=z0+(dz*t)-z1 b=4*((a1*d1)+(a2*d2)+(a3*d3))*((a1*d1)+(a2*d2)+(a3*d3)) a=4*((a1*a1)+(a2*a2)+(a3*a3)) value=(b-(a*c)) return value xrange=range for _ in range(int(input())): x1,y1,z1,x0,y0,z0,dx,dy,dz,cx,cy,cz,r=list(map(int,input().split())) d1=x1-cx d2=y1-cy d3=z1-cz c=(d1*d1)+(d2*d2)+(d3*d3)-(r*r) low=0 high=10**9+1 while low<(high-10**-6): mid=low+(high-low)*1.0/2; value=vision(mid); if abs(value)<=epi: break; elif value>0: low=mid; else: high=mid; print(mid) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: "I'm a fan of anything that tries to replace actual human contact." - Sheldon. After years of hard work, Sheldon was finally able to develop a formula which would diminish the real human contact. He found k$k$ integers n1,n2...nk$n_1,n_2...n_k$ . Also he found that if he could minimize the value of m$m$ such that ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$ = ∑ki=1$\sum_{i=1}^k$mi$m_i$, he would finish the real human contact. Since Sheldon is busy choosing between PS-4 and XBOX-ONE, he want you to help him to calculate the minimum value of m$m$. -----Input:----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains a single integer k$k$. - Next line contains k space separated integers n1,n2...nk$n_1,n_2...n_k$ . -----Output:----- For each test case output the minimum value of m for which ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$=m1$m_1$+m2$m_2$+. . . mk$m_k$ and 0$0$ <= mi$m_i$<= ni$n_i$ . If no such answer exists print -1. -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤k≤1000$1 \leq k \leq 1000$ - 1≤ni≤10$1 \leq n_i \leq 10$18$18$ -----Sample Input:----- 1 1 5 -----Sample Output:----- 2 -----EXPLANATION:----- 5$5$C$C$2$2$ = 10 which is even and m is minimum. 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()) def conv(n): k = bin(n) k = k[2:] z = len(k) c = '1'*z if c == k: return False def find(n): x = bin(n)[2:] str = '' for i in x[::-1]: if i == '0': str+='1' break else: str+='0' return int(str[::-1],2) for i in range(t): n = int(input()) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Everyone loves short problem statements. Given a function $ f(x) $ find its minimum value over the range $ 0 < x < π/2$ $ f(x) = ( x^2 + b*x + c ) / sin( x ) $ -----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, two real numbers $b, c$. -----Output:----- For each test case, output the minimum value of $ f(x) $ over the given range. Absolute error of $10^{-6}$ is allowed. -----Constraints----- - $1 \leq T \leq 100000$ - $1 \leq b,c \leq 20$ -----Sample Input:----- 1 2 2 -----Sample Output:----- 5.8831725615 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 math input=sys.stdin.readline def binary(l,r,co,b,c): x=(l+r)/2 #print(x) val1=(2*x+b)*math.sin(x) val2=(x**2+b*x+c)*math.cos(x) x=(l+r)/2 val=val1-val2 if(abs(val)<.0000001 or co==150): return (l+r)/2 if(val<0): return binary((l+r)/2,r,co+1,b,c) else: return binary(l,(l+r)/2,co+1,b,c) t=int(input()) for _ in range(t): b,c=list(map(float,input().split())) x=binary(.0000000001,math.pi/2-.0000000001,0,b,c) #print("t=",_) val=(x*x+b*x+c)/math.sin(x) print(val) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have unweighted tree of $n$ vertices. You have to assign a positive weight to each edge so that the following condition would hold: For every two different leaves $v_{1}$ and $v_{2}$ of this tree, bitwise XOR of weights of all edges on the simple path between $v_{1}$ and $v_{2}$ has to be equal to $0$. Note that you can put very large positive integers (like $10^{(10^{10})}$). It's guaranteed that such assignment always exists under given constraints. Now let's define $f$ as the number of distinct weights in assignment. [Image] In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $0$. $f$ value is $2$ here, because there are $2$ distinct edge weights($4$ and $5$). [Image] In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $1$ and vertex $6$ ($3, 4, 5, 4$) is not $0$. What are the minimum and the maximum possible values of $f$ for the given tree? Find and print both. -----Input----- The first line contains integer $n$ ($3 \le n \le 10^{5}$) — the number of vertices in given tree. The $i$-th of the next $n-1$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$) — it means there is an edge between $a_{i}$ and $b_{i}$. It is guaranteed that given graph forms tree of $n$ vertices. -----Output----- Print two integers — the minimum and maximum possible value of $f$ can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. -----Examples----- Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 -----Note----- In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. [Image] In the second example, possible assignments for each minimum and maximum are described in picture below. The $f$ value of valid assignment of this tree is always $3$. [Image] In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. [Image] 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()) g = [[] for i in range(n)] for i in range(n-1): u,v = [int(i)-1 for i in input().split()] g[u].append(v) g[v].append(u) leaf = [len(i)==1 for i in g] root = -1 mx = n-1 for i in range(n): if leaf[i]: root = i leafs = 0 for j in g[i]: if leaf[j]: leafs += 1 if leafs > 1: mx -= leafs-1 stack = [(root, -1, 0)] even = True while len(stack)>0: i, j, d = stack.pop() if leaf[i] and d%2 == 1: even = False break for k in g[i]: if k != j: stack.append((k,i,d+1)) mn = 1 if even else 3 print(mn,mx) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef Loves to listen to remix songs, but currently he had already finished the entire playlist of remix songs. As Chef is smart, so he thought let's make my own remix songs of the original songs. Chef is not having much knowledge of making remix songs, so he came up with the simple technique in which he will pick the word which contains the smallest number of characters from the lyrics of the song, and then he will append that word to the start and end of the lyrics, also Chef will insert this word between every two words of the lyrics. Note: While inserting a new word Chef will also insert extra white-spaces, so that every word in the final remixed lyrics is separated by space. It is Recommended to use fast Input/Ouput techniques. -----Input:----- - The input contains the text $S$, which denotes the lyrics of the song. -----Output:----- - Print the Remixed, lyrics as done by Chef. -----Constraints:----- - $1 \leq Length of text $S$ \leq 10^7$ -----Sample Input:----- Mai Hu Jiyaan -----Sample Output:----- Hu Mai Hu Hu Hu Jiyaan Hu The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python m= 9999999 word='' p= '' try: s=input().split() for i in s: if(len(i) <= m): m = len(i) word = i p = word for i in s: p+= (' '+i+' '+ word) print(p) except EOFError: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Due to the COVID pandemic, people have been advised to stay at least $6$ feet away from any other person. Now, people are lining up in a queue at the local shop and it is your duty to check whether they are all following this advice. There are a total of $N$ spots (numbered $1$ through $N$) where people can stand in front of the local shop. The distance between each pair of adjacent spots is $1$ foot. Each spot may be either empty or occupied; you are given a sequence $A_1, A_2, \ldots, A_N$, where for each valid $i$, $A_i = 0$ means that the $i$-th spot is empty, while $A_i = 1$ means that there is a person standing at this spot. It is guaranteed that the queue is not completely empty. For example, if $N = 11$ and the sequence $A$ is $(0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1)$, then this is a queue in which people are not following the advice because there are two people at a distance of just $3$ feet from each other. You need to determine whether the people outside the local shop are following the social distancing advice or not. As long as some two people are standing at a distance smaller than 6 feet from each other, it is bad and you should report it, since social distancing is not being followed. -----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 next line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing the string "YES" if social distancing is being followed or "NO" otherwise (without quotes). -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 100$ - $0 \le A_i \le 1$ for each valid $i$ - at least one spot is occupied -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 3 3 1 0 1 7 1 0 0 0 0 0 1 11 0 1 0 0 0 0 0 1 0 0 1 -----Example Output----- NO YES NO -----Explanation----- Example case 1: The first and third spots are occupied and the distance between them is $2$ feet. Example case 2: The first and seventh spots are occupied and the distance between them is $6$ feet. 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()) l=list(map(int,input().split())) l1=[] c=1 for i in range(len(l)): if l[i]==1: l1.append(i) for j in range(len(l1)-1): if l1[j+1]-l1[j]<6: c=0 break if c: print("YES") else: print("NO") t-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Every great chef knows that lucky numbers are positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Our chef has recently returned from the Lucky country. He observed that every restaurant in the Lucky country had a lucky number as its name. He believes that having a lucky number as a restaurant name can indeed turn out to be very lucky. Our chef believes that it is possible to make a lucky number having N digits even luckier. Any number following the rules below is called Lucky lucky number - 1. The number contains only digits 4 and 7. 2. Count of digit 4 in the number should be divisible by 7. 3. Count of digit 7 in the number should be divisible by 4. Help our chef to compute the count of digit 4 in the smallest Lucky lucky number having N digits. -----Input----- First line contains T, number of test cases. Each of the next T lines contains a number N, the number of digits in the Lucky lucky number to be formed. 1<=T<=1000 1<=N<=1000000000 (10^9) -----Output----- If it is not possible to form a Lucky lucky number having N digits, output -1. Otherwise, output the count of digit 4 in the smallest Lucky lucky number having N digits. -----Example----- Input: 5 7 4 11 1 15 Output: 7 0 7 -1 7 Explanation For the last test case, N = 15, the smallest lucky lucky number is 444444477777777. The count of digit 4 is 7. 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 os def __starting_point(): start = 0 for line in sys.stdin: if start == 0: start = 1 continue else: try: n = int(line.strip()) # print n q = n/7 rem = n%7 if rem==0: res = n elif rem==1: res = (q-1)*7 elif rem==2: res = (q-2)*7 elif rem==3: res = (q-3)*7 elif rem==4: res = q*7 elif rem==5: res = (q-1)*7 elif rem==6: res = (q-2)*7 if res < 0: print(-1) else: print(res) except: break __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a set Y of n distinct positive integers y_1, y_2, ..., y_{n}. Set X of n distinct positive integers x_1, x_2, ..., x_{n} is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: Take any integer x_{i} and multiply it by two, i.e. replace x_{i} with 2·x_{i}. Take any integer x_{i}, multiply it by two and add one, i.e. replace x_{i} with 2·x_{i} + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y_1, ..., y_{n} (1 ≤ y_{i} ≤ 10^9), that are guaranteed to be distinct. -----Output----- Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. -----Examples----- Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): from heapq import heapify, heapreplace input() s = set(map(int, input().split())) xx = [-x for x in s] heapify(xx) while True: x = -xx[0] while x != 1: x //= 2 if x not in s: s.add(x) heapreplace(xx, -x) break else: break print(' '.join(str(-x) for x in xx)) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n. This time the Little Elephant has permutation p_1, p_2, ..., p_{n}. Its sorting program needs to make exactly m moves, during the i-th move it swaps elements that are at that moment located at the a_{i}-th and the b_{i}-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements. Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed. We'll call a pair of integers i, j (1 ≤ i < j ≤ n) an inversion in permutatuon p_1, p_2, ..., p_{n}, if the following inequality holds: p_{i} > p_{j}. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 1000, n > 1) — the permutation size and the number of moves. The second line contains n distinct integers, not exceeding n — the initial permutation. Next m lines each contain two integers: the i-th line contains integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}) — the positions of elements that were changed during the i-th move. -----Output----- In the only line print a single real number — the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10^{ - 6}. -----Examples----- Input 2 1 1 2 1 2 Output 0.500000000 Input 4 3 1 3 2 4 1 2 2 3 1 4 Output 3.000000000 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python inp = input().split(' ') val=[]; totNums = int(inp[0]); totOpt = int(inp[1]); inp = input().split(' '); #assert(len(inp) == totNums); for it in inp: val.append(int(it)) dp = [[0.0 for _ in range(0,totNums)] for __ in range(0,totNums)] for i in range(0,totNums): for j in range(0,totNums): if val[i]>val[j]: dp[i][j] = 1.0 while totOpt>0: totOpt -= 1 inp = input().split(' ') fr = int(inp[0])-1; to = int(inp[1])-1; for i in range(0,totNums): if i!=fr and i!=to: dp[i][fr] = dp[i][to] = (dp[i][fr] + dp[i][to]) / 2; dp[fr][i] = dp[to][i] = (dp[fr][i] + dp[to][i]) / 2; dp[fr][to] = dp[to][fr] = (dp[fr][to] + dp[to][fr]) / 2; ans = 0.0 for i in range(0,totNums): for j in range(i+1,totNums): ans += dp[i][j] print('%.10f'%ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef Ciel wants to put a fancy neon signboard over the entrance of her restaurant. She has not enough money to buy the new one so she bought some old neon signboard through the internet. Ciel was quite disappointed when she received her order - some of its letters were broken. But she realized that this is even better - she could replace each broken letter by any letter she wants. So she decided to do such a replacement that the resulting signboard will contain the word "CHEF" as many times as possible. We can model the signboard as a string S having capital letters from 'A' to 'Z', inclusive, and question marks '?'. Letters in the string indicate the intact letters at the signboard, while question marks indicate broken letters. So Ciel will replace each question mark with some capital letter and her goal is to get the string that contains as many substrings equal to "CHEF" as possible. If there exist several such strings, she will choose the lexicographically smallest one. Note 1. The string S = S1...SN has the substring "CHEF" if for some i we have SiSi+1Si+2Si+3 = "CHEF". The number of times "CHEF" is the substring of S is the number of those i for which SiSi+1Si+2Si+3 = "CHEF". Note 2. The string A = A1...AN is called lexicographically smaller than the string B = B1...BN if there exists K from 1 to N, inclusive, such that Ai = Bi for i = 1, ..., K-1, and AK < BK. In particular, A is lexicographically smaller than B if A1 < B1. We compare capital letters by their positions in the English alphabet. So 'A' is the smallest letter, 'B' is the second smallest letter, ..., 'Z' is the largest letter. -----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 only line of each test case contains a string S. -----Output----- For each test case, output a single line containing the content of the signboard Chef Ciel will come up with. That is you should output the lexicographically smallest string that could be obtained from the input string by replacing all its question marks by some capital letters and having as many substrings equal to "CHEF" as possible. -----Constraints----- - 1 ≤ T ≤ 2013 - 1 ≤ length of S ≤ 2013 - Each character in S is either a capital letter from 'A' to 'Z', inclusive, or the question mark '?'. -----Example----- Input: 5 ????CIELIS???E? ????CIELISOUR???F T?KEITE?SY ???????? ???C??? Output: CHEFCIELISACHEF CHEFCIELISOURCHEF TAKEITEASY CHEFCHEF AAACHEF -----Explanation ----- Example Case 1. Here the resulting string can have at most 2 substrings equal to "CHEF". For example, some possible such strings are: - CHEFCIELISACHEF - CHEFCIELISQCHEF - CHEFCIELISZCHEF However, lexicographically smallest one is the first one. Example Case 3. Here the resulting string cannot have "CHEF" as its substring. Therefore, you must simply output the lexicographically smallest string that can be obtained from the given one by replacing question marks with capital letters. 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 gcd import sys input=lambda : sys.stdin.readline().strip() c=lambda x: 10**9 if(x=="?") else int(x) def main(): for _ in range(int(input())): s=list(input())[::-1] l=['F','E','H','C'] i=0 while(i<len(s)): if(i+3<len(s)): f=True for j in range(i,i+4): if(l[j-i]==s[j] or s[j]=='?'): pass else: f=False break if(f): for j in range(i,i+4): s[j]=l[j-i] if(s[i]=="?"): s[i]='A' else: if(s[i]=="?"): s[i]="A" i+=1 print(*s[::-1],sep='') main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number a_{i} written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112. He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112 = 1192 × 11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there. Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways. Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353. -----Input----- Input data contains multiple test cases. The first line of the input data contains an integer t — the number of test cases (1 ≤ t ≤ 100). The descriptions of test cases follow. Each test is described by two lines. The first line contains an integer n (1 ≤ n ≤ 2000) — the number of cards in Borya's present. The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — numbers written on the cards. It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000. -----Output----- For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353. -----Example----- Input 4 2 1 1 3 1 31 12 3 12345 67 84 9 1 2 3 4 5 6 7 8 9 Output 2 2 2 31680 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python mod = 998244353 f0 = [ [0 for i in range(11)] for j in range(2010) ] f1 = [ [0 for i in range(11)] for j in range(2010) ] fac = [0 for i in range(2010)] tab = [0 for i in range(11)] C = [ [0 for i in range(2010)] for j in range(2010) ] def Init() : fac[0] = 1 for i in range(2010) : if i > 0 : fac[i] = fac[i - 1] * i % mod C[i][0] = 1 for j in range(1, 2010) : C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod def len(x) : res = 0 while x > 0 : res += 1 x = x // 10 return res def solve() : n = int(input()) f0[0][0] = f1[0][0] = 1 a = list(map(int, input().split())) c0, c1 = 0, 0 s0, s1 = 0, 0 for nu in a : m = nu % 11 if len(nu) & 1 : c1 += 1 s1 += m for i in range(11) : f1[c1][i] = 0 for i in range(c1 - 1, -1, -1) : for j in range(11) : if f1[i][j] == 0 : continue f1[i + 1][(j + m) % 11] += f1[i][j] f1[i + 1][(j + m) % 11] %= mod else : c0 += 1 s0 += m for i in range(11) : f0[c0][i] = 0 for i in range(c0 - 1, -1, -1) : for j in range(11) : if f0[i][j] == 0 : continue f0[i + 1][(j + m) % 11] += f0[i][j] f0[i + 1][(j + m) % 11] %= mod s1 %= 11 s0 %= 11 part = c1 // 2 for i in range(11) : tab[i] = 0 for i in range(11) : tab[(i + i + 11 - s1) % 11] = f1[c1 - part][i] for i in range(11) : tab[i] = tab[i] * fac[part] % mod * fac[c1 - part] % mod ans = 0 if c1 == 0 : ans = f0[c0][0] * fac[c0] elif c0 == 0 : ans = tab[0] else : for i in range(c0 + 1) : for j in range(11) : if f0[i][j] == 0 : continue # print(f0[i][j], tab[(j + j + 11 - s0) % 11] \ # , fac[i] % mod * fac[c0 - i] % mod, C[j + (c1 - part) - 1][(c1 - part) - 1] % mod * C[part + c0 - i][part] % mod ) ans = ( ans \ + fac[i] % mod * fac[c0 - i] % mod \ * f0[i][j] * tab[(j + j + 11 - s0) % 11] % mod \ * C[i + (c1 - part) - 1][(c1 - part) - 1] % mod \ * C[part + c0 - i][part] ) % mod print(ans) Init() T = int(input()) for ttt in range(T) : solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Berland year consists of $m$ months with $d$ days each. Months are numbered from $1$ to $m$. Berland week consists of $w$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $w$ days. A pair $(x, y)$ such that $x < y$ is ambiguous if day $x$ of month $y$ is the same day of the week as day $y$ of month $x$. Count the number of ambiguous pairs. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of testcases. Each of the next $t$ lines contains three integers $m$, $d$ and $w$ ($1 \le m, d, w \le 10^9$) — the number of months in a year, the number of days in a month and the number of days in a week. -----Output----- Print $t$ integers — for each testcase output the number of pairs $(x, y)$ such that $x < y$ and day $x$ of month $y$ is the same day of the week as day $y$ of month $x$. -----Example----- Input 5 6 7 4 10 7 12 12 30 7 1 1 1 3247834 10298779 625324 Output 6 9 5 0 116461800 -----Note----- Here are the pairs for the first test case: $$ 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 readlines = sys.stdin.readlines ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def gcd(a, b): while b: a, b = b, a%b return a def solve(): m, d, w = nm() g = w // gcd(d-1, w) c = min(m, d) v = c // g ans = v * (v - 1) // 2 * g ans += (c - g * v) * v print(ans) return # solve() T = ni() for _ in range(T): solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is interested to solve series problems. Chef wants to solve a series problem but he can't solve it till now.Can you help Chef to solve the series problem? - In series problem, the series goes as follows 1,9,31,73,141 . . . . . . . . Your task is to find the Nth term of series. For larger value of $N$ answer becomes very large, So your output should be performed $N$th term modulo 1000000007 ($10^9+7$ ). -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single integer $N$. -----Output:----- For each testcase, output in a single line answer i.e. The $N$th term of series modulo 1000000007. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 10^9$ -----Sample Input:----- 2 8 10 -----Sample Output:----- 561 1081 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 try: for t in range(int(input())): n=int(input()) ans=n*n*n+((n-1)**2) if ans<=10**9+7: print(ans) else: print(ans)%(10**9+7) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits. -----Input----- You are given a string consisting of 6 characters (all characters are digits from 0 to 9) — this string denotes Luba's ticket. The ticket can start with the digit 0. -----Output----- Print one number — the minimum possible number of digits Luba needs to replace to make the ticket lucky. -----Examples----- Input 000000 Output 0 Input 123456 Output 2 Input 111000 Output 1 -----Note----- In the first example the ticket is already lucky, so the answer is 0. In the second example Luba can replace 4 and 5 with zeroes, and the ticket will become lucky. It's easy to see that at least two replacements are required. In the third example Luba can replace any zero with 3. It's easy to see that at least one replacement is required. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python x=int(input()) def s(a): r=0 while a>0: r+=a%10 a//=10 return r def d(a,b): r=0 for i in range(6): if a%10!=b%10: r += 1 a//=10 b//=10 return r c=6 for i in range(1000000): if s(i%1000)==s(i//1000): c=min(c,d(x,i)) print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ivan is collecting coins. There are only $N$ different collectible coins, Ivan has $K$ of them. He will be celebrating his birthday soon, so all his $M$ freinds decided to gift him coins. They all agreed to three terms: Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $L$ coins from gifts altogether, must be new in Ivan's collection. But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms. -----Input----- The only line of input contains 4 integers $N$, $M$, $K$, $L$ ($1 \le K \le N \le 10^{18}$; $1 \le M, \,\, L \le 10^{18}$) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection. -----Output----- Print one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print "-1" (without quotes). -----Examples----- Input 20 15 2 3 Output 1 Input 10 11 2 4 Output -1 -----Note----- In the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new. In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m, k, l = map(int, input().split()) cnt = (k + l + m - 1) // m if cnt * m > n: print(-1) else: print(cnt) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a set of points in the 2D plane. You start at the point with the least X and greatest Y value, and end at the point with the greatest X and least Y value. The rule for movement is that you can not move to a point with a lesser X value as compared to the X value of the point you are on. Also for points having the same X value, you need to visit the point with the greatest Y value before visiting the next point with the same X value. So, if there are 2 points: (0,4 and 4,0) we would start with (0,4) - i.e. least X takes precedence over greatest Y. You need to visit every point in the plane. -----Input----- You will be given an integer t(1<=t<=20) representing the number of test cases. A new line follows; after which the t test cases are given. Each test case starts with a blank line followed by an integer n(2<=n<=100000), which represents the number of points to follow. This is followed by a new line. Then follow the n points, each being a pair of integers separated by a single space; followed by a new line. The X and Y coordinates of each point will be between 0 and 10000 both inclusive. -----Output----- For each test case, print the total distance traveled by you from start to finish; keeping in mind the rules mentioned above, correct to 2 decimal places. The result for each test case must be on a new line. -----Example----- Input: 3 2 0 0 0 1 3 0 0 1 1 2 2 4 0 0 1 10 1 5 2 2 Output: 1.00 2.83 18.21 For the third test case above, the following is the path you must take: 0,0 -> 1,10 1,10 -> 1,5 1,5 -> 2,2 = 18.21 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 def get_distance(x1,y1,x2,y2): return sqrt((x1-x2)**2 + (y1-y2)**2) T = int(input()) ans = [] for _ in range(T): blank = input() N = int(input()) C = [[] for i in range(10**4+1)] for i in range(N): x,y = [int(i) for i in input().split()] C[x].append(y) distance = 0 lastx = None lasty = None for i in range(10**4+1): if(C[i]!=[]): max_ci = max(C[i]) min_ci = min(C[i]) if(lastx!=None and lasty!=None): distance += get_distance(lastx,lasty,i,max_ci) distance += max_ci - min_ci lastx = i lasty = min_ci # ans.append(round(distance,2)) ans.append("{:.2f}".format(distance)) # ans.append(distance) for i in ans: print(i) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Voritex a big data scientist collected huge amount of big data having structure of two rows and n columns. Voritex is storing all the valid data for manipulations and pressing invalid command when data not satisfying the constraints. Voritex likes brute force method and he calls it as BT, he decided to run newly created BT engine for getting good result. At each instance when BT engine is outputting a newly created number Voritex calls it as BT number. Voritex is daydreaming and thinking that his engine is extremely optimised and will get an interview call in which he will be explaining the structure of BT engine and which will be staring from 1 and simultaneously performing $i$-th xor operation with $i$ and previously(one step before) obtained BT number. BT engine is outputting the $K$-th highest BT number in the first $N$ natural numbers. Chef : (thinking) I also want to create BT engine…….. -----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 line of each test case contains a two integers $N$ and $K$. -----Output:----- For each test case, print a single line containing integer $K$-th highest number else print -$1$ when invalid command pressed. -----Constraints----- - $1 \leq T \leq 100000$ - $1 \leq N \leq 100000$ - $1 \leq K \leq N$ -----Sample Input:----- 2 4 2 5 5 -----Sample Output:----- 2 0 -----EXPLANATION:----- For first valid constraints generating output as 0 2 1 5 1^1 first BT number is 0 2^0 second BT number is 2 3^2 third BT number is 1 4^1 fourth BT number is 5 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 import math import os import random import re import sys r = 100000 prev = 1 s = set() for i in range(1, r+1): now = i ^ prev s.add(now) prev = now s = list(s) t = int(input()) while t > 0: t -= 1 n, k = list(map(int, input().split())) if n > 3: if n % 2 == 0: size = (n//2) + 2 else: size = ((n-1)//2) + 2 else: size = n if size - k >= 0: print(s[size-k]) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Bandwidth of a matrix A is defined as the smallest non-negative integer K such that A(i, j) = 0 for |i - j| > K. For example, a matrix with all zeros will have its bandwith equal to zero. Similarly bandwith of diagonal matrix will also be zero. For example, for the below given matrix, the bandwith of this matrix is 2. 1 0 0 0 1 1 1 1 0 Bandwidth of the below matrix is 1. Bandwidth of the below matrix is 2. Bandwidth of the below matrix is also 2. You will be a given a binary matrix A of dimensions N × N. You are allowed to make following operation as many times as you wish (possibly zero or more). In a single operation, you can swap any two entries of the matrix. Your aim is to minimize the bandwidth of the matrix. Find the minimum bandwidth of the matrix A you can get after making as many operations of above type as you want. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follow. First line of each test case contains an integer N denoting the height/width of the matrix. Next N lines of each test case contain N space separated binary integers (either zero or one) corresponding to the entries of the matrix. -----Output----- For each test case, output a single integer corresponding to the minimum bandwidth that you can obtain. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 500 - 0 ≤ A(i, j) ≤ 1 -----Subtasks----- - Subtask #1 (40 points) : 1 ≤ N ≤ 100 - Subtask #2 (60 points) : original constraints -----Example----- Input: 6 2 0 0 0 0 2 1 0 0 1 2 1 0 1 0 2 1 0 1 1 3 1 0 0 0 1 1 1 1 0 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output: 0 0 0 1 1 3 -----Explanation----- Example case 1. The bandwidth of a matrix will all zero entries will be zero. This is the minimum bandwidth you can get, so there is no need of performing any swap operation. Example case 2. The bandwidth of a diagonal matrix will also be zero. Example case 3. You can make the given matrix a diagonal matrix by swapping A(2, 1) and A(2, 2), which will have zero bandwidth. Example case 4. You can not make swaps in any way that can reduce the bandwidth of this matrix. Bandwidth of this matrix is equal to 1, which is the minimum bandwidth that you can get. Example case 5. Bandwidth of the given matrix is 2. You can make it equal to be 1 by swapping A(3, 1) and A(3, 3), i.e. the matrix after the operation will look like 1 0 0 0 1 1 0 1 1 The bandwidth of this matrix is 1. Example case 6. The swap operations won't have any effect on the matrix. Its bandwidth 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 t = int(input()) for i in range(t): n = int(input()) A = [] for i in range(0, n): A.append([int(i) for i in input().split()]) ones = sum([sum(i) for i in A]) compare = n ans = 0 for i in range(0, n): if ones <= compare: ans = i break compare += 2*(n-1-i) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has an array A consisting of N integers (1-based indexing). He asks you to perform the following operation M times: for i = 2 to N: Ai = Ai + Ai-1 Your task is to find the xth element of the array (i.e., Ax) after performing the above operation M times. As the answer could be large, please output it modulo 109 + 7. -----Input----- - The first line of input contains an integer T denoting the number of test cases. - The first line of each test case contains three space-separated integers — N, x, and M — denoting the size of the array, index of the element you need to find, and the amount of times you need to repeat operation before finding the element, respectively. The second line contains N space-separated integers A1, A2, …, AN. -----Output----- For each test case, output a single line containing one integer: Ax modulo 109 + 7. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ x ≤ N ≤ 105 - 1 ≤ M ≤ 1018 - 1 ≤ Ai ≤ 1018 -----Subtasks-----Subtask 1 (8 points): - 1 ≤ x ≤ min{2, N}Subtask 2 (24 points): - 1 ≤ N * M ≤ 106Subtask 3 (68 points): No additional constraints -----Example----- Input: 2 3 2 3 1 2 3 3 3 3 1 2 3 Output: 5 15 -----Explanation----- Values in the array A: - Before the operations: [1, 2, 3] - After the first operation: [1, 3, 6] - After the second operation: [1, 4, 10] - After the third operation: [1, 5, 15] Since input file can be fairly large (about 8 MB), it's recommended to use fast I/O (for example, in C++, use scanf/printf instead of cin/cout). 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,x,m = map(int,input().split()) a = list(map(int,input().split())) for _ in range(m): for i in range(1,n): a[i] = a[i] + a[i-1] print(a[x-1]%(10**9+7)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: The game starts with n piles of stones indexed from 1 to n. The i-th pile contains s_{i} stones. The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of 0 stones does not count as a move. The player who is unable to make a move loses. Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game. In this modified version, no move can be made more than once on a pile. For example, if 4 stones are removed from a pile, 4 stones cannot be removed from that pile again. Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally. -----Input----- First line consists of a single integer n (1 ≤ n ≤ 10^6) — the number of piles. Each of next n lines contains an integer s_{i} (1 ≤ s_{i} ≤ 60) — the number of stones in i-th pile. -----Output----- Print a single line containing "YES" (without quotes) if Jon wins, otherwise print "NO" (without quotes) -----Examples----- Input 1 5 Output NO Input 2 1 2 Output YES -----Note----- In the first case, Sam removes all the stones and Jon loses. In second case, the following moves are possible by Sam: $\{1,2 \} \rightarrow \{0,2 \}, \{1,2 \} \rightarrow \{1,0 \}, \{1,2 \} \rightarrow \{1,1 \}$ In each of these cases, last move can be made by Jon to win the game as follows: $\{0,2 \} \rightarrow \{0,0 \}, \{1,0 \} \rightarrow \{0,0 \}, \{1,1 \} \rightarrow \{0,1 \}$ 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()) arr = [int(input()) for i in range(n)] b = [0 for i in range(n)] s = 0 for i in range(n): j = int((arr[i] << 1) ** 0.5) if j * (j + 1) > (arr[i] << 1): j -= 1 s ^= j if s != 0: print('NO') else: print('YES') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number x_{i} from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex x_{i}, then Greg wants to know the value of the following sum: $\sum_{v, u, v \neq u} d(i, v, u)$. Help Greg, print the value of the required sum before each step. -----Input----- The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line a_{ij} (1 ≤ a_{ij} ≤ 10^5, a_{ii} = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ n) — the vertices that Greg deletes. -----Output----- Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. -----Examples----- Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 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 array import array # noqa: F401 n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] aa = tuple([int(x) - 1 for x in input().split()]) ans = [''] * n for i in range(n-1, -1, -1): x = aa[i] for a in range(n): for b in range(n): if matrix[a][b] > matrix[a][x] + matrix[x][b]: matrix[a][b] = matrix[a][x] + matrix[x][b] val, overflow = 0, 0 for a in aa[i:]: for b in aa[i:]: val += matrix[a][b] if val > 10**9: overflow += 1 val -= 10**9 ans[i] = str(10**9 * overflow + val) print(' '.join(ans)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Doctor Kunj installed new software on cyborg Shresth. This software introduced Shresth to range minimum queries. Cyborg Shresth thought of T$T$ different problems in each of which you will be given an array A$A$ of length N$N$ and an array B$B$ of length M$M$. In each of these problems, you have to calculate: ∑mi=1∑mj=irangeMin(B[i],B[j])$\sum_{i=1}^m \sum_{j=i}^m rangeMin(B[i],B[j])$ Where rangeMin(i,j)$rangeMin(i,j)$ returns the minimum element in the range of indices i$i$ to j$j$ (both included) in array A$A$. It is given that array B$B$ consists of pairwise distinct elements and is in ascending order. -----Input Format:----- - First line will contain T$T$, the number of different problems Cyborg Shresth thought of. - Each problem's input data will be given in three different lines. - The first line will contain N$N$ and M$M$, the length of array A$A$ and B$B$ respectively. - The second line will contain N$N$ space separated positive integers, which form the array A$A$. - - The third line will contain M$M$ space separated positive integers, which form the array B$B$. -----Output Format:----- - For each different problem, print on a new line the answer to the problem, i.e. the value of ∑mi=1∑mj=irangeMin(B[i],B[j])$\sum_{i=1}^m \sum_{j=i}^m rangeMin(B[i],B[j])$ . -----Constraints:----- - 1≤T≤105$1 \leq T \leq {10}^5$ - 1≤N≤105$1 \leq N \leq {10}^5$ - 1≤M≤105$1 \leq M \leq {10}^5$ - 1≤A[i]≤109$1 \leq A[i] \leq 10^9$ - 1≤B[i]≤N$1 \leq B[i] \leq N$ It is guaranteed that the sum of N$N$ over all test cases does not exceed 106${10}^6$ . -----Sample Input:----- 1 7 3 10 3 7 9 1 19 2 1 4 6 -----Sample Output:----- 43 -----Explanation:----- For the given array A$A$, we have to calculate rangeMin(1,1)+rangeMin(1,4)+rangeMin(1,6)+rangeMin(4,4)+rangeMin(4,6)+rangeMin(6,6)$rangeMin(1,1) + rangeMin(1,4) + rangeMin(1,6) + rangeMin(4,4) + rangeMin(4,6) + rangeMin(6,6) $. This is equal to 10+3+1+9+1+19=43$10 + 3 + 1 + 9 + 1 +19 = 43$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def f(a,n): l,r,s1,s2 = [0]*n, [0]*n, [], [] for i in range(n): count = 1 while(len(s1)>0 and a[i]<s1[-1][0]): count += s1[-1][1] s1.pop() s1.append((a[i],count)) l[i] = count for i in range(n-1,-1,-1): count = 1 while(len(s2)>0 and a[i]<=s2[-1][0]): count += s2[-1][1] s2.pop() s2.append((a[i],count)) r[i] = count count = 0 for i in range(n): count += a[i]*l[i]*r[i] return count t = int(input()) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Naturally, the magical girl is very good at performing magic. She recently met her master wizard Devu, who gifted her R potions of red liquid, B potions of blue liquid, and G potions of green liquid. - The red liquid potions have liquid amounts given by r[1], ..., r[R] liters. - The green liquid potions have liquid amounts given by g[1], ..., g[G] liters. - The blue liquid potions have liquid amounts given by b[1], ..., b[B] liters. She want to play with the potions by applying magic tricks on them. In a single magic trick, she will choose a particular color. Then she will pick all the potions of the chosen color and decrease the amount of liquid in them to half (i.e. if initial amount of liquid is x, then the amount after decrement will be x / 2 where division is integer division, e.g. 3 / 2 = 1 and 4 / 2 = 2). Because she has to go out of station to meet her uncle Churu, a wannabe wizard, only M minutes are left for her. In a single minute, she can perform at most one magic trick. Hence, she can perform at most M magic tricks. She would like to minimize the maximum amount of liquid among all of Red, Green and Blue colored potions. Formally Let v be the maximum value of amount of liquid in any potion. We want to minimize the value of v. Please help her. -----Input----- First line of the input contains an integer T denoting the number of test cases. Then for each test case, we have four lines. The first line contains four space separated integers R, G, B, M. The next 3 lines will describe the amount of different color liquids (r, g, b), which are separated by space. -----Output----- For each test case, print a single integer denoting the answer of the problem. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ R, G, B, M ≤ 100 - 1 ≤ r[i], g[i], b[i] ≤ 10^9 -----Example----- Input: 3 1 1 1 1 1 2 3 1 1 1 1 2 4 6 3 2 2 2 1 2 3 2 4 6 8 Output: 2 4 4 -----Explanation----- Example case 1. Magical girl can pick the blue potion and make its liquid amount half. So the potions will now have amounts 1 2 1. Maximum of these values is 2. Hence 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 import math import heapq def half(n): return n//2 def main(arr,m): a,b,c=arr while m!=0: s=max(a,b,c) if s==a: a=half(a) elif s==b: b=half(b) else: c=half(c) m-=1 return max(a,b,c) for i in range(int(input())): r,g,b,m=list(map(int,input().split())) arr=[] for j in range(3): c=max(list(map(int,input().split()))) arr.append(c) print(main(arr,m)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers $d, m$, find the number of arrays $a$, satisfying the following constraints: The length of $a$ is $n$, $n \ge 1$ $1 \le a_1 < a_2 < \dots < a_n \le d$ Define an array $b$ of length $n$ as follows: $b_1 = a_1$, $\forall i > 1, b_i = b_{i - 1} \oplus a_i$, where $\oplus$ is the bitwise exclusive-or (xor). After constructing an array $b$, the constraint $b_1 < b_2 < \dots < b_{n - 1} < b_n$ should hold. Since the number of possible arrays may be too large, you need to find the answer modulo $m$. -----Input----- The first line contains an integer $t$ ($1 \leq t \leq 100$) denoting the number of test cases in the input. Each of the next $t$ lines contains two integers $d, m$ ($1 \leq d, m \leq 10^9$). Note that $m$ is not necessary the prime! -----Output----- For each test case, print the number of arrays $a$, satisfying all given constrains, modulo $m$. -----Example----- Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 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): d, m = list(map(int, input().split())) d += 1 out = 1 curr = 2 while curr < d: out *= (curr // 2) + 1 out %= m curr *= 2 out *= (d - curr // 2 + 1) print((out - 1) % m) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price. At every moment of time, every SELL offer has higher price than every BUY offer. In this problem no two ever existed orders will have the same price. The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below. [Image] The presented order book says that someone wants to sell the product at price $12$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $10$. There are two possible actions in this orderbook: Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever. It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL $20$" if there is already an offer "BUY $20$" or "BUY $25$" — in this case you just accept the best BUY offer. You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: "ADD $p$" denotes adding a new order with price $p$ and unknown direction. The order must not contradict with orders still not removed from the order book. "ACCEPT $p$" denotes accepting an existing best offer with price $p$ and unknown direction. The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo $10^9 + 7$. If it is impossible to correctly restore directions, then output $0$. -----Input----- The first line contains an integer $n$ ($1 \le n \le 363\,304$) — the number of actions in the log. Each of the next $n$ lines contains a string "ACCEPT" or "ADD" and an integer $p$ ($1 \le p \le 308\,983\,066$), describing an action type and price. All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet. -----Output----- Output the number of ways to restore directions of ADD actions modulo $10^9 + 7$. -----Examples----- Input 6 ADD 1 ACCEPT 1 ADD 2 ACCEPT 2 ADD 3 ACCEPT 3 Output 8 Input 4 ADD 1 ADD 2 ADD 3 ACCEPT 2 Output 2 Input 7 ADD 1 ADD 2 ADD 3 ADD 4 ADD 5 ACCEPT 3 ACCEPT 5 Output 0 -----Note----- In the first example each of orders may be BUY or SELL. In the second example the order with price $1$ has to be BUY order, the order with the price $3$ has to be SELL order. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import heapq n = int(input()) buy = [] # negative sell = [] unknown = [] res = 1 for i in range(n): cmd, amount = input().strip().split() amount = int(amount) if cmd == 'ADD': if sell and sell[0] < amount: heapq.heappush(sell, amount) elif buy and -buy[0] > amount: heapq.heappush(buy, -amount) else: unknown.append(amount) else: if (sell and amount > sell[0]) or (buy and amount < -buy[0]): print(0) return if sell and amount == sell[0]: heapq.heappop(sell) elif buy and amount == -buy[0]: heapq.heappop(buy) else: res = res * 2 % 1000000007 for x in unknown: if x < amount: heapq.heappush(buy, -x) elif x > amount: heapq.heappush(sell, x) unknown = [] res = res * (len(unknown) + 1) % 1000000007 print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In a bizarre game of chess ,knight was so drunk, that instead of his usual move he started walking straight. In every move Knight jumps on 2n steps forward (n is number of block that he had travelled so far from starting) but after that he has to take either 1 step forward or backward. Now the Knight needs to get to position X so King (i.e. You) needs to decide the order of his backward or forward step in such a way that he can reach its destination in minimum number of steps. Remember he always travels in a straight line and the length of the board is infinite. -----Input----- The first line of the input contains an integer T denoting the number of test cases, for each test case enter value X ( i.e. destination) Note : initially knight is at n = 1. -----Output----- For each test case the output should be string of numbers 1 & 2 where 1 denotes backward step and 2 denote the forward step Note : for no solution print 0. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ X ≤ 10^10 -----Example----- Input: 2 17 10 Output: 2111 0 -----Explanation----- Case 1 : starting from n = 1 , knight moves to n = 3 ('2') , 5 ('1') , 9 ('1') , 17 ('1') i.e. string printed is 2 1 1 1 Case 2 : no solution is possible 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 log,pow n=int(input()) a=[] for i in range(n): no=int(input()) if(no%2==0): a.append("0") elif(no==1): a.append("1") elif(no==3): a.append("3") else: s="2" lv=int(log(no,2)) clv=1 cno=3 while(cno!=no): if(no<cno*pow(2,lv-clv)): s=s+"1" clv=clv+1 cno=(2*cno)-1 else: s=s+"2" clv=clv+1 cno=(2*cno)+1 a.append(s) for i in a: print(i) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef wants to serve mankind by making people immortal by preparing a dish, a dish of life - a dish with the best taste in the universe, one with the smell and splash of fresh water flowing down the springs of the mountain, one with the smell of the best lily flowers of the garden, one that has contained the very essence of life in a real sense. This dish will contain K ingredients that are found only in remote islands amid mountains. For sake of convenience, we enumerate the ingredients by the integers from 1 to K, both inclusive. There are N islands and each of them offers some ingredients. Chef being a little child did not know how to collect the ingredients for the recipe. He went to all the islands and bought all the ingredients offered in each island. Could he possibly have saved some time by skipping some island? If it was not possible for Chef to collect the required ingredients (i.e. all the K ingredients), output "sad". If it was possible for him to skip some islands, output "some", otherwise output "all". -----Input----- First line of the input contains an integer T denoting number of test cases. The description of T test cases follow. The first line of each test case contains two space separated integers N, K. The i-th of the next lines will contain first an integer Pi, denoting the number of ingredients grown in the i-th island, followed by Pi distinct integers in the range [1, K]. All the integers are space separated. -----Output----- For each test case, output a single line containing one of the strings "sad", "all" or "some" (without quotes) according to the situation. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N, K ≤ 105 - 1 ≤ Pi ≤ K - Sum of Pi over all test cases ≤ 106 -----Subtasks----- Subtask #1 (30 points) - 1 ≤ N, K ≤ 50 Subtask #2 (30 points) - 1 ≤ K ≤ 50 Subtask #3 (40 points) - original constraints -----Example----- Input 3 3 4 3 1 2 3 2 1 3 2 1 2 2 3 3 1 2 3 2 1 3 2 3 2 1 2 2 1 3 Output sad some all -----Explanation----- Example 1. The ingredient 4 is not available in any island, so Chef can't make the dish of life. Hence, the answer is "sad". Example 2. Chef can just go to the first island and collect all the three ingredients required. He does not need to visit the second island. So, the answer is "some". Example 3. Chef has to visit both the islands in order to obtain all the three ingredients. So, the answer is "all". 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,k = list(map(int,input().split())) array = [] tot = [] for _ in range(n): temp = list(map(int,input().split())) aa = temp[0] del(temp[0]) temp.sort() temp.insert(0,aa) array.append(temp) dic = {} array.sort(reverse=True) for i in array: del(i[0]) for i in range(1,k+1): dic[i] = False count = 0 for i in array: count += 1 # print(count,tot) for j in i: if(dic[j]==True): pass else: tot.append(j) dic[j]=True if(len(tot)==k): break if(len(tot)!=k): print("sad") elif(count!=n): print("some") else: print("all") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer d_{i}, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, d_{i} = - 1 or it's degree modulo 2 is equal to d_{i}. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. -----Input----- The first line contains two integers n, m (1 ≤ n ≤ 3·10^5, n - 1 ≤ m ≤ 3·10^5) — number of vertices and edges. The second line contains n integers d_1, d_2, ..., d_{n} ( - 1 ≤ d_{i} ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. -----Output----- Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. -----Examples----- Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 -----Note----- In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys n, m = list(map(int, sys.stdin.readline().split())) d = list(map(int, sys.stdin.readline().split())) gph = [[] for _ in range(n)] for _ in range(m): u, v = list(map(int, sys.stdin.readline().split())) u -= 1 v -= 1 gph[u].append((v, _)) gph[v].append((u, _)) t = -1 if d.count(1) % 2 == 1: if -1 not in d: print(-1) return t = d.index(-1) ans = [False] * m vis = [False] * n ed = [(-1, -1)] * n rets = [(d[u] == 1) or (u == t) for u in range(n)] stk = [[0, iter(gph[0])]] while len(stk) > 0: u = stk[-1][0] vis[u] = True try: while True: v, i = next(stk[-1][1]) if not vis[v]: ed[v] = (u, i) stk.append([v, iter(gph[v])]) break except StopIteration: p, e = ed[u] if p >= 0 and rets[u]: rets[p] = not rets[p] ans[e] = True stk.pop() pass print(ans.count(True)) print("\n".join([str(i+1) for i in range(m) if ans[i]])) #1231 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The campus has $m$ rooms numbered from $0$ to $m - 1$. Also the $x$-mouse lives in the campus. The $x$-mouse is not just a mouse: each second $x$-mouse moves from room $i$ to the room $i \cdot x \mod{m}$ (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the $x$-mouse is unknown. You are responsible to catch the $x$-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the $x$-mouse enters a trapped room, it immediately gets caught. And the only observation you made is $\text{GCD} (x, m) = 1$. -----Input----- The only line contains two integers $m$ and $x$ ($2 \le m \le 10^{14}$, $1 \le x < m$, $\text{GCD} (x, m) = 1$) — the number of rooms and the parameter of $x$-mouse. -----Output----- Print the only integer — minimum number of traps you need to install to catch the $x$-mouse. -----Examples----- Input 4 3 Output 3 Input 5 2 Output 2 -----Note----- In the first example you can, for example, put traps in rooms $0$, $2$, $3$. If the $x$-mouse starts in one of this rooms it will be caught immediately. If $x$-mouse starts in the $1$-st rooms then it will move to the room $3$, where it will be caught. In the second example you can put one trap in room $0$ and one trap in any other room since $x$-mouse will visit all rooms $1..m-1$ if it will start in any of these rooms. 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 gcd def powmod(a,b,m): a%=m r=1 while b: if b&1:r=r*a%m a=a*a%m b>>=1 return r def f(n): r=[] if (n&1)==0: e=0 while (n&1)==0:n>>=1;e+=1 yield (2,e) p=3 while n>1: if p*p>n:p=n if n%p: p+=2 continue e=1;n//=p while n%p==0:n//=p;e+=1 yield (p,e) p+=2 return r m,x=map(int,input().split()) p=2 r=[(1,1)] for p,e in f(m): assert e>=1 ord=p-1 assert powmod(x,ord,p)==1 for pi,ei in f(p-1): while ord % pi == 0 and powmod(x,ord//pi,p)==1: ord//=pi ords=[(1,1),(ord,p-1)] q=p for v in range(2,e+1): q*=p if powmod(x,ord,q)!=1:ord*=p assert powmod(x,ord,q)==1 ords.append((ord,q//p*(p-1))) r=[(a//gcd(a,c)*c,b*d) for a,b in r for c,d in ords] print(sum(y//x for x,y in r)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Prof. Sergio Marquina is a mathematics teacher at the University of Spain. Whenever he comes across any good question(with complexity k), he gives that question to students within roll number range i and j. At the start of the semester he assigns a score of 10 to every student in his class if a student submits a question of complexity k, his score gets multiplied by k. This month he gave M questions and he is wondering what will be mean of maximum scores of all the students. He is busy planning a tour of the Bank of Spain for his students, can you help him? -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains the first line of input, two integers N, M i.e. Number of students in the class and number of questions given in this month. - Next M lines contain 3 integers -i,j,k i.e. starting roll number, end roll number, and complexity of the question -----Output:----- - For each test case, output in a single line answer - floor value of Mean of the maximum possible score for all students. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N, M \leq 105$ - $1 \leq i \leq j \leq N$ - $1 \leq k \leq 100$ -----Sample Input:----- 1 5 3 1 3 5 2 5 2 3 4 7 -----Sample Output:----- 202 -----EXPLANATION:----- Initial score of students will be : [10,10,10,10,10] after solving question 1 scores will be: [50,50,50,10,10] after solving question 2 scores will be: [50,100,100,20,20] after solving question 1 scores will be: [50,100,700,140,20] Hence after all questions mean of maximum scores will (50+100+700+140+20)/5=202 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())): n,m=[int(x)for x in input().rstrip().split()] s=[] for p in range(n): s.append(10) for c in range(m): i,j,k=[int(x)for x in input().rstrip().split()] for q in range(i-1,j): s[q]=s[q]*k print(sum(s)//n) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Petr is organizing Petr Mitrichev Contest #11. The top N coders according to codechef ratings (excluding Petr himself) agreed to participate in the contest. The participants have been ranked from 0 to N-1 according to their ratings. Petr had asked each participant to choose a coder with rating higher than himself/ herself, whom he/she would like to be team-mates with, and the ith ranked coder's choice is stored as choice[i]. As expected, programmers turned out to be lazy, and only a few of them actually filled in their choices. If choice[i] = -1, then it means the ith coder was lazy and did not fill his/her choice. Of course, the top-ranked person (i.e., rank = 0), Gennady Korotkevich (obviously), despite clearly not being a lazy person, was not able to fill any choice, because he is the top ranked coder, so choice[0] is always equal to -1. Petr, being the organizer, had to undertake the arduous task of filling in the choices for the lazy participants. Unfortunately, he also got lazy and adopted the following random strategy: For each lazy person i (i.e., for all i > 0, such that choice[i] = -1), he flips an unbiased coin (i.e. with 1/2 probability it lands Heads, and with 1/2 probability it lands Tails). Notice that no coin is flipped for i=0, since Gennady is not lazy despite his choice being -1. If it lands Heads, he will not change the choice of this person. That is, he leaves choice[i] as -1. Otherwise, if it lands Tails, he will uniformly at random select one of the top i ranked participants as choice of ith person. That is, he sets choice[i] = j, where j is randomly and uniformly chosen from 0 to i-1, inclusive. After this process of filling the choice array, Petr is wondering about the maximum number of teams he can have such that all the valid choices are respected (i.e. if choice[i] = j and j != -1, then i and j should be in the same team). Petr now has to arrange for computers. As each team will need a computer, he wants to know the expected value of maximum number of teams. As he is too busy in organizing this contest, can you please help him? -----Input:----- The first line of input contains T, the number of test cases. Each test case contains 2 lines. The first line contains a single integer N. The second line contains N integers, which specify the choice array: choice[0], choice[1],..,choice[N-1]. -----Output:----- Each test case's output must be in a new line and must be 1 number which is the expected number of teams. Your answer should be within an absolute error of 10-6 from the correct answer. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 1000 - The sum of all the T Ns in one test file ≤ 5000 - -1 ≤ choice[i] ≤ i-1 , for all 0 ≤ i < N - choice[0] will be equal to -1, always -----Example----- Input: 1 5 -1 -1 1 2 1 Output: 1.5 -----Explanation:----- choice[2] = 1 implies 1 and 2 should be in the same team. choice[3] = 2 implies that 2 and 3 have to be in the same team. Therefore, 1, 2 and 3 have to be in the same team. Also, choice[4] = 1 implies that 1 and 4 have to be in the same team, which means that 1, 2, 3 and 4 — all have to be in the same team. The only lazy person is 1. So with probability 1/2, Petr leaves his choice unchanged, or with the remaining 1/2 probability, he assigns choice[1] = 0, as 0 is the only higher ranked person for 1. In the first case, you can get 2 teams: {0} and {1, 2, 3 ,4}. In the second case, because choice[1] = 0, 0 and 1 are forced to be in the same team, and hence {0, 1, 2, 3, 4} is the only possible team. Therefore, with 1/2 probability, number of teams = 1 and with another 1/2 probability, it is 2. Hence, expected number of teams = (1/2 * 1) + (1/2 * 2) = 1.5. 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 comb(n,r): f = math.factorial return f(n) / f(r) / f(n-r) t=int(input()) for i in range(1,t+1): n=int(input()) arr = list(map(int, input().split())) m=0 ans=0.0 for i in range(0,n): if (arr[i]==-1): m=m+1 for i in range(0,m): ans=ans+((m-i)*comb(m-1,m-1-i)) ans=ans/pow(2,m-1) print('{0:.7f}'.format(ans)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In the 2-D world of Flatland, the Circles were having their sports day and wanted to end it with a nice formation. So, they called upon Mr. Sphere from Spaceland for help. Mr Sphere decides to arrange the Circles in square formations. He starts with $N$ Circles and forms the largest possible square using these Circles. He then takes the remaining Circles and repeats the procedure. A square of side $S$ requires $S^2$ Circles to create. Find the number of squares he will be able to form at the end of the process. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single integer $N$. -----Output:----- For each testcase, output a single integer denoting the number of squares. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 1000$ -----Sample Input:----- 2 85 114 -----Sample Output:----- 2 4 -----EXPLANATION:----- Test case 1 : Mr Sphere forms a square of side 9 using 81 Circles and then forms a square of side 2 using the remaining 4. 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 for _ in range(int(input())): n=int(input()) c=0 while(n>0): i=int(math.sqrt(n)) c+=1 n=n-i**2 print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided to upsolve the following problem: You have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \frac{l + r - 1}{2}$, then if $r - l + 1$ is an even number and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$, then the pair is funny. In other words, $\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\oplus$ of elements of the right half. Note that $\oplus$ denotes the bitwise XOR operation. It is time to continue solving the contest, so Sasha asked you to solve this task. -----Input----- The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the size of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^{20}$) — array itself. -----Output----- Print one integer — the number of funny pairs. You should consider only pairs where $r - l + 1$ is even number. -----Examples----- Input 5 1 2 3 4 5 Output 1 Input 6 3 2 2 3 7 6 Output 3 Input 3 42 4 2 Output 0 -----Note----- Be as cool as Sasha, upsolve problems! In the first example, the only funny pair is $(2, 5)$, as $2 \oplus 3 = 4 \oplus 5 = 1$. In the second example, funny pairs are $(2, 3)$, $(1, 4)$, and $(3, 6)$. In the third example, there are no funny pairs. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) from collections import Counter as C n = ii() a = li() oe = [C(), C()] oe[1][0] = 1 x = 0 ans = 0 for i in range(n): x ^= a[i] ans += oe[i % 2][x] oe[i % 2][x] += 1 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Every college has a stud−max$stud-max$ buoy. JGEC$JGEC$ has its own Atul$Atul$ who loves to impress everyone with his smile. A presentation is going on at the auditorium where there are N$N$ rows of M$M$ chairs with people sitting on it. Everyone votes for Atul's presentation skills, but Atul is interested in knowing the maximum$maximum$ amount of vote that he receives either taking K$K$ people vertically$vertically$ or horizontally$horizontally$. Atul$Atul$, however, wants to finish up the presentation party soon, hence asks for your help so that he can wrap up things faster. -----Input:----- - First line will contain T$T$, number of test cases. Then the test cases follow. - Each testcase contains of a single line of input, three integers N$N$, M$M$ and K$K$. - N lines follow, where every line contains M numbers$numbers$ denoting the size of the sugar cube -----Output:----- For each test case, output in a single line the maximum votes Atul can get. -----Constraints----- - 1≤T≤$1 \leq T \leq $5 - 1≤N,M≤500$1 \leq N,M \leq 500$ - K≤min(N,M)$K \leq min(N,M)$ - 1≤numbers≤109$1 \leq numbers \leq 10^9$ -----Sample Input:----- 1 4 4 3 1 4 5 7 2 3 8 6 1 4 8 9 5 1 5 6 -----Sample Output:----- 22 -----EXPLANATION:----- If Atul starts counting votes from (1,4), then he can take the 3 consecutive elements vertically downwards and those are 7,6 and 9 which is the maximum sum possible. 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): q = input().split() n = int(q[0]) m = int(q[1]) k = int(q[2]) sumax = 0 b = [] for j in range(n): a = [int(k) for k in input().split()] b = b + [a] for j in range(n): su = 0 for x in range(k): su = su +b[j][x] if su > sumax: sumax = su for a in range(1, m-k+1): su = su - b[j][a-1] +b[j][k+a-1] if su > sumax: sumax = su for j in range(m): su = 0 for x in range(k): su = su + b[x][j] if su > sumax: sumax = su for a in range(1, n-k+1): su = su - b[a-1][j] + b[a+k-1][j] if su > sumax: sumax = su print(sumax) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation. For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a_1, a_2, ..., a_{n}. He also wrote a square matrix b of size n × n. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as b_{ij}) equals: the "bitwise AND" of numbers a_{i} and a_{j} (that is, b_{ij} = a_{i} & a_{j}), if i ≠ j; -1, if i = j. Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly. Help Polycarpus, given matrix b, restore the sequence of numbers a_1, a_2, ..., a_{n}, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 10^9. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100) — the size of square matrix b. Next n lines contain matrix b. The i-th of these lines contains n space-separated integers: the j-th number represents the element of matrix b_{ij}. It is guaranteed, that for all i (1 ≤ i ≤ n) the following condition fulfills: b_{ii} = -1. It is guaranteed that for all i, j (1 ≤ i, j ≤ n; i ≠ j) the following condition fulfills: 0 ≤ b_{ij} ≤ 10^9, b_{ij} = b_{ji}. -----Output----- Print n non-negative integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces. It is guaranteed that there is sequence a that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them. -----Examples----- Input 1 -1 Output 0 Input 3 -1 18 0 18 -1 0 0 0 -1 Output 18 18 0 Input 4 -1 128 128 128 128 -1 148 160 128 148 -1 128 128 160 128 -1 Output 128 180 148 160 -----Note----- If you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation. 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()) a=[] for i in range(n): a.append(list(map(int,input().split()))) ans = [0]*n for i in range(n): for j in range(n): if j!=i: ans[i] |= a[i][j] print(ans[i],end = ' ') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This problem is about sequences of positive integers $a_1,a_2,...,a_N$. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, $3,7,11,3$ is a subsequence of $6,3,11,5,7,4,3,11,5,3$ , but $3,3,7$ is not a subsequence of $6,3,11,5,7,4,3,11,5,3$ . A fully dividing sequence is a sequence $a_1,a_2,...,a_N$ where $a_i$ divides $a_j$ whenever $i < j$. For example, $3,15,60,720$ is a fully dividing sequence. Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence. Consider the sequence $2,3,7,8,14,39,145,76,320$ It has a fully dividing sequence of length $3$, namely $2,8,320$, but none of length $4$ or greater. Consider the sequence $2,11,16,12,36,60,71,17,29,144,288,129,432,993$. It has two fully dividing subsequences of length $5$, - $2,11,16,12,36,60,71,17,29,144,288,129,432,993$ and - $2,11,16,12,36,60,71,17,29,144,288,129,432,993$ and none of length $6$ or greater. -----Input:----- The first line of input contains a single positive integer $N$ indicating the length of the input sequence. Lines $2,...,N+1$ contain one integer each. The integer on line $i+1$ is $a_i$. -----Output:----- Your output should consist of a single integer indicating the length of the longest fully dividing subsequence of the input sequence. -----Constraints:----- - $1 \leq N \leq 10000$ - $1 \leq a_i \leq 1000000000$ -----Sample input 1:----- 9 2 3 7 8 14 39 145 76 320 -----Sample output 1:----- 3 -----Sample input 2:----- 14 2 11 16 12 36 60 71 17 29 144 288 129 432 993 -----Sample output 2:----- 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! n=int(input()) a=[] for i in range(n): x=int(input()) a.append(x) # print(a) ans=0 m=[1]*n for i in range(n): for j in range(i): if a[i]%a[j]==0: m[i]=max(m[i],m[j]+1) print(max(m)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef Ada is building a new restaurant in the following way: - First, $N$ points $X_1, X_2, \ldots, X_N$ are chosen on the $x$-axis. - Then, $N$ columns (numbered $1$ through $N$) are made. For simplicity, the columns are represented as vertical segments; for each valid $i$, the height of the $i$-th segment is $H_i$. - Ada assigns a column to each of the points $X_1, X_2, \ldots, X_N$ in an arbitrary way (each column must be assigned to exactly one point). - Finally, Ada constructs the roof of the restaurant, represented by a polyline with $N$ vertices. Let's denote the column assigned to the $i$-th point by $P_i$. For each valid $i$, the $i$-th of these vertices is $(X_i, H_{P_i})$, i.e. the polyline joins the tops of the columns from left to right. Ada wants the biggest restaurant. Help her choose the positions of the columns in such a way that the area below the roof is the biggest possible. Formally, she wants to maximise the area of the polygon whose perimeter is formed by the roof and the segments $(X_N, H_{P_N}) - (X_N, 0) - (X_1, 0) - (X_1, H_{P_1})$. Let $S$ be this maximum area; you should compute $2 \cdot S$ (it is guaranteed that $2 \cdot S$ is an integer). -----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 valid $i$, the $i$-th of these lines contains two space-separated integers $X_i$ and $H_i$. -----Output----- For each test case, print a single line containing one integer $2 \cdot S$. -----Constraints----- - $1 \le T \le 3 \cdot 10^5$ - $2 \le N \le 10^5$ - $0 \le X_1 < X_2 < \ldots < X_N \le 2 \cdot 10^9$ - $1 \le H_i \le 10^9$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $10^6$ -----Example Input----- 1 5 1 1 2 2 3 3 4 4 5 5 -----Example Output----- 27 -----Explanation----- 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 _ in range(t): n = int(input()) a = [] b = [] for i in range(n): x,y = list(map(int, input().split())) a.append(x) b.append(y) b.sort() xcor = [] xcor.append(a[1]-a[0]) xcor.append(a[n-1]-a[n-2]) for i in range(1,n-1): xcor.append(a[i+1]-a[i-1]) xcor.sort() ans = 0 #print(xcor) #print(b) for i in range(n): ans = ans + xcor[i]*b[i] print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef made $N$ pieces of cakes, numbered them $1$ through $N$ and arranged them in a row in this order. There are $K$ possible types of flavours (numbered $1$ through $K$); for each valid $i$, the $i$-th piece of cake has a flavour $A_i$. Chef wants to select a contiguous subsegment of the pieces of cake such that there is at least one flavour which does not occur in that subsegment. Find the maximum possible length of such a subsegment of cakes. -----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 $K$. - 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 maximum length of a valid subsegment. -----Constraints----- - $1 \le T \le 1,000$ - $1 \le N \le 10^5$ - $2 \le K \le 10^5$ - $1 \le A_i \le K$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $10^6$ -----Subtasks----- Subtask #1 (50 points): - $N \le 10^3$ - $K = 2$ - the sum of $N$ over all test cases does not exceed $10^4$ Subtask #2 (50 points): original constraints -----Example Input----- 2 6 2 1 1 1 2 2 1 5 3 1 1 2 2 1 -----Example Output----- 3 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): t= int(input()) while(t!=0): n,k = list(map(int , input().split())) arr = list(map(int, input().split())) freq = [0]*100001 k=k-1 st=0 end=0 currentCount=0 previousElement = 0 for i in range(n): freq[arr[i]]+=1 if(freq[arr[i]]==1): currentCount+=1 while(currentCount>k): freq[arr[previousElement]]-=1 if(freq[arr[previousElement]]==0): currentCount-=1 previousElement+=1 if(i-previousElement+1 >= end-st+1): end=i st=previousElement print(end-st+1) t=t-1 def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's call some positive integer classy if its decimal representation contains no more than $3$ non-zero digits. For example, numbers $4$, $200000$, $10203$ are classy and numbers $4231$, $102306$, $7277420000$ are not. You are given a segment $[L; R]$. Count the number of classy integers $x$ such that $L \le x \le R$. Each testcase contains several segments, for each of them you are required to solve the problem separately. -----Input----- The first line contains a single integer $T$ ($1 \le T \le 10^4$) — the number of segments in a testcase. Each of the next $T$ lines contains two integers $L_i$ and $R_i$ ($1 \le L_i \le R_i \le 10^{18}$). -----Output----- Print $T$ lines — the $i$-th line should contain the number of classy integers on a segment $[L_i; R_i]$. -----Example----- Input 4 1 1000 1024 1024 65536 65536 999999 1000001 Output 1000 1 0 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 #sys.stdin=open("data.txt") input=sys.stdin.readline # this math tutorial is boring classy=set() for i in range(19): for j in range(i): for k in range(j): for a in range(10): # a=0 for good measure for b in range(10): for c in range(10): what=a*10**i+b*10**j+c*10**k classy.add(what) li=sorted(classy) def counting(i): # return len([x for x in li if x <= i])+C lo=0 hi=len(li)-1 while lo<hi: mid=(lo+hi+1)//2 if li[mid]<=i: lo=mid else: hi=mid-1 return lo for _ in range(int(input())): a,b=map(int,input().split()) print(counting(b)-counting(a-1)) ```