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: Sereja have array A' that contain N integers. Now Sereja want to permute elements of the array, he want to use some permutation p, such that A[i] = A'[p[i]], where A - new array. Lets function f(A,i) = S - A[i] - A[i +1] - ... - A[j], where j is the maximum possible index, such that A[i] + A[i + 1] + ... + A[j] <= S, if A[i] > S, f(A, i) = S. Help Sereja to find such permutation p, such that (f(A, 1) + f(A, 2) + ... f(A, k))/k will be as low as possible. -----Input----- First line of input contain integer T - number of testcases. Next lines contain T testcases. First line of each testcase contain three integers N, k, S. Next line contain N integers - array A'. -----Output----- For each testcase output N numbers in one line - permutation p. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 2000 - 1 ≤ k ≤ N - 1 ≤ A'[i] ≤ 10^4 - 1 ≤ S ≤ 10^9 -----Example----- Input: 2 3 2 4 3 4 1 4 4 1 1 1 1 1 Output: 2 1 3 4 3 2 1 -----Scoring----- Suppose Sum will be sum of yours (f(A, 1) + f(A, 2) + ... f(A, k))/k per each testcase. Lets B will be the smallest such sum. Your score will be equal to B/Sum. Lower scores will earn more points. We have 20 official test files. You must correctly solve all test files to receive OK. During the contest, your overall score is the sum of the scores on the first 4 test files. After the contest, all solutions will be rescored by the sum of the scores on the rest 16 test files. Note, that public part of the tests may not contain some border cases. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Md. Khairullah Gaurab # SUST, CSE, 20th Batch # [email protected] test = int(input()); for i in range(test): N, S, K = list(map(int,input().split())); lis = list(map(int,input().split())); ans = [i+1 for i in range(N)] ; ans.sort(reverse=True); for j in range(N): print(ans[j],end=' '); print('') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ahmed Gafer failed to pass the test, but he got the job because of his friendship with Said and Shahhoud. After working in the kitchen for a while, he blew it. The customers didn't like the food anymore and one day he even burned the kitchen. Now the master Chef is very upset. Ahmed isn't useful anymore at being a co-Chef, so S&S decided to give him a last chance. They decided to give Ahmed a new job, and make him work as the cashier of the restaurant. Nevertheless, in order not to repeat their previous mistake, they decided to give him a little test to check if his counting skills are good enough for the job. The problem is as follows: Given a string A of lowercase English letters, Ahmad was asked to find the number of good substrings. A substring A[L, R] is good if: - The length of the substring is exactly 2 and AL = AR, OR - The length of the substring is greater than 2,AL = AR and the substring A[L + 1, R - 1] has only one distinct letter. Anyways, Ahmed struggled trying to find a solution for the problem. Since his mathematical skills are very poor as it turned out, he decided to cheat and contacted you asking for your help. Can you help him in this challenge? -----Input----- The first line of the input contains the integer T, indicating the number of test cases. Each of the following T lines, contains a string A. -----Output----- For each test case, output a single line containing a single number, indicating the number of good substrings. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ |A| ≤ 105 - It's guaranteed that the sum of |A| over all test cases doesn't exceed 5x105. -----Example----- Input: 2 a abba Output: 0 2 -----Explanation----- Example case 2. The good substrings of abba are: { bb } and { abba }. 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())): s=input() count=0 i=0 while i<len(s)-1: ch=s[i] j=i+1 while j<len(s) and s[j]==ch: j+=1 l=j-i if i!=0 and j!=len(s) and s[i-1]==s[j] : count+=1 count+=l*(l-1)//2 #print(s[i:j],count) i=j print(count) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Master Shifu is training Po to become The Dragon Warrior and as a final assignment he must obtain maximum deliciousness from dumplings. There are $N$ plates of dumplings in front of him with deliciousness $A_1, A_2, \ldots, A_N$, Po can choose any number of continuous plates of dumplings. The total deliciousness is the sum of deliciousness of all the chosen dumplings. What is the minimum number of plates he must choose so that total deliciousness is maximum possible? Note: Po must choose atleast one plate. -----Input:----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output:----- For each test case, print a single line containing one integer. -----Constraints----- - $1 \le T \le 10$ - $1 \le N \le 2 \cdot 10^5$ - $0 \le A_i \le 10^9$ -----Sample Input:----- 2 4 1 2 3 4 5 3 2 0 3 0 -----Sample Output:----- 4 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 N=int(input()) for _ in range(N): n=int(input()) arr=list(map(int,input().split()))[:n] count=0 last=0 for i in range(n): if(arr[i]!=0): break last=i count+=1 for i in arr[-1:last:-1]: if(i!=0): break count+=1 ans=n-count if(ans==0): print(1) else: print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire. After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings! To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names. Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's! Given the string $s$ representing Jeff's product name and the string $c$ representing his competitor's product name, find a way to swap at most one pair of characters in $s$ (that is, find two distinct indices $i$ and $j$ and swap $s_i$ and $s_j$) such that the resulting new name becomes strictly lexicographically smaller than $c$, or determine that it is impossible. Note: String $a$ is strictly lexicographically smaller than string $b$ if and only if one of the following holds: $a$ is a proper prefix of $b$, that is, $a$ is a prefix of $b$ such that $a \neq b$; There exists an integer $1 \le i \le \min{(|a|, |b|)}$ such that $a_i < b_i$ and $a_j = b_j$ for $1 \le j < i$. -----Input----- The first line of input contains a single integer $t$ ($1 \le t \le 1500$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $s$ and $c$ ($2 \le |s| \le 5000, 1 \le |c| \le 5000$). The strings $s$ and $c$ consists of uppercase English letters. It is guaranteed that the sum of $|s|$ in the input is at most $5000$ and the sum of the $|c|$ in the input is at most $5000$. -----Output----- For each test case, output a single line containing a single string, which is either the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $c$. In case there are many possible such strings, you can output any of them; three dashes (the string "---" without quotes) if it is impossible. -----Example----- Input 3 AZAMON APPLE AZAMON AAAAAAAAAAALIBABA APPLE BANANA Output AMAZON --- APPLE -----Note----- In the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE". It is impossible to improve the product's name in the second test case and satisfy all conditions. In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def solve(): s,c = input().split() # i,jでjが複数あるとき n = len(s) for i in range(n-1): prev = s[i] pos = i for j in range(i+1, n): if s[j]<prev: prev = s[j] pos = j elif s[j] == prev: pos = j if prev == s[i]: continue t = list(s) t[i], t[pos] = prev, s[i] s = "".join(t) break if s<c: print(s) else: print("---") t = int(input()) for i in range(t): solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The students of Codechef Middle School are visiting an amusement park. The children want to go on a ride, however, there is a minimum height requirement of $X$ cm. Determine if the children are eligible to go on the ride. Print "Yes" if they are eligible, "No" otherwise. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, two integers $H$ which is a child's height in cm and $X$ which is the minimum permissible height. -----Output:----- For each testcase, output in a single line $"Yes"$ or $"No"$. You cannot give your answer as "YeS", "YES", "yes" or any other variation. -----Constraints----- - $1 \leq T \leq 10^4$ - $50 \leq H \leq 200$ - $50 \leq X \leq 200$ -----Sample Input:----- 2 120 100 90 100 -----Sample Output:----- Yes No -----EXPLANATION:----- The first child has height more than minimum permissible height, so he can go on the ride while the other person cannot! 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())): h,x=map(int,input().split()) if(h>=x): print("Yes") else: print("No") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has two integer sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_M$. You should choose $N+M-1$ pairs, each in the form $(A_x, B_y)$, such that the sums $A_x + B_y$ are all pairwise distinct. It is guaranteed that under the given constraints, a solution always exists. If there are multiple solutions, you may find any one. -----Input----- - The first line of the input contains two space-separated integers $N$ and $M$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. - The third line contains $M$ space-separated integers $B_1, B_2, \ldots, B_M$. -----Output----- Print $N+M-1$ lines. Each of these lines should contain two space-separated integers $x$ and $y$ denoting that you chose a pair $(A_{x+1}, B_{y+1})$. -----Constraints----- - $1 \le N, M \le 2 \cdot 10^5$ - $|A_i| \le 10^9$ for each valid $i$ - $|B_i| \le 10^9$ for each valid $i$ - $A_1, A_2, \ldots, A_N$ are pairwise distinct - $B_1, B_2, \ldots, B_M$ are pairwise distinct -----Subtasks----- Subtask #1 (25 points): $1 \le N, M \le 10^3$ Subtask #2 (75 points): original constraints -----Example Input----- 3 2 10 1 100 4 3 -----Example Output----- 2 1 0 0 1 0 0 1 -----Explanation----- The chosen pairs and their sums are: - $A_3 + B_2 = 100+3 = 103$ - $A_1 + B_1 = 10+4 = 14$ - $A_2 + B_1 = 1+4 = 5$ - $A_1 + B_2 = 10+3 = 13$ Since all sums are distinct, this is a correct output. 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,m = map(int, input().split()) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) max1 = arr1.index(max(arr1)) min2 = arr2.index(min(arr2)) arr = [] for i in range(m): arr.append([max1, i]) for i in range(n): if i!=max1: arr.append([i , min2]) for i in arr: print(*i) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to $1$ meter movement in the south, north, west or east direction respectively). It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visited the first time), then the time of such movement is $5$ seconds. If he rolls along previously visited segment of a path (i.e., this segment of the path has been covered by his path before), then it takes $1$ second. Find the skier's time to roll all the path. -----Input----- The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. Each set is given by one nonempty string of the characters 'S', 'N', 'W', 'E'. The length of the string does not exceed $10^5$ characters. The sum of the lengths of $t$ given lines over all test cases in the input does not exceed $10^5$. -----Output----- For each test case, print the desired path time in seconds. -----Example----- Input 5 NNN NS WWEN WWEE NWNWS Output 15 6 16 12 25 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python DIR = {"N": (0, 1), "S": (0, -1), "W": (-1, 0), "E": (1, 0)} for t in range(int(input())): path = input() tracks = set() x, y = 0, 0 time = 0 for char in path: x1 = x + DIR[char][0] y1 = y + DIR[char][1] if (x, y, x1, y1) in tracks or (x1, y1, x, y) in tracks: time += 1 else: time += 5 tracks.add((x, y, x1, y1)) x, y = x1, y1 print(time) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has N subordinates. In order to complete a very important order he will choose exactly K of them. He can't choose less than K since it will be not enough to complete the order in time. On the other hand if he chooses more than K subordinates he can't control them during the operation. Help him to find the number of ways he can choose the team to complete this very important order. -----Input----- The first line contains a single positive integer T <= 100, the number of test cases. T test cases follow. The only line of each test case contains two integers N and K, where 0 <= N, K < 2^64. It is guaranteed that the answer will be less than 2^64. -----Output----- For each test case, output a single line containing the number of ways to choose the required team. -----Example----- Input: 3 2 1 3 3 10 5 Output: 2 1 252 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def nCr(n,k): if(k>n):return 0 k=min(k,n-k) num,den=1,1 for i in range(k): num*=(n-i) den*=(i+1) return num/den def Main(): for cases in range(int(input())): a,b=[int(x) for x in input().split()] print(nCr(a,b)) Main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given string $s$ of length $n$ consisting of 0-s and 1-s. You build an infinite string $t$ as a concatenation of an infinite number of strings $s$, or $t = ssss \dots$ For example, if $s =$ 10010, then $t =$ 100101001010010... Calculate the number of prefixes of $t$ with balance equal to $x$. The balance of some string $q$ is equal to $cnt_{0, q} - cnt_{1, q}$, where $cnt_{0, q}$ is the number of occurrences of 0 in $q$, and $cnt_{1, q}$ is the number of occurrences of 1 in $q$. The number of such prefixes can be infinite; if it is so, you must say that. A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd". -----Input----- The first line contains the single integer $T$ ($1 \le T \le 100$) — the number of test cases. Next $2T$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $-10^9 \le x \le 10^9$) — the length of string $s$ and the desired balance, respectively. The second line contains the binary string $s$ ($|s| = n$, $s_i \in \{\text{0}, \text{1}\}$). It's guaranteed that the total sum of $n$ doesn't exceed $10^5$. -----Output----- Print $T$ integers — one per test case. For each test case print the number of prefixes or $-1$ if there is an infinite number of such prefixes. -----Example----- Input 4 6 10 010010 5 3 10101 1 0 0 2 0 01 Output 3 0 1 -1 -----Note----- In the first test case, there are 3 good prefixes of $t$: with length $28$, $30$ and $32$. 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 ' '*t: n,x=map(int,input().split()) s=input() L=[0] for i in s: if i=='0':L.append(L[-1]+1) else:L.append(L[-1]-1) L.pop(0) k=L[-1] c=0 if x==0:c+=1 if k>0: for i in L: if i%k==x%k and i<=x:c+=1 print(c) elif k<0: for i in L: if i%k==x%k and i>=x:c+=1 print(c) else: for i in L: if i==x:c=-1 print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$). Find any such rectangular matrix of size $n \times m$ that satisfies all of the following conditions: each row of the matrix contains exactly $a$ ones; each column of the matrix contains exactly $b$ ones; all other elements are zeros. If the desired matrix does not exist, indicate this. For example, for $n=3$, $m=6$, $a=2$, $b=1$, there exists a matrix satisfying the conditions above: $$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$ -----Input----- The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then $t$ test cases follow. Each test case is described by four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$), where $n$ and $m$ are the sizes of the matrix, and $a$ and $b$ are the number of ones for rows and columns, respectively. -----Output----- For each test case print: "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or "NO" (without quotes) if it does not exist. To print the matrix $n \times m$, print $n$ rows, each of which consists of $m$ numbers $0$ or $1$ describing a row of the matrix. Numbers must be printed without spaces. -----Example----- Input 5 3 6 2 1 2 2 2 1 2 2 2 2 4 4 2 2 2 1 1 2 Output YES 010001 100100 001010 NO YES 11 11 YES 1100 1100 0011 0011 YES 1 1 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, m, a, b = list(map(int, input().split())) if a * n != b * m: print('NO') else: ar = [] for i in range(n): ar.append([0] * m) x, y = 0, a for i in range(n): if x < y: for j in range(x, y): ar[i][j] = 1 else: for j in range(x, m): ar[i][j] = 1 for j in range(y): ar[i][j] = 1 x += a y += a x %= m y %= m print('YES') for i in range(n): print(''.join(map(str, ar[i]))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K(odd) to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 3 5 7 -----Sample Output:----- 1 111 111 111 11111 11 11 1 1 1 11 11 11111 1111111 11 11 1 1 1 1 1 1 1 1 1 1 1 11 11 1111111 -----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 from sys import stdin, stdout from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque from heapq import merge, heapify, heappop, heappush, nsmallest from bisect import bisect_left as bl, bisect_right as br, bisect mod = pow(10, 9) + 7 mod2 = 998244353 def inp(): return stdin.readline().strip() def out(var, end="\n"): stdout.write(str(var)+"\n") def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end) def lmp(): return list(mp()) def mp(): return map(int, inp().split()) def smp(): return map(str, inp().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] def remadd(x, y): return 1 if x%y else 0 def ceil(a,b): return (a+b-1)//b def isprime(x): if x<=1: return False if x in (2, 3): return True if x%2 == 0: return False for i in range(3, int(sqrt(x))+1, 2): if x%i == 0: return False return True for _ in range(int(inp())): n = int(inp()) for i in range(n): for j in range(n): if i==0 or i==n-1 or j==0 or j==n-1 or i==j or i+j==n-1: print(1, end="") else: print(" ", end="") print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction. A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of queries. Next $n$ lines contain queries, one per line. Each line contains three integers $p$, $q$, and $b$ ($0 \le p \le 10^{18}$, $1 \le q \le 10^{18}$, $2 \le b \le 10^{18}$). All numbers are given in notation with base $10$. -----Output----- For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise. -----Examples----- Input 2 6 12 10 4 3 10 Output Finite Infinite Input 4 1 1 2 9 36 2 4 12 3 3 5 4 Output Finite Finite Finite Infinite -----Note----- $\frac{6}{12} = \frac{1}{2} = 0,5_{10}$ $\frac{4}{3} = 1,(3)_{10}$ $\frac{9}{36} = \frac{1}{4} = 0,01_2$ $\frac{4}{12} = \frac{1}{3} = 0,1_3$ 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 binpow(a, n, p): res = 1 while n > 0: if n % 2 == 1: res = (res * a) % p a = (a * a) % p n >>= 1 return res def main(): result = [] t = int(sys.stdin.readline()) for line in sys.stdin.readlines(): p, q, b = list(map(int, line.split())) for i in range(6): b = (b * b) % q result.extend(list("Finite\n" if (p * b) % q == 0 else list("Infinite\n"))) sys.stdout.write("".join(result)) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. [Image] Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows: let starting_time be an array of length n current_time = 0 dfs(v): current_time = current_time + 1 starting_time[v] = current_time shuffle children[v] randomly (each permutation with equal possibility) // children[v] is vector of children cities of city v for u in children[v]: dfs(u) As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)). Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help. -----Input----- The first line of input contains a single integer n (1 ≤ n ≤ 10^5) — the number of cities in USC. The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} < i), where p_{i} is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered p_{i} and i in USC. -----Output----- In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10^{ - 6}. -----Examples----- Input 7 1 2 1 1 4 4 Output 1.0 4.0 5.0 3.5 4.5 5.0 5.0 Input 12 1 1 2 2 4 4 3 3 1 10 8 Output 1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) pos,tree,ans,sz = list(map(int,input().split())) if n > 1 else [],[],[],[] for i in range(n): tree.append([]) ans.append(0.0) sz.append(0) for i in range(n-1): tree[pos[i]-1].append(i+1) for i in range(n)[::-1]: sz[i] = 1 for to in tree[i]: sz[i] += sz[to] for i in range(n): for to in tree[i]: ans[to] = ans[i] + 1 + (sz[i]-1-sz[to]) * 0.5 st = lambda i: str(i+1) print(' '.join(list(map(st,ans)))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef likes prime numbers. However, there is one thing he loves even more. Of course, it's semi-primes! A semi-prime number is an integer which can be expressed as a product of two distinct primes. For example, $15 = 3 \cdot 5$ is a semi-prime number, but $1$, $9 = 3 \cdot 3$ and $5$ are not. Chef is wondering how to check if an integer can be expressed as a sum of two (not necessarily distinct) semi-primes. Help Chef with this tough task! -----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 integer $N$. -----Output----- For each test case, print a single line containing the string "YES" if it is possible to express $N$ as a sum of two semi-primes or "NO" otherwise. -----Constraints----- - $1 \le T \le 200$ - $1 \le N \le 200$ -----Example Input----- 3 30 45 62 -----Example Output----- YES YES NO -----Explanation----- Example case 1: $N=30$ can be expressed as $15 + 15 = (3 \cdot 5) + (3 \cdot 5)$. Example case 2: $45$ can be expressed as $35 + 10 = (5 \cdot 7) + (2 \cdot 5)$. Example case 3: $62$ cannot be expressed as a sum of two semi-primes. 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 sys n = 201 v = [0 for i in range(n + 1)] def gen(): for i in range(1, n + 1): v[i] = i countDivision = [0 for i in range(n + 1)] for i in range(n + 1): countDivision[i] = 2 for i in range(2, n + 1, 1): if (v[i] == i and countDivision[i] == 2): for j in range(2 * i, n + 1, i): if (countDivision[j] > 0): v[j] = int(v[j] / i) countDivision[j] -= 1 try: t=int(sys.stdin.readline()) for _ in range(t): gen() x=int(sys.stdin.readline()) flag=0 for i in range(2,x//2+1): if v[i]==1 and v[x-i]==1: flag=1 #print(i,x-i) if flag==1: print("YES") else: print("NO") except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is making Window frames for his new office, for this he has n wooden Logs whose lengths are l1, l2, … ln respectively. Chef Doesn’t want to break any logs or Stick 2 or more logs together. To make a h × w Window Frame, he needs two Logs with lengths equal h and two with length . The Chef wants as much sunlight in as possible and for it he has decided to make from the available logs as many frames as possible. Help him in finding the number of window Frames that he can make. Note : Chef do not need to use all the logs Input: The first line of the input contains a single integer T denoting the number of test cases. The description of each test case follows :. The first line of each test case contains a single integer n the number of wooden logs. The second line contains n space-separated integers l1,l2,l3….ln The length of each wooden log Output: The only line in Output Contains single Integer denoting the maximum possible number of Wooden Frames. Constraints: 1 ≤ T ≤ 10 1 ≤ n ≤ 100 1 ≤ li ≤ 10000 Example Input: 2 4 1 2 1 2 8 1 2 1 3 4 1 5 6 Example Output: 1 0 Explanation : First Case : We can build a frame of dimension 1x2 as two logs of each dimension are available. Second Case : We can’t build any Frame as no logs of length except 1 have more than one piece. 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()) j=0 while j<t: n=int(input()) lst=list(map(int,input().split())) s=set() d=list() for i in lst: if i in s: s.remove(i) d.append(i) else: s.add(i) x=len(d) if x%2==0: print(x//2) else: print((x-1)//2) j+=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mandarin chinese , Russian and Vietnamese as well. You are given a grid with $n$ rows and $m$ columns. Each cell of this grid can either be empty or it contains one particle. It can never contain more than one particle. Let's denote the cell in the $i$-th row and $j$-th column by $(i, j)$, with the top left corner being $(0, 0)$. From a cell $(i, j)$, a particle could move in one of the following four directions: - to the left, i.e. to the cell $(i, j - 1)$ - to the right, i.e. to the cell $(i, j + 1)$ - up, i.e. to the cell $(i - 1, j)$ - down, i.e. to the cell $(i + 1, j)$ It is not possible for a particle to move to a cell that already contains a particle or to a cell that does not exist (leave the grid). It is possible to apply a force in each of these directions. When a force is applied in a given direction, all particles will simultaneously start moving in this direction as long as it is still possible for them to move. You are given a sequence of forces. Each subsequent force is applied only after all particles have stopped moving. Determine which cells of the grid contain particles after all forces from this sequence are applied in the given order. -----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$. - $n$ lines describing the initial grid follow. For each $i$ ($1 \le i \le n$), the $i$-th of these lines contains a binary string with length $m$ describing the $i$-th row of the grid. For each $j$ ($1 \le j \le m$), if the $j$-th character of this string is '1', then the cell $(i, j)$ contains a particle, and if it is '0', then the cell $(i, j)$ is empty. - The last line contains a single string $S$ describing the sequence of applied forces. Each character of this string corresponds to applying a force in some direction; forces applied in the directions left, right, up, down correspond to characters 'L', 'R', 'U', 'D' respectively. -----Output----- For each test case, print $n$ lines each containing a binary string of length $m$, describing the resulting grid (after all the forces are applied) in the same format as the input grid. -----Constraints----- - $1 \le T \le 200$ - $1 \le n, m \le 100$ - $1 \le |S| \le 2 \cdot 10^4$ -----Subtasks----- Subtaks #1 (30 points): - $1 \le T \le 10$ - $1 \le n, m \le 10$ - $1 \le |S| \le 100$ Subtask #2 (70 points): Original constraints -----Example Input----- 3 4 4 1010 0010 1001 0100 LRDU 4 3 000 010 001 101 LRL 3 2 01 10 00 D -----Example Output----- 0011 0011 0001 0001 000 100 100 110 00 00 11 -----Explanation----- Example case 1: The initial grid is: 1010 0010 1001 0100 After applying the first force (in the direction "L", i.e. to the left), the grid is: 1100 1000 1100 1000 After applying the second force (in the direction "R"), the grid is: 0011 0001 0011 0001 After applying the third force (in the direction "D"), the grid is: 0001 0001 0011 0011 After applying the fourth force (in the direction "U"), the final grid is: 0011 0011 0001 0001 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): for _ in range(int(input())): rows,column = map(int,input().split()) arr = [] for i in range(rows): arr.append(list(input())) string = input() last = string[-1] operation = Find(string,last) for i in string[0]+operation: if i == "L": arr = Left(arr) if i == "R": arr = Right(arr) if i == "U": arr = Transpose(arr) arr = Left(arr) arr = Transpose(arr) if i == "D": arr = Transpose(arr) arr = Right(arr) arr = Transpose(arr) for i in arr: print(i) def Left(arr): for i in range(len(arr)): ans = arr[i].count("1") arr[i] = "1"*ans + (len(arr[i]) - ans)*"0" return arr def Right(arr): for i in range(len(arr)): ans = arr[i].count("1") arr[i] = (len(arr[i]) - ans)*"0"+"1"*ans return arr def Transpose(arr): ansss = [] ans = list(map(list, zip(*arr))) for i in ans: ass = i hello = "" for j in ass: hello += j ansss.append(hello) return ansss def Find(string,last): for i in string[-2::-1]: if last == "L": if i in ["D","U"]: last = i + last break if last == "R": if i in ["D","U"]: last = i + last break if last == "D": if i in ["L","R"]: last = i + last break if last == "U": if i in ["L","R"]: last = i + last break return last def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Consider all binary strings of length $m$ ($1 \le m \le 60$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $2^m$ such strings in total. The string $s$ is lexicographically smaller than the string $t$ (both have the same length $m$) if in the first position $i$ from the left in which they differ, we have $s[i] < t[i]$. This is exactly the way strings are compared in dictionaries and in most modern programming languages when comparing them in a standard way. For example, the string 01011 is lexicographically smaller than the string 01100, because the first two characters are the same, and the third character in the first string is less than that in the second. We remove from this set $n$ ($1 \le n \le \min(2^m-1, 100)$) distinct binary strings $a_1, a_2, \ldots, a_n$, each of length $m$. Thus, the set will have $k=2^m-n$ strings. Sort all strings of the resulting set in lexicographical ascending order (as in the dictionary). We number all the strings after sorting from $0$ to $k-1$. Print the string whose index is $\lfloor \frac{k-1}{2} \rfloor$ (such an element is called median), where $\lfloor x \rfloor$ is the rounding of the number down to the nearest integer. For example, if $n=3$, $m=3$ and $a=[$010, 111, 001$]$, then after removing the strings $a_i$ and sorting, the result will take the form: $[$000, 011, 100, 101, 110$]$. Thus, the desired median is 100. -----Input----- The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then, $t$ test cases follow. The first line of each test case contains integers $n$ ($1 \le n \le \min(2^m-1, 100)$) and $m$ ($1 \le m \le 60$), where $n$ is the number of strings to remove, and $m$ is the length of binary strings. The next $n$ lines contain $a_1, a_2, \ldots, a_n$ — distinct binary strings of length $m$. The total length of all given binary strings in all test cases in one test does not exceed $10^5$. -----Output----- Print $t$ answers to the test cases. For each test case, print a string of length $m$ — the median of the sorted sequence of remaining strings in the corresponding test case. -----Example----- Input 5 3 3 010 001 111 4 3 000 111 100 011 1 1 1 1 1 0 3 2 00 01 10 Output 100 010 0 1 11 -----Note----- The first test case is explained in the statement. In the second test case, the result after removing strings and sorting is $[$001, 010, 101, 110$]$. Therefore, the desired median is 010. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def read_int(): return int(input()) def read_ints(): return list(map(int, input().split(' '))) t = read_int() for case_num in range(t): n, m = read_ints() a = [] for i in range(n): a.append(int(input(), 2)) a.sort() k = 2 ** m - n ans = (k - 1) // 2 for ai in a: if ai <= ans: ans += 1 binary = '{:b}'.format(ans) print(binary.rjust(m, '0')) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A balanced parenthesis string is defined as follows: - The empty string is balanced - If P is balanced, (P) is also - If P and Q are balanced, PQ is also balanced You are given two even integers n$n$ and k$k$. Find any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$, or claim that no such string exists. -----Input----- - First line will contain T$T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line containing n$n$ and k$k$. -----Output----- For every testcase, print on a new line, any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$. If there doesn't exist any such string, print −1$-1$ instead. -----Constraints----- - 1≤T≤50000$1 \leq T \leq 50000$ - 2≤k≤n≤105$2 \leq k \leq n \leq 10^5$ - Sum of n$n$ over all testcases doesn't exceed 105$10^5$. - n$n$ and k$k$ are both even integers. -----Example Input----- 2 4 2 8 6 -----Example Output----- -1 (())(()) -----Explanation----- In the first testcase, the only balanced strings of length 4$4$ are (()) and ()(), both of which contain () as a substring. In the second testcase, (())(()) is a balanced string that doesn't contain any balanced substring of length 6$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 input(): return sys.stdin.readline().strip() for i in range(int(input())): n, k = map(int, input().split()) arr = [] if k == 2 or k == 4 or n % 2 != 0 or n == k: arr.append('-1') elif k % 2 != 0: for i in range(int(n / 2)): arr.append('(') for i in range(int(n / 2)): arr.append(')') elif int(n / (k - 2)) == 1: if (n - 2) % 4 == 0: for i in range(int((n - 2) / 4)): arr.append('(') for i in range(int((n - 2) / 4)): arr.append(')') arr.append('()') for i in range(int((n - 2) / 4)): arr.append('(') for i in range(int((n - 2) / 4)): arr.append(')') else: for i in range(int((n - 4) / 4)): arr.append('(') for i in range(int((n - 4) / 4)): arr.append(')') arr.append('(())') for i in range(int((n - 4) / 4)): arr.append('(') for i in range(int((n - 4) / 4)): arr.append(')') else: for i in range(int((n % (k - 2)) / 2)): arr.append('(') for i in range(int(n / (k - 2))): for j in range(int((k - 2) / 2)): arr.append('(') for j in range(int((k - 2) / 2)): arr.append(')') for i in range(int((n % (k - 2)) / 2)): arr.append(')') print("".join(arr)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Anmol gained a lot of weight last semester. So this semester, he decided to run everyday. There is a very long straight road starting at his hostel. There are N poles on the road - P1, P2, P3,..., PN on the road. All the poles lie on the same side of his hostel. The distance between Pi and his hostel is Di. For 1 ≤ i, j ≤ N, i < j implies Di < Dj Everyday, Anmol chooses a pole Pi to start running from. He keeps on running until he reaches Pi+K. Whenever he reaches a pole (other than the starting pole), he records the distance traveled since the last pole. You are given the distances recorded by him today. Your task is to find the number of distinct values of i such that i + K ≤ N and if he starts at Pi and end at Pi+K, he would end up having exactly the same record of distances (in the same order). -----Input----- - The first line of the input contains an integer T denoting the number of test cases. - The first line of each test case contains two space separated integers N and K. - The next line contains N space separated integers D1, D2,..., DN. - The next line contains K space separated integers representing the distances recorded by Anmol in the same order. . -----Output----- - For each test case, output a single line containing the answer for that test case. -----Constraints----- - 1 ≤ T ≤ 10 - 2 ≤ N ≤ 5 x 104 - 1 ≤ K < N - 1 ≤ Di ≤ 106 -----Subtasks----- -----Subtask #1 (20 points)----- - 1 ≤ N ≤ 1000 -----Subtask #2 (80 points)----- - Original constraints -----Example----- Input: 3 5 1 1 5 10 12 14 5 5 2 5 8 13 16 21 3 5 5 3 2 6 8 11 16 2 3 5 Output: 1 2 1 -----Explanation----- Example case 1. If he runs from P2 to P3, he will record (5) Example case 2. He can start at P1 or P3 Example case 3. He can start at P2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #code snippet reference:http://www.geeksforgeeks.org/searching-for-patterns-set    -2-kmp-algorithm/ def KMPMatch(pattern, string): M = len(pattern) N = len(string) nonlocal ans lps = [0]*M j = 0 LPSCompute(pattern, M, lps) i = 0 while i < N: if pattern[j] == string[i]: i+=1 j+=1 if j==M: ans+=1 j = lps[j-1] elif i < N and pattern[j] != string[i]: if j != 0: j = lps[j-1] else: i+=1 def LPSCompute(pattern, M, lps): len = 0 lps[0] i = 1 while i < M: if pattern[i]==pattern[len]: len+=1 lps[i] = len i+=1 else: if len!=0: len = lps[len-1] else: lps[i] = 0 i+=1 for _ in range(int(input())): n,k=list(map(int,input().split())) s=list(map(int,input().split())) pattern=list(map(int,input().split())) ans=0 string=[] for i in range(n-1): string.append(s[i+1]-s[i]) KMPMatch(pattern, string) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Naman owns a very famous Ice Cream parlour in Pune. He has a wide range of flavours with different pricing. Every flavour costs ₹ X per gram and quantity of each flavour in the parlour is indefinite. Now, Naman has received an order for a party wherein he is asked to prepare each Ice Cream with N number of flavours. He needs to prepare each Ice Cream of W grams and at the same time has to keep the cost minimum. Can you help him out? Note: If it is not possible to prepare such an Ice Cream, print “Not Possible”. -----Input:----- First line contains an integer T denoting the number of test cases. First line of every test case contains an integer N denoting the number of flavours. The second line of every test case by N space separated integers denoting the cost per gram of each flavour. Second line of every test case contains two space separated integers W and Y denoting the weight of Ice Cream in grams and the number of flavours to be used respectively. -----Output:----- For each test case, print the total cost of the Ice Cream in a single line. -----Constraints:----- 1 ≤ T ≤ 100 1 ≤ N,W,Y ≤ 40000 -----Example:-----Input: 2 5 4 6 8 1 10 10 3 2 1 2 1 2Output: 18 Not Possible -----Explanation:----- In the first test case to achieve the minimum cost, the Ice Cream will consist of 8 grams of flavour costing ₹1, 1 gram of flavour costing ₹4 and 1 gram of flavour costing ₹6. In the second test case it is not possible to make an ice-cream weighing 1 gram using 2 flavours. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python test = int(input()) for i in range(test): flavor = int(input()) rate = input() gaf = input() gaf = gaf.split() gaf = [int(x) for x in gaf] rate = rate.split() rate = [int(x) for x in rate] rate.sort() c = gaf[0] - gaf[1] sum = rate[0]*c t = True if gaf[0] < gaf[1]: t = False j = 0 while(j<gaf[1] and t): sum = sum + rate[j] j = j + 1 if t : print(sum) else: print("Not Possible") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Chef has a positive integer N. He can apply any of the following operations as many times as he want in any order: - Add 1 to the number N. - Take some digit of N and replace it by any non-zero digit. - Add any non-zero leading digit to N. Find the minimum number of operations that is needed for changing N to the lucky number. -----Input----- The first line contains a single positive integer T, the number of test cases. T test cases follow. The only line of each test case contains a positive integer N without leading zeros. -----Output----- For each T test cases print one integer, the minimum number of operations that is needed for changing N to the lucky number. -----Constraints----- 1 ≤ T ≤ 10 1 ≤ N < 10100000 -----Example----- Input: 3 25 46 99 Output: 2 1 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(0,int(input())): n=input().strip() x=n.count('4') y=n.count('7') print(len(n)-x-y) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It is an interesting exercise to write a program to print out all permutations of $1, 2, …, n$. However, since there are $6227020800$ permutations of $1, 2, …, 13$, it is unlikely that we would ever run this program on an input of size more than $10$. However, here is another interesting problem whose solution can also be used to generate permutations. We can order the permutations of $1, 2, …, n$ under the lexicographic (or dictionary) order. Here are the permutations of $1,2,3$ in lexicographic order: 123132213231312321123132213231312321 1 \, 2 \, 3 \quad 1 \, 3 \, 2 \quad 2 \, 1 \, 3 \quad 2 \, 3 \, 1 \quad 3 \, 1 \, 2 \quad 3 \, 2 \, 1 The problem we have is the following: given a permutation of $1,2, …, n$, generate the next permutation in lexicographic order. For example, for $2 3 1 4$ the answer is $2 3 4 1$. -----Input:----- The first line of the input contains two integers, $N$ and $K$. This is followed by $K$ lines, each of which contains one permutation of $1, 2,…,N$. -----Output:----- The output should consist of $K$ lines. Line $i$ should contain the lexicographically next permutation correponding to the permutation on line $i+1$ in the input. -----Constraints:----- - $1 \leq N \leq 1000$. - $1 \leq K \leq 10$. -----Sample input----- 3 2 3 1 2 2 3 1 -----Sample output----- 3 2 1 3 1 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 as mt # from collections import Counter # from itertools import permutations # from functools import reduce # from heapq import nsmallest, nlargest, heapify, heappop, heappush, heapreplace def get_inpt(): return sys.stdin.readline().strip() def get_int(): return int(sys.stdin.readline().strip()) def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_array(): return list(map(int, sys.stdin.readline().strip().split())) # sys.setrecursionlimit(10**7) # INF = float('inf') # MOD1, MOD2 = 10**9+7, 998244353 n, k = get_ints() for _ in range(k): arr = get_array() for i in reversed(range(n-1)): if arr[i] < arr[i+1]: ind = i+1 minn = arr[i+1] for j in range(i+1, n): if arr[j] > arr[i]: minn = min(arr[j], minn) ind = j arr[i], arr[ind] = arr[ind], arr[i] arr = arr[:i+1] + sorted(arr[i+1:]) break print(*arr) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- 0 01 10 010 101 010 0101 1010 0101 1010 -----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 t in range(t): n=int(input()) for i in range(0,n): for j in range(0,n): if i%2==0: if j%2==0: print(0,end="") else: print(1,end="") else: if j%2==0: print(1,end="") else: print(0,end="") print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: DZY loves planting, and he enjoys solving tree problems. DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge in the shortest path between nodes x and y. Specially g(z, z) = 0 for every z. For every integer sequence p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n), DZY defines f(p) as $\operatorname{min}_{i = 1}^{n} g(i, p_{i})$. DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most x_{j} times. Please, find the maximum possible f(p) under the described restrictions. -----Input----- The first line contains an integer n (1 ≤ n ≤ 3000). Each of the next n - 1 lines contains three integers a_{i}, b_{i}, c_{i} (1 ≤ a_{i}, b_{i} ≤ n; 1 ≤ c_{i} ≤ 10000), denoting an edge between a_{i} and b_{i} with length c_{i}. It is guaranteed that these edges form a tree. Each of the next n lines describes an element of sequence x. The j-th line contains an integer x_{j} (1 ≤ x_{j} ≤ n). -----Output----- Print a single integer representing the answer. -----Examples----- Input 4 1 2 1 2 3 2 3 4 3 1 1 1 1 Output 2 Input 4 1 2 1 2 3 2 3 4 3 4 4 4 4 Output 3 -----Note----- In the first sample, one of the optimal p is [4, 3, 2, 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()) edges = [[int(x) for x in input().split()] for i in range(n-1)] edges = sorted(edges) use_count = [0]+[int(input()) for i in range(n)] lo,hi = 0,10000 def getpar(par,u): if par[par[u]] == par[u]: return par[u] par[u] = getpar(par,par[u]) return par[u] def unite(par,sz,use,u,v): u = getpar(par,u) v = getpar(par,v) par[u] = v sz[v] += sz[u] use[v] += use[u] def solve(fp): par = [i for i in range(n+1)] sz = [1 for i in range(n+1)] use = [use_count[i] for i in range(n+1)] for edge in edges: if edge[2] < fp: unite(par,sz,use,edge[0],edge[1]) total_use = sum(use_count) for i in range(n+1): p = getpar(par,i) if(p == i): if(total_use - use[p] < sz[p]): return False return True while lo < hi: mid = (lo+hi+1)//2 if solve(mid): lo = mid else: hi = mid-1 print(lo) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A spy needs your help to encrypt a 5 letter message. To encrypt the message the following steps are need to be done: 1)Each letter of the message will be converted to it's equivalent number (i.e A=0, B=1,..Z=25) 2)98, 57, 31, 45, 46 are the 5 numbers in the key. 3)Add the equivalent number of the first letter of the message to the first number of the key, then the equivalent number of the second letter of the message to the second number of the key and so on. 4)Take modulo 26 of the sum of each expression. 5)Convert the newly obtained numbers into it's equivalent letters (i.e 0=A, 1=B,…25=Z) Print the final encrypted string. Note: It is guaranteed that the given string only contains Only Upper-case Latin Letters. -----Input:----- - The first line of the input contains a single Integer $T$. $T$ denoting the number of testcases, description of each testcases contains. - The first line of the each testcase contains a single string $S$. $S$ denoting the string which you need to encrypt -----Output:----- - For each test case, print encypted string i.e result of above operation. Note: Each testcase output must be printed on new line -----Constraints:----- - $1 \leq T \leq 100$ - $1 \leq S \leq 5$ -----Sample Input:----- 2 HELLO HELL -----Sample Output:----- BJQEI BJQE -----Explanation:----- - For 1st Testcase : The conversion of "HELLO" to its equivalent number will be 7, 4, 11, 11, 14 respectively. Then we add each equivalent number of the message with corresponding number in the key: 7 + 98 = 105 4 + 57 = 61 11 + 31 = 42 11 + 45 = 56 14 + 46 = 60 Further we take the sum: 105 modulo 26 = 1 61 modulo 26 = 9 42 modulo 26 = 16 56 modulo 26 = 4 60 modulo 26 = 8 Finally, convert the newly obtained numbers into it's equivalent letters: B J Q E I Print the final string: BJQEI 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 string from collections import OrderedDict from itertools import zip_longest dic = OrderedDict(zip(string.ascii_uppercase, range(0, 26))) keys = [98, 57, 31, 45, 46] t = int(input()) # number of test cases s1 = [] for i in range(t): s = input() for i in s: if i in dic.keys(): s1.append(int(i.replace(i, str(dic[i])))) s2 = [sum(t) for t in zip_longest(s1, keys, fillvalue=0)] inv_dic = {v:k for k,v in dic.items()} s_1 = list() for i in range(len(s1)): s_1.append(s2[i]%26) res= [inv_dic[i] for i in s_1] print(''.join(res)) inv_dic.clear() res.clear() s1.clear() s2.clear() s_1.clear() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have a laser with P amount of energy in it. You are playing a game where you have to use the laser to destroy some crystals, each with some health of their own. Initially, you have 0 points. Each crystal has an associated health. The health of the ith crystal is given by health[i]. You can perform one of the two actions: - At the cost of health[i] energy, you can destroy the ith crystal and gain 1 point. You can only perform this action if your laser has atleast health[i] energy in it. - At the cost of 1 point, you can destroy the ith crystal and refuel the laser's energy by an amount equal to health[i]. This action can only be performed if you have atleast one point. Note: Each crystal can only be destroyed once. Determine the maximum number of points you can obtain by destroying any number of crystals and performing either action as you wish. -----Input:----- - First line will contain n, number of crystals. - Second line will contain space separated integers, health of each crystal. - Third line will contain an integer P, initial energy of the laser. -----Output:----- Print the largest number of points we can have after destroying any number of crystals. -----Constraints----- - health.length <= 1000 - 0 <= health[i] < 10000 - 0 <= P < 10000 -----Subtasks----- - 40 points : 1 <= health.length <= 100 - 60 points : health.length > 100 -----Sample Input 1:----- 1 200 100 -----Sample Output 1:----- 0 -----Explanation:----- The laser initially has only 100 energy. Since the only crystal requires 200 energy to destroy, we cannot perform any action here, and the game ends. The number of points is zero. -----Sample Input 2:----- 2 100 200 150 -----Sample Output 2:----- 1 -----Explanation:----- The laser has 150 energy. We can consume 100 energy and destroy the first crystal and gain 1 point. The remaining energy is 50, which is not enough to destroy the other crystal. We end the game here as we have the maximum possible points attainable. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def game(n,l,p): if(len(l)==0): return 0 l.sort() if(len(l)>=1 and p<l[0]): return 0 l.sort() c=0 ma=set() ma.add(0) while(len(l)): if(p>=l[0]): p-=l[0] c+=1 ma.add(c) l=l[1:] else: if(c>0): c-=1 ma.add(c) p+=l[-1] l=l[:-1] else: return max(ma) return max(ma) n=int(input()) l=list(map(int,input().split())) p=int(input()) print(game(n,l,p)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Consider the fraction, $a/b$, where $a$ and $b$ are positive integers. If $a < b$ and $GCD(a,b) = 1$, it is called a reduced proper fraction. If we list the set of a reduced proper fraction for $d \leq 8$, (where $d$ is the denominator) in ascending order of size, we get: $1/8$, $1/7$, $1/6$, $1/5$, $1/4$, $2/7$, $1/3$, $3/8$, $2/5$ , $3/7$, $1/2$, $4/7$, $3/5$, $5/8$, $2/3$, $5/7$, $3/4$, $4/5$, $5/6$, $6/7$, $7/8$ It can be seen that $2/5$ is the fraction immediately to the left of $3/7$. By listing the set of reduced proper fractions for $d \leq N$ in ascending order of value, find the numerator and denominator of the fraction immediately to the left of $a/b$ when $a$ and $b$ are given. -----Input:----- - First line of input contains an integer $T$, number of test cases - Next $T$ lines contain $a$ $b$ $N$ separated by space -----Output:----- Print the numerator and denominator separated by a space corresponding to each test case on a new line -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq a < b \leq 10^9$ - $GCD(a,b) = 1$ - $b < N \leq 10^{15}$ -----Subtasks----- - 10 points: $1 \leq N \leq 100$ - 30 points : $1 \leq N \leq 10^6$ - 60 points : $1 \leq N \leq 10^{15}$ -----Sample Input:----- 5 3 7 8 3 5 8 4 5 8 6 7 8 1 5 8 -----Sample Output:----- 2 5 4 7 3 4 5 6 1 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin from fractions import Fraction input = stdin.readline for _ in range(int(input())): a, b, n = list(map(int, input().split())) ab = Fraction(a, b) p = set() for i in range(1, n+1): for j in range(n, 0, -1): x = Fraction(i, j) if x > ab: break p.add(x) x = sorted(p)[-2] print(x.numerator, x.denominator) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Give me Chocolate Anushka wants to buy chocolates.there are many chocolates in front of her, tagged with their prices. Anushka has only a certain amount to spend, and she wants to maximize the number of chocolates she buys with this money. Given a list of prices and an amount to spend, what is the maximum number of chocolates Anushka can buy? For example, if prices =[1,2,3,4] and Anushka has k=7 to spend, she can buy items [1,2,3] for 6 , or [3,4] for 7 units of currency. she would choose the first group of 3 items. Input Format The first line contains two integers, n and k , the number of priced chocolates and the amount Anushka has to spend. The next line contains n space-separated integers prices[i] Constraints 1<= n <= 105 1<= k <= 109 1<= prices[i] <= 109 A chocolate can't be bought multiple times. Output Format An integer that denotes the maximum number of chocolates Anushka can buy for her. Sample Input 7 50 1 12 5 111 200 1000 10 Sample Output 4 Explanation she can buy only 4 chocolatess at most. These chocolates have the following prices: 1, 12, 5, 10. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n,k = map(int,input().split()) prices = list(map(int,input().split())) prices.sort() sum,cnt = 0, 0 for price in prices: sum += price if sum <= k: cnt += 1 else: break print(cnt) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland. In Udayland, there are 2^{n} days in a year. ZS the Coder wants to interview k people from Udayland, each of them has birthday in one of 2^{n} days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day. ZS the Coder knows that the answer can be written as an irreducible fraction $\frac{A}{B}$. He wants to find the values of A and B (he does not like to deal with floating point numbers). Can you help him? -----Input----- The first and only line of the input contains two integers n and k (1 ≤ n ≤ 10^18, 2 ≤ k ≤ 10^18), meaning that there are 2^{n} days in a year and that ZS the Coder wants to interview exactly k people. -----Output----- If the probability of at least two k people having the same birthday in 2^{n} days long year equals $\frac{A}{B}$ (A ≥ 0, B ≥ 1, $\operatorname{gcd}(A, B) = 1$), print the A and B in a single line. Since these numbers may be too large, print them modulo 10^6 + 3. Note that A and B must be coprime before their remainders modulo 10^6 + 3 are taken. -----Examples----- Input 3 2 Output 1 8 Input 1 3 Output 1 1 Input 4 3 Output 23 128 -----Note----- In the first sample case, there are 2^3 = 8 days in Udayland. The probability that 2 people have the same birthday among 2 people is clearly $\frac{1}{8}$, so A = 1, B = 8. In the second sample case, there are only 2^1 = 2 days in Udayland, but there are 3 people, so it is guaranteed that two of them have the same birthday. Thus, the probability is 1 and A = B = 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python m = 10** 6 + 3 n, k = list(map(int, input().split())) p = 1 for i in range(n): p *= 2 if p > k: break if p < k: print('1 1') return gcd = tmp = k - 1 while tmp: gcd -= tmp % 2 tmp //= 2 b = pow(2, (k - 1) * n - gcd, m) a = 1 mem = [-1]*100 for i in range(1, k): cnt = 0 while i % 2 == 0: i //= 2 cnt += 1 if mem[cnt] == -1: mem[cnt] = pow(2, n - cnt, m) a = a * (mem[cnt] - i + m) % m if a == 0: break print((b - a + m) % m, b) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk). Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost. -----Input----- The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} is 0 if the cow number i is facing left, and 1 if it is facing right. -----Output----- Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 4 0 0 1 0 Output 1 Input 5 1 0 1 0 1 Output 3 -----Note----- In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python __author__ = 'Pavel Mavrin' n = int(input()) a = [int(x) for x in input().split()] s = 0 res = 0 for i in a: if i == 0: res += s else: s += 1 print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has created a special dividing machine that supports the below given operations on an array of positive integers. There are two operations that Chef implemented on the machine. Type 0 Operation Update(L,R): for i = L to R: a[i] = a[i] / LeastPrimeDivisor(a[i]) Type 1 Operation Get(L,R): result = 1 for i = L to R: result = max(result, LeastPrimeDivisor(a[i])) return result; The function LeastPrimeDivisor(x) finds the smallest prime divisor of a number. If the number does not have any prime divisors, then it returns 1. Chef has provided you an array of size N, on which you have to apply M operations using the special machine. Each operation will be one of the above given two types. Your task is to implement the special dividing machine operations designed by Chef. Chef finds this task quite easy using his machine, do you too? -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains two space-separated integers N, M, denoting the size of array A and the number of queries correspondingly. The second line of each test case contains N space-separated integers A1, A2, ..., AN denoting the initial array for dividing machine. Each of following M lines contain three space-separated integers type, L, R - the type of operation (0 - Update operation, 1 - Get operation), and the arguments of function, respectively -----Output----- For each test case, output answer of each query of type 1 (Get query) separated by space. Each test case from the same file should start from the new line. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ Ai ≤ 106 - 1 ≤ L ≤ R ≤ N - 0 ≤ type ≤ 1 - Sum of M over all test cases in a single test file does not exceed 106 -----Subtasks----- Subtask #1: (10 points) - 1 ≤ N, M ≤ 103 Subtask #2: (25 points) - 1 ≤ N, M ≤ 105 - Ai is a prime number. Subtask #3: (65 points) - 1 ≤ N, M ≤ 105 -----Example----- Input: 2 6 7 2 5 8 10 3 44 1 2 6 0 2 3 1 2 6 0 4 6 1 1 6 0 1 6 1 4 6 2 2 1 3 0 2 2 1 1 2 Output: 5 3 5 11 1 -----Explanation----- Example case 1.The states of array A after each Update-operation: A: = [2 1 4 10 3 44] A: = [2 1 4 5 1 22] A: = [1 1 2 1 1 11] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math n=1001 a=[True]*n l=[] for i in range(2,33): if(a[i]): for j in range(i*i,n,i): a[j]=False for pr in range(2,1001): if(a[pr]): l.append(pr) t=int(input()) for j in range(t): n,m=list(map(int,input().strip().split())) arr=[int(num) for num in input().strip().split()] Matrix =[] index=[0]*100000 factors=[0]*100000 ans='' for r in range(len(arr)): li=[] for val in l: while((arr[r]%val)==0): arr[r]=arr[r]/val li.append(val) factors[r]+=1 if(arr[r]!=1): li.append(arr[r]) arr[r]=1 factors[r]+=1 Matrix.append(li) for k in range(m): opr=[int(o) for o in input().strip().split()] L=opr[1] R=opr[2] if(opr[0]==0): for ran in range(L-1,R): if(index[ran]<factors[ran]): index[ran]+=1 else: result=1 for ran in range(L-1,R): if(index[ran]<factors[ran]): result=max(result,Matrix[ran][index[ran]]) ans+=str(result) ans+=' ' print(ans[:-1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Many things in this first paragraph are references to some pretty famous YouTube stars, so be careful about rephrasing. Thanks! Michael, Kevin and Jake are sharing a cake, in celebration of their Webby award. They named it VCake. Unlike other cakes they considered, this one has finite volume and surface area. It's shaped as a normal rectangular cake with dimensions R centimeters by C centimeters. For the purposes of this problem, we can forget about three dimensions and think of a cake as just a 2D rectangle. Chef will now cut the cake into three pieces, one for each person. However, the cake's shape and Chef's really old tools pose a few restrictions: - Chef can only cut the cake, or a cake piece, across a line parallel to one of its sides. - Chef can only cut the cake, or a cake piece, from end to end. That is, she cannot cut the cake partially. - Chef can only cut the cake, or a cake piece, such that the sides of the resulting pieces (which will be rectangular in shape) are integers. In addition, Michael, Kevin and Jake also have a few preferences of their own: - They want their pieces to be connected (in one piece), and rectangular in shape. - Michael wants his piece to have an area exactly M square centimeters. (Again, forget about a third dimension.) - Kevin wants his piece to have an area exactly K square centimeters. - Jake wants his piece to have an area exactly J square centimeters. With these restrictions, Chef is at a loss. Is it possible for Chef to accomplish this task? Please note that the entire cake should be used. There should be no leftover cake. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each test case consists of a single line containing five space separated integers R, C M, K and J. -----Output----- For each test case, output a single line containing either “Yes” or “No” (without quotes), denoting whether Chef can accomplish the task or not. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ R, C ≤ 109 - 1 ≤ M, K, J ≤ 1018 -----Example----- Input:4 4 5 10 4 6 4 5 6 10 4 4 5 4 6 10 2 2 2 2 2 Output:Yes Yes Yes No -----Explanation----- Example case 1. In this case, Chef can accomplish the task by doing the following slicing. pre tt _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _________ | | | | | | |M M M M M| | | -- |_ _ _ _ _| -- |_ _ _ _ _| -- |M_M_M_M_M| | | | | | | | |J J J|K K| |_ _ _ _ _| |_ _ _ _ _| |_ _ _|_ _| |J_J_J|K_K| /tt /pre I'll make an image if I have time Example case 4. Here, Michael, Kevin and Jake each wants a piece with area 2, but the total area of the cake is only 2×2 = 4. This means the task is impossible. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #!/usr/bin/python import sys def __starting_point(): t = int(input()) for iteration in range(t): r,c,m_inp,k_inp,j_inp = input().strip().split(" ") r=int(r) c=int(c) m_inp=int(m_inp) k_inp=int(k_inp) j_inp=int(j_inp) ans = "" if (r*c) != (m_inp+k_inp+j_inp): print("No") continue else: flag = False for i in range(6): if flag: break if i==0: m = m_inp k = k_inp j = j_inp elif i==1: m = j_inp k = m_inp j = k_inp elif i==2: m = k_inp k = j_inp j = m_inp elif i==3: m = m_inp k = j_inp j = k_inp elif i==4: m = k_inp k = m_inp j = j_inp elif i==5: m = j_inp k = k_inp j = m_inp if m%r == 0: r_remain_1 = r c_remain_1 = c-(m/r) if k%r_remain_1 == 0: r_remain_2 = r_remain_1 c_remain_2 = c_remain_1 - (k/r_remain_1) if r_remain_2*c_remain_2 == j: print("Yes") flag = True continue if k%c_remain_1 == 0: c_remain_2 = c_remain_1 r_remain_2 = r_remain_1 - (k/c_remain_1) if r_remain_2*c_remain_2 == j: print("Yes") flag = True continue if j%r_remain_1 == 0: r_remain_2 = r_remain_1 c_remain_2 = c_remain_1 - (j/r_remain_1) if r_remain_2*c_remain_2 == k: print("Yes") flag = True continue if j%c_remain_1 == 0: c_remain_2 = c_remain_1 r_remain_2 = r_remain_1 - (j/c_remain_1) if r_remain_2*c_remain_2 == k: print("Yes") flag = True continue if m%c == 0: c_remain_1 = c r_remain_1 = r-(m/c) if k%r_remain_1 == 0: r_remain_2 = r_remain_1 c_remain_2 = c_remain_1 - (k/r_remain_1) if r_remain_2*c_remain_2 == j: print("Yes") flag = True continue if k%c_remain_1 == 0: c_remain_2 = c_remain_1 r_remain_2 = r_remain_1 - (k/c_remain_1) if r_remain_2*c_remain_2 == j: print("Yes") flag = True continue if j%r_remain_1 == 0: r_remain_2 = r_remain_1 c_remain_2 = c_remain_1 - (j/r_remain_1) if r_remain_2*c_remain_2 == k: print("Yes") flag = True continue if j%c_remain_1 == 0: c_remain_2 = c_remain_1 r_remain_2 = r_remain_1 - (j/c_remain_1) if r_remain_2*c_remain_2 == k: print("Yes") flag = True continue if not flag: print("No") __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The name of our college is "Government College of Engineering and Textile Technology Berhampore". There is another college named "Government College of Engineering and Textile Technology Serampore". As the names are quite similar, those who are unaware of existence of both the colleges, often get confused. And mistake one with other. Given a string, if it contains the word berhampore (case insensitive), print GCETTB or if it contains serampore(case-insensitive), print GCETTS . If the string contains neither print Others. If it contains both Berhampore and Serampore print Both Input - First line contains single integer T, No. of test case - Next line for every test contain case a string S Output Print GCETTB or GCETTS or Others or Both on a new line Constraints - 1 <= T <= 10 - 0 <= len(S) <= 100 - S contain a-z and A-Z and space only Sample Input 3 Government clg Berhampore SeRaMporE textile college Girls college Kolkata Sample Output GCETTB GCETTS Others Explanation Self-Explanatory 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 i in range(t): n=input() n=n.lower() a="berhampore" b="serampore" if a in n: if b in n: print("Both") else: print("GCETTB") elif b in n: if a in n: print("Both") else: print("GCETTS") else: print("Others") except Exception as e: pass ```
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 consisting of lowercase English letters. Process Q queries of the following two types: - Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.) - Type 2: answer the number of different characters occurring in the substring of S between the l_q-th and r_q-th characters (inclusive). -----Constraints----- - N, Q, i_q, l_q, and r_q are integers. - S is a string consisting of lowercase English letters. - c_q is a lowercase English letter. - 1 \leq N \leq 500000 - 1 \leq Q \leq 20000 - |S| = N - 1 \leq i_q \leq N - 1 \leq l_q \leq r_q \leq N - There is at least one query of type 2 in each testcase. -----Input----- Input is given from Standard Input in the following format: N S Q Query_1 \vdots Query_Q Here, Query_i in the 4-th through (Q+3)-th lines is one of the following: 1 i_q c_q 2 l_q r_q -----Output----- For each query of type 2, print a line containing the answer. -----Sample Input----- 7 abcdbbd 6 2 3 6 1 5 z 2 1 1 1 4 a 1 7 d 2 1 7 -----Sample Output----- 3 1 5 In the first query, cdbb contains three kinds of letters: b , c , and d, so we print 3. In the second query, S is modified to abcdzbd. In the third query, a contains one kind of letter: a, so we print 1. In the fourth query, S is modified to abcazbd. In the fifth query, S does not change and is still abcazbd. In the sixth query, abcazbd contains five kinds of letters: a, b, c, d, and z, so we print 5. 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 = list(input()) s = [ord(i)-97 for i in s] dic = {} for i in range(26): dic[i] = [] for i in range(n): dic[s[i]].append(i) for i in range(26): dic[i].append(float('inf')) from bisect import bisect_left q = int(input()) for i in range(q): x, y, z = input().split() if x == '1': y, z = int(y) - 1, ord(z) - 97 p = bisect_left(dic[s[y]], y) dic[s[y]].pop(p) dic[z].insert(bisect_left(dic[z], y), y) s[y] = z else: res = 0 y, z = int(y) - 1, int(z) - 1 for i in range(26): p = dic[i][bisect_left(dic[i], y)] if p <= z: res += 1 print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process. -----Input----- The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 10^5, 1 ≤ n ≤ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers r_{i}, c_{i} (1 ≤ r_{i} ≤ h, 1 ≤ c_{i} ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct. -----Output----- Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 10^9 + 7. -----Examples----- Input 3 4 2 2 2 2 3 Output 2 Input 100 100 3 15 16 16 15 99 88 Output 545732279 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def init_factorials(N, mod): f = 1 fac = [1] * N for i in range(1, N): f *= i f %= mod fac[i] = f return fac def init_inv(N, mod, fac): b = bin(mod-2)[2:][-1::-1] ret = 1 tmp = fac[N] if b[0] == '1': ret = fac[N] for bi in b[1:]: tmp *= tmp tmp %= mod if bi == '1': ret *= tmp ret %= mod inv = [1] * (N + 1) inv[N] = ret for i in range(N-1, 0, -1): ret *= i + 1 ret %= mod inv[i] = ret return inv def f(r, c, mod, fac, inv): return (fac[r + c] * inv[r] * inv[c]) % mod def read_data(): h, w, n = list(map(int, input().split())) blacks = [] for i in range(n): r, c = list(map(int, input().split())) blacks.append((r, c)) return h, w, n, blacks def solve(h, w, n, blacks): mod = 10**9 + 7 fac = init_factorials(h + w + 10, mod) inv = init_inv(h + w + 5, mod, fac) ans = (fac[h+w-2]*inv[h-1]*inv[w-1]) % mod eb = [(r + c, r, c) for r, c in blacks] eb.sort() blacks = [(r, c) for rc, r, c in eb] g = [f(r-1, c-1, mod, fac, inv) for r, c in blacks] hw = h+w for i, (r, c) in enumerate(blacks): gi = g[i] rc = r + c ans -= gi*fac[hw-rc]*inv[h-r]*inv[w-c] ans %= mod for j, (rj, cj) in enumerate(blacks[i+1:], i+1): if r <= rj and c <= cj: g[j] -= gi*fac[rj+cj-rc]*inv[rj-r]*inv[cj-c] g[j] %= mod return ans h, w, n, blacks = read_data() print(solve(h, w, n, blacks)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given $n$ points on the plane. The polygon formed from all the $n$ points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $1$ to $n$, in clockwise order. We define the distance between two points $p_1 = (x_1, y_1)$ and $p_2 = (x_2, y_2)$ as their Manhattan distance: $$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as $p_1, p_2, \ldots, p_k$ $(k \geq 3)$, then the perimeter of the polygon is $d(p_1, p_2) + d(p_2, p_3) + \ldots + d(p_k, p_1)$. For some parameter $k$, let's consider all the polygons that can be formed from the given set of points, having any $k$ vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define $f(k)$ to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: [Image] In the middle polygon, the order of points ($p_1, p_3, p_2, p_4$) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is ($p_1, p_2, p_3, p_4$), which is the left polygon. Your task is to compute $f(3), f(4), \ldots, f(n)$. In other words, find the maximum possible perimeter for each possible number of points (i.e. $3$ to $n$). -----Input----- The first line contains a single integer $n$ ($3 \leq n \leq 3\cdot 10^5$) — the number of points. Each of the next $n$ lines contains two integers $x_i$ and $y_i$ ($-10^8 \leq x_i, y_i \leq 10^8$) — the coordinates of point $p_i$. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. -----Output----- For each $i$ ($3\leq i\leq n$), output $f(i)$. -----Examples----- Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 -----Note----- In the first example, for $f(3)$, we consider four possible polygons: ($p_1, p_2, p_3$), with perimeter $12$. ($p_1, p_2, p_4$), with perimeter $8$. ($p_1, p_3, p_4$), with perimeter $12$. ($p_2, p_3, p_4$), with perimeter $12$. For $f(4)$, there is only one option, taking all the given points. Its perimeter $14$. In the second example, there is only one possible polygon. Its perimeter is $8$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline n = int(input()) x = [] y = [] for i in range(n): xi, yi = map(int, input().split()) x.append(xi) y.append(yi) min_x = min(x) max_x = max(x) min_y = min(y) max_y = max(y) answer = 0 for i in range(n): dx = max(max_x - x[i], x[i] - min_x) dy = max(max_y - y[i], y[i] - min_y) answer = max(answer, dx + dy) print(2*answer, end = ' ') for i in range(4, n + 1): print(2*(max_x - min_x + max_y - min_y), end = ' ') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array $a_1$, $a_2$, ..., $a_n$ of integers, such that $1 \le a_1 < a_2 < \ldots < a_n \le 10^3$, and then went to the bathroom. JATC decided to prank his friend by erasing some consecutive elements in the array. Since he doesn't want for the prank to go too far, he will only erase in a way, such that Giraffe can still restore the array using the information from the remaining elements. Because Giraffe has created the array, he's also aware that it's an increasing array and all the elements are integers in the range $[1, 10^3]$. JATC wonders what is the greatest number of elements he can erase? -----Input----- The first line of the input contains a single integer $n$ ($1 \le n \le 100$) — the number of elements in the array. The second line of the input contains $n$ integers $a_i$ ($1 \le a_1<a_2<\dots<a_n \le 10^3$) — the array written by Giraffe. -----Output----- Print a single integer — the maximum number of consecutive elements in the array that JATC can erase. If it is impossible to erase even a single element, print $0$. -----Examples----- Input 6 1 3 4 5 6 9 Output 2 Input 3 998 999 1000 Output 2 Input 5 1 2 3 4 5 Output 4 -----Note----- In the first example, JATC can erase the third and fourth elements, leaving the array $[1, 3, \_, \_, 6, 9]$. As you can see, there is only one way to fill in the blanks. In the second example, JATC can erase the second and the third elements. The array will become $[998, \_, \_]$. Because all the elements are less than or equal to $1000$, the array is still can be restored. Note, that he can't erase the first $2$ elements. In the third example, JATC can erase the first $4$ elements. Since all the elements are greater than or equal to $1$, Giraffe can still restore the array. Note, that he can't erase the last $4$ elements. 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 = [0] + list(map(int, input().split())) + [1001] mx = 1 p = 1 for i in range(1, n + 2): if a[i] == a[i - 1] + 1: p += 1 mx = max(p, mx) else: p = 1 print(max(0, mx - 2)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are two friends Alice and Bob. They have a packet of $n$ candies. They want to split the candies between them, and to do so, they kept them all in a single line. The $i^{\text{th}}$ candy in the line has a sweetness value of $a_i$. They decided to take turns in picking the candies. Alice has the first turn. In a person's turn, they either eat the leftmost candy or the rightmost candy with equal probability. Can you find the expected value of sum of sweetness of the candies eaten by Alice? Your answer is considered correct if its absolute or relative error doesn't exceed $10^{-6}$ . -----Input:----- - The first line will contain $T$, number of testcases. Then the testcases follow. - First line of each testcase contains a single integer $n$ denoting the number of candies. - Second line of each testcase contains $n$ space separated integers representing $a_1,a_2,a_3,...a_n$ respectively. -----Output:----- For each testcase, output the expected value of sum of sweetness of the candies which Alice eats. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq n \leq 10^3$ - $1 \leq a_i \leq 10^6$ - Sum of $n$ across all the tests $\leq 10^3$ -----Sample Input:----- 2 2 1 2 3 1 2 3 -----Sample Output:----- 1.500000000000000 4.000000000000000 -----EXPLANATION:----- In the first sample, Alice eats either the first or the second candy with equal probability. Hence, expected value is $(1+2)/2 = 1.5$ For the second sample, expected value is $4$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import setrecursionlimit setrecursionlimit(10 ** 9) def solve(i, j, c=0): if i > j: return 0 if (i, j) in dp: return dp[i, j] x0 = solve(i+1, j, c^1) x1 = solve(i, j-1, c^1) if c == 0: y = 1 << (j - i) x0 += a[i] * y x1 += a[j] * y dp[i, j] = x0 + x1 return dp[i, j] for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) dp = {} total = solve(0, n-1) print(total / (1 << n)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. At time 1, the first spectator stands. At time 2, the second spectator stands. ... At time k, the k-th spectator stands. At time k + 1, the (k + 1)-th spectator stands and the first spectator sits. At time k + 2, the (k + 2)-th spectator stands and the second spectator sits. ... At time n, the n-th spectator stands and the (n - k)-th spectator sits. At time n + 1, the (n + 1 - k)-th spectator sits. ... At time n + k, the n-th spectator sits. Arpa wants to know how many spectators are standing at time t. -----Input----- The first line contains three integers n, k, t (1 ≤ n ≤ 10^9, 1 ≤ k ≤ n, 1 ≤ t < n + k). -----Output----- Print single integer: how many spectators are standing at time t. -----Examples----- Input 10 5 3 Output 3 Input 10 5 7 Output 5 Input 10 5 12 Output 3 -----Note----- In the following a sitting spectator is represented as -, a standing spectator is represented as ^. At t = 0  ---------- $\Rightarrow$ number of standing spectators = 0. At t = 1  ^--------- $\Rightarrow$ number of standing spectators = 1. At t = 2  ^^-------- $\Rightarrow$ number of standing spectators = 2. At t = 3  ^^^------- $\Rightarrow$ number of standing spectators = 3. At t = 4  ^^^^------ $\Rightarrow$ number of standing spectators = 4. At t = 5  ^^^^^----- $\Rightarrow$ number of standing spectators = 5. At t = 6  -^^^^^---- $\Rightarrow$ number of standing spectators = 5. At t = 7  --^^^^^--- $\Rightarrow$ number of standing spectators = 5. At t = 8  ---^^^^^-- $\Rightarrow$ number of standing spectators = 5. At t = 9  ----^^^^^- $\Rightarrow$ number of standing spectators = 5. At t = 10 -----^^^^^ $\Rightarrow$ number of standing spectators = 5. At t = 11 ------^^^^ $\Rightarrow$ number of standing spectators = 4. At t = 12 -------^^^ $\Rightarrow$ number of standing spectators = 3. At t = 13 --------^^ $\Rightarrow$ number of standing spectators = 2. At t = 14 ---------^ $\Rightarrow$ number of standing spectators = 1. At t = 15 ---------- $\Rightarrow$ number of standing spectators = 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def read_ints(): return [int(i) for i in input().split()] n, k, t = read_ints() if t <= k: print(t) elif t > n: print(k + n - t) else: print(k) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: For the multiset of positive integers $s=\{s_1,s_2,\dots,s_k\}$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $s$ as follow: $\gcd(s)$ is the maximum positive integer $x$, such that all integers in $s$ are divisible on $x$. $\textrm{lcm}(s)$ is the minimum positive integer $x$, that divisible on all integers from $s$. For example, $\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$ and $\textrm{lcm}(\{4,6\})=12$. Note that for any positive integer $x$, $\gcd(\{x\})=\textrm{lcm}(\{x\})=x$. Orac has a sequence $a$ with length $n$. He come up with the multiset $t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$, and asked you to find the value of $\gcd(t)$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence. -----Input----- The first line contains one integer $n\ (2\le n\le 100\,000)$. The second line contains $n$ integers, $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 200\,000$). -----Output----- Print one integer: $\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\})$. -----Examples----- Input 2 1 1 Output 1 Input 4 10 24 40 80 Output 40 Input 10 540 648 810 648 720 540 594 864 972 648 Output 54 -----Note----- For the first example, $t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$, so $\gcd(t)=1$. For the second example, $t=\{120,40,80,120,240,80\}$, and it's not hard to see that $\gcd(t)=40$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def Sieve(n): ret = [] divlis = [-1] * (n+1) flag = [True] * (n+1) flag[0] = False flag[1] = False ind = 2 while ind <= n: if flag[ind]: ret.append(ind) ind2 = ind ** 2 while ind2 <= n: flag[ind2] = False divlis[ind2] = ind ind2 += ind ind += 1 return ret,divlis sev,divlis = Sieve(210000) n = int(input()) a = list(map(int,input().split())) dic = {} for i in range(n): nd = {} na = a[i] while divlis[na] != -1: if divlis[na] not in nd: nd[divlis[na]] = 0 nd[divlis[na]] += 1 na //= divlis[na] if na != 1: if na not in nd: nd[na] = 1 else: nd[na] += 1 for x in nd: if x not in dic: dic[x] = [] dic[x].append(nd[x]) ans = 1 for i in dic: if len(dic[i]) < n-1: #print (i,"a") continue dic[i].sort() if len(dic[i]) == n: ans *= i ** dic[i][1] #print (i,"b") else: ans *= i ** dic[i][0] #print (i,"c") print (ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise. -----Input----- The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 10^5). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right. -----Output----- Print the number of steps, so that the line remains the same afterward. -----Examples----- Input 10 10 9 7 8 6 5 3 4 2 1 Output 2 Input 6 1 2 3 4 5 6 Output 0 -----Note----- In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] → [10 8 4] → [10]. So, there are two steps. 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()) ans = 0 stk = [] for v in map(int, input().split()): last = 0 while len(stk) and stk[-1][0] < v and stk[-1][1]: last = max(last, stk[-1][1]) del stk[-1] if not len(stk) or stk[-1][0] < v: stk.append((v, 0)) else: stk.append((v, last + 1)); ans = max(ans, last + 1) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vivek was quite bored with the lockdown, so he came up with an interesting task. He successfully completed this task and now, he would like you to solve it. You are given two strings $A$ and $B$, each with length $N$. Let's index the characters in each string from $0$ ― for each $i$ ($0 \le i < N$), the $i+1$-th characters of $A$ and $B$ are denoted by $A_i$ and $B_i$ respectively. You should convert $A$ to $B$ by performing operations of the following type: - Choose a subset $S$ of the set $\{0, 1, \ldots, N-1\}$. - Let $c$ be the alphabetically smallest character among $A_x$ for all $x \in S$. - For each $x \in S$, replace $A_x$ by $c$. You should find the smallest necessary number of operations or report that it is impossible to convert $A$ to $B$. If it is possible, you also need to find one way to convert $A$ to $B$ using this smallest number of operations. If there are multiple solutions, you may find any one. -----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 a single string $A$. - The third line contains a single string $B$. -----Output----- For each test case: - If it is impossible to convert $A$ to $B$, print a single line containing the integer $-1$. - Otherwise, first, print a line containing a single integer $K$ ― the minimum number of operations. - Then, print $K$ lines describing the operations. Each of these lines should contain a positive integer $Z$, followed by a space and $Z$ pairwise distinct space-separated integers from the set $\{0, 1, \ldots, N-1\}$ ― the elements of $S$. -----Constraints----- - $1 \le T \le 20$ - $1 \le N \le 10^3$ - $|A| = |B| = N$ - $A$ and $B$ contain only lowercase English letters -----Subtasks----- Subtask #1 (30 points): $B$ contains only characters 'a' and 'b' Subtask #2 (70 points): original constraints -----Example Input----- 3 5 abcab aabab 3 aaa aab 2 de cd -----Example Output----- 2 3 1 2 4 3 0 1 3 -1 -1 -----Explanation----- Example case 1: - First, we can choose $S = (1, 2, 4)$, so the character $c$ is 'b' and the string $A$ after this operation is "abbab". - Then, we choose $S = (0, 1, 3)$, so $c$ is 'a', and $A$ becomes "aabab". - There is no way to convert $A$ to $B$ in only one operation. Example case 2: We can see that it is impossible to convert $A$ to $B$ since $c$ is always 'a'. Example case 3: We can see again that it is impossible to convert $A$ to $B$ since $c$ cannot be 'c'. 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=input() b=input() l=[] flag=0 for i in range(n): if b[i]!=a[i]: if b[i] in a and b[i]<a[i]: l.append(b[i]) else: flag=1 break if flag==1: print(-1) else: if l==[]: print(0) else: l = sorted(list(set(l)), reverse = True) print(len(l)) for i in range(len(l)): q=[] r=[] for j in range(len(a)): if l[i]==b[j]: q.append(j) r.append(a[j]) if l[i] not in r: for k in range(len(a)): if a[k]==l[i]: q.append(k) print(len(q),*q) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The year 2015 is almost over. Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 2015_10 = 11111011111_2. Note that he doesn't care about the number of zeros in the decimal representation. Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster? Assume that all positive integers are always written without leading zeros. -----Input----- The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10^18) — the first year and the last year in Limak's interval respectively. -----Output----- Print one integer – the number of years Limak will count in his chosen interval. -----Examples----- Input 5 10 Output 2 Input 2015 2015 Output 1 Input 100 105 Output 0 Input 72057594000000000 72057595000000000 Output 26 -----Note----- In the first sample Limak's interval contains numbers 5_10 = 101_2, 6_10 = 110_2, 7_10 = 111_2, 8_10 = 1000_2, 9_10 = 1001_2 and 10_10 = 1010_2. Two of them (101_2 and 110_2) have the described property. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def zero(strx): k = [] str2 = list(strx) for i in range(1, len(str2)): str3 = str2[:] str3[i] = '0' k.append(''.join(str3)) return k a = [] for i in range(1, 64): a += zero('1'*i) ct = 0 x, y = list(map(int, input().split(' '))) for i in a: if x <= int(i, 2) <= y: ct+=1 print(ct) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length [Image] The picture corresponds to the first example -----Input----- The first line contains single integer n (1 ≤ n ≤ 5·10^5) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x_1, y_1, x_2 and y_2 ( - 10^9 ≤ x_1 < x_2 ≤ 10^9, - 10^9 ≤ y_1 < y_2 ≤ 10^9), that means that points (x_1, y_1) and (x_2, y_2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. -----Output----- Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer c_{i} (1 ≤ c_{i} ≤ 4) — the color of i-th rectangle. -----Example----- Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 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()) ans = 'YES\n' for i in range(n): x1, y1, x2, y2 = map(int, input().split()) res = (x1 & 1) * 2 + (y1 & 1) + 1 ans += str(res) + '\n' print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a_1, a_2, ..., a_{k}, that their sum is equal to n and greatest common divisor is maximal. Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them. If there is no possible sequence then output -1. -----Input----- The first line consists of two numbers n and k (1 ≤ n, k ≤ 10^10). -----Output----- If the answer exists then output k numbers — resulting sequence. Otherwise output -1. If there are multiple answers, print any of them. -----Examples----- Input 6 3 Output 1 2 3 Input 8 2 Output 2 6 Input 5 3 Output -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, k = map(int, input().split()) div = [] i = 1 n1 = n while i * i <= n: if n % i == 0: div.append(i) div.append(n // i) i += 1 div.sort() mx = -1 for i in range(len(div)): a = div[i] * k * (k + 1) // 2 if a <= n: mx = div[i] if mx == -1: print(-1) else: for i in range(k - 1): print(mx * (i + 1), end= " ") print(n - mx * k * (k - 1) // 2) ```
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. Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes. In the player, Polycarp stores $n$ songs, each of which is characterized by two parameters: $t_i$ and $g_i$, where $t_i$ is the length of the song in minutes ($1 \le t_i \le 15$), $g_i$ is its genre ($1 \le g_i \le 3$). Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the $i$-th song, he would spend exactly $t_i$ minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated. Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. -----Input----- The first line of the input contains two integers $n$ and $T$ ($1 \le n \le 15, 1 \le T \le 225$) — the number of songs in the player and the required total duration, respectively. Next, the $n$ lines contain descriptions of songs: the $i$-th line contains two integers $t_i$ and $g_i$ ($1 \le t_i \le 15, 1 \le g_i \le 3$) — the duration of the $i$-th song and its genre, respectively. -----Output----- Output one integer — the number of different sequences of songs, the total length of exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo $10^9 + 7$ (that is, the remainder when dividing the quantity by $10^9 + 7$). -----Examples----- Input 3 3 1 1 1 2 1 3 Output 6 Input 3 3 1 1 1 1 1 3 Output 2 Input 4 10 5 3 2 1 3 2 5 1 Output 10 -----Note----- In the first example, Polycarp can make any of the $6$ possible playlist by rearranging the available songs: $[1, 2, 3]$, $[1, 3, 2]$, $[2, 1, 3]$, $[2, 3, 1]$, $[3, 1, 2]$ and $[3, 2, 1]$ (indices of the songs are given). In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of $2$ possible ways: $[1, 3, 2]$ and $[2, 3, 1]$ (indices of the songs are given). In the third example, Polycarp can make the following playlists: $[1, 2, 3]$, $[1, 3, 2]$, $[2, 1, 3]$, $[2, 3, 1]$, $[3, 1, 2]$, $[3, 2, 1]$, $[1, 4]$, $[4, 1]$, $[2, 3, 4]$ and $[4, 3, 2]$ (indices of the songs are given). 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 factorial def lol(n): if n == 1: yield [0] yield [1] else: for p in lol(n - 1): p.append(0) yield p p[-1] = 1 yield p p.pop() def sp(g1, g2, g3, f): if g1 == 0: if g2 == g3: return 2 elif abs(g2 - g3) == 1: return 1 else: return 0 elif g2 == 0: if g1 == g3: return 2 elif abs(g1 - g3) == 1: return 1 else: return 0 elif g3 == 0: if g2 == g1: return 2 elif abs(g2 - g1) == 1: return 1 else: return 0 else: if f == 1: b = sp(g1, g2 - 1, g3, 2) c = sp(g1, g2, g3 - 1, 3) return b + c elif f == 2: a = sp(g1 - 1, g2, g3, 1) c = sp(g1, g2, g3 - 1, 3) return a + c elif f == 3: a = sp(g1 - 1, g2, g3, 1) b = sp(g1, g2 - 1, g3, 2) return a + b else: a = sp(g1 - 1, g2, g3, 1) b = sp(g1, g2 - 1, g3, 2) c = sp(g1, g2, g3 - 1, 3) return a + b + c n, T = map(int, input().split()) S = [] cnt = 0 M = 10 ** 9 + 7 for i in range(n): S.append(list(map(int, input().split()))) for p in lol(n): d = 0 g1, g2, g3 = 0, 0, 0 for i in range(n): if p[i]: d += S[i][0] if S[i][1] == 1: g1 += 1 elif S[i][1] == 2: g2 += 1 elif S[i][1] == 3: g3 += 1 if d == T: cnt += factorial(g1) * factorial(g2) * factorial(g3) * sp(g1, g2, g3, 0) cnt %= M print(cnt) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has a natural number N. Cheffina challenges chef to check whether the given number is divisible by the sum of its digits or not. If the given number is divisible then print "Yes" else "No". -----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 16 27 -----Sample Output:----- No Yes The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys,io,os,math from math import ceil,log,gcd,inf from itertools import permutations mod=1000000007 mod1=998244353 def printlist(n): sys.stdout.write(" ".join(map(str,n)) + "\n") printf=lambda n:sys.stdout.write(str(n)+"\n") def printns(n): sys.stdout.write(str(n)) def intinp(): return int(sys.stdin.readline()) def strinp(): return sys.stdin.readline() def arrinp(): return list(map(int,sys.stdin.readline().strip().split())) def mulinp(): return list(map(int,sys.stdin.readline().strip().split())) def flush(): return sys.stdout.flush() def power_two(x): return (1<<x) def lcm(a,b): return a*b//gcd(a,b) def solve(): n=intinp() ans=str(n) count=0 for i in ans: count+=int(i) if(n%count==0): print('Yes') return 0 print('No') def main(): tc=intinp() while(tc): solve() tc-=1 main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for $n$ days. On the $i$-th day: If Du can speak, he'll make fun of Boboniu with fun factor $a_i$. But after that, he may be muzzled depending on Boboniu's mood. Otherwise, Du won't do anything. Boboniu's mood is a constant $m$. On the $i$-th day: If Du can speak and $a_i>m$, then Boboniu will be angry and muzzle him for $d$ days, which means that Du won't be able to speak on the $i+1, i+2, \cdots, \min(i+d,n)$-th days. Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of $a$. -----Input----- The first line contains three integers $n$, $d$ and $m$ ($1\le d\le n\le 10^5,0\le m\le 10^9$). The next line contains $n$ integers $a_1, a_2, \ldots,a_n$ ($0\le a_i\le 10^9$). -----Output----- Print one integer: the maximum total fun factor among all permutations of $a$. -----Examples----- Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 -----Note----- In the first example, you can set $a'=[15, 5, 8, 10, 23]$. Then Du's chatting record will be: Make fun of Boboniu with fun factor $15$. Be muzzled. Be muzzled. Make fun of Boboniu with fun factor $10$. Make fun of Boboniu with fun factor $23$. Thus the total fun factor is $48$. 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 N, D, M = map(int, readline().split()) A = list(map(int, readline().split())) Am = [a for a in A if a > M] Ao = [a for a in A if a <= M] Am.sort(reverse = True) Ao.sort(reverse = True) Cam = Am[:] Cao = Ao[:] for i in range(1, len(Cam)): Cam[i] += Cam[i-1] for i in range(1, len(Cao)): Cao[i] += Cao[i-1] k = -(-N//(D+1)) ans = sum(Am[:k]) lcam = len(Cam) Cam = [0] + Cam for i in range(len(Cao)): k = min(lcam, -(-(N-(i+1))//(D+1))) ans = max(ans, Cao[i] + Cam[k]) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After completing some serious investigation, Watson and Holmes are now chilling themselves in the Shimla hills. Very soon Holmes became bored. Holmes lived entirely for his profession. We know he is a workaholic. So Holmes wants to stop his vacation and get back to work. But after a tiresome season, Watson is in no mood to return soon. So to keep Holmes engaged, he decided to give Holmes one math problem. And Holmes agreed to solve the problem and said as soon as he solves the problem, they should return back to work. Watson too agreed. The problem was as follows. Watson knows Holmes’ favorite numbers are 6 and 5. So he decided to give Holmes N single digit numbers. Watson asked Holmes to form a new number with the given N numbers in such a way that the newly formed number should be completely divisible by 5 and 6. Watson told Holmes that he should also form the number from these digits in such a way that the formed number is maximum. He may or may not use all the given numbers. But he is not allowed to use leading zeros. Though he is allowed to leave out some of the numbers, he is not allowed to add any extra numbers, which means the maximum count of each digit in the newly formed number, is the same as the number of times that number is present in those given N digits. -----Input----- The first line of input contains one integers T denoting the number of test cases. Each test case consists of one integer N, number of numbers. Next line contains contains N single digit integers -----Output----- For each test case output a single number, where the above said conditions are satisfied. If it is not possible to create such a number with the given constraints print -1.If there exists a solution, the maximised number should be greater than or equal to 0. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 10000 - 0 ≤ Each digit ≤ 9 -----Subtasks----- Subtask #1 : (90 points) - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 10000 Subtask 2 : (10 points) - 1 ≤ T ≤ 10 - 1 ≤ N≤ 10 -----Example----- Input: 2 12 3 1 2 3 2 0 2 2 2 0 2 3 11 3 9 9 6 4 3 6 4 9 6 0 Output: 33322222200 999666330 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(0,t): n=int(input()) lis=list(map(int,input().split())) lis2=[] for j in range(0,10): lis2.append(0) for j in range(0,len(lis)): lis2[lis[j]]+=1; s=sum(lis) while s%3!=0: if s%3==2: if lis2[2]>=1: lis2[2]-=1 s=s-2 elif lis2[5]>=1: lis2[5]-=1 s=s-5 elif lis2[8]>=1: lis2[8]-=1 s=s-8 elif lis2[1]>=2: lis2[1]-=2 s=s-2 elif lis2[1]>=1 and lis2[4]>=1: lis2[1]-=1 lis2[4]-=1 s=s-5 elif lis2[4]>=2: lis2[4]-=2 s=s-8 elif lis2[1]>=1 and lis2[7]>=1: lis2[1]-=1 lis2[7]-=1 s=s-8 elif lis2[4]>=1 and lis2[7]>=1: lis2[4]-=1 lis2[7]-=1 s=s-11 elif lis2[7]>=2: lis2[7]-=2 s=s-14 elif s%3==1: if lis2[1]>=1: lis2[1]-=1 s=s-1 elif lis2[4]>=1: lis2[4]-=1 s=s-4 elif lis2[7]>=1: lis2[7]-=1 s=s-7 elif lis2[2]>=2: lis2[2]-=2 s=s-4 elif lis2[5]>=1 and lis2[2]>=1: lis2[2]-=1 lis2[5]-=1 s=s-7 elif lis2[5]>=2: lis2[5]-=2 s=s-10 elif lis2[2]>=1 and lis2[8]>=1: lis2[2]-=1 lis2[8]-=1 s=s-10 elif lis2[8]>=1 and lis2[5]>=1: lis2[8]-=1 lis2[5]-=1 s=s-13 elif lis2[8]>=2: lis2[8]-=2 s=s-16 lis3=[] for j in range(1,10): if lis2[j]>=1: for k in range(0,lis2[j]): lis3.append(j) lis3.reverse() for k in range(0,lis2[0]): lis3.append(0) sol='' for k in range(0,len(lis3)): sol+=str(lis3[k]) print(sol) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let N be a positive even number. We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below. First, let q be an empty sequence. Then, perform the following operation until p becomes empty: - Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q. When p becomes empty, q will be a permutation of (1, 2, ..., N). Find the lexicographically smallest permutation that can be obtained as q. -----Constraints----- - N is an even number. - 2 ≤ N ≤ 2 × 10^5 - p is a permutation of (1, 2, ..., N). -----Input----- Input is given from Standard Input in the following format: N p_1 p_2 ... p_N -----Output----- Print the lexicographically smallest permutation, with spaces in between. -----Sample Input----- 4 3 2 4 1 -----Sample Output----- 3 1 2 4 The solution above is obtained as follows:pq(3, 2, 4, 1)()↓↓(3, 1)(2, 4)↓↓()(3, 1, 2, 4) The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline import numpy as np from heapq import heappush, heappop N = int(input()) A = np.array(input().split(), dtype=np.int32) a_to_i = {a:i for i,a in enumerate(A)} # sparse table を使ってRMQ # parityの同じところだけを見るようにしておく U = len(A).bit_length() sp = [None,A] for i in range(2,U): L = 1 << (i-1) sp.append(np.minimum(sp[-1][:-L], sp[-1][L:])) def RMQ(x,y): # x番目から偶数番目だけ見て[x,y]での最小値を返す d = y - x if d <= 1: return A[x] n = d.bit_length() return min(sp[n-1][x], sp[n-1][y+2-(1<<(n-1))]) def F(x,y): # 辞書式で最小の2つ組をとる # そのあと、今後調べないといけない区間の一覧を返す x1 = RMQ(x,y-1) i1 = a_to_i[x1] x2 = RMQ(i1+1,y) i2 = a_to_i[x2] task = ((x,y) for x,y in ((x,i1-1), (i1+1,i2-1), (i2+1,y)) if y > x) return x1,x2,task q = [(None,None,((0,N-1),))] answer = [] while q: x,y,task = heappop(q) answer.append(x) answer.append(y) for left,right in task: heappush(q,F(left,right)) print(' '.join(map(str,answer[2:]))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Eugene loves sequences, especially arithmetic progressions. One day he was asked to solve a difficult problem. If a sequence of numbers A1, A2, ... , AN form an arithmetic progression A, he was asked to calculate sum of F(Ai), for L ≤ i ≤ R. F(X) is defined as: If X < 10 then F(X) = X. Else F(X) = F(sum_of_digits(X)). Example: F(1378) = F(1+3+7+8) = F(19) = F(1 + 9) = F(10) = F(1+0) = F(1) = 1 -----Input----- - The first line of the input contains an integer T denoting the number of test cases. - Each test case is described in one line containing four integers: A1 denoting the first element of the arithmetic progression A, D denoting the common difference between successive members of A, and L and R as described in the problem statement. -----Output----- - For each test case, output a single line containing one integer denoting sum of F(Ai). -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ A1 ≤ 109 - 0 ≤ D ≤ 109 - 1 ≤ R ≤ 1018 - 1 ≤ L ≤ R -----Subtasks----- - Subtask 1: 0 ≤ D ≤ 100, 1 ≤ A1 ≤ 109, 1 ≤ R ≤ 100 - 15 points - Subtask 2: 0 ≤ D ≤ 109, 1 ≤ A1 ≤ 109, 1 ≤ R ≤ 106 - 25 points - Subtask 3: Original constraints - 60 points -----Example----- Input: 2 1 1 1 3 14 7 2 4 Output: 6 12 -----Explanation----- Example case 1. A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...} A1 = 1 A2 = 2 A3 = 3 F(A1) = 1 F(A2) = 2 F(A3) = 3 1+2+3=6 Example case 2. A = {14, 21, 28, 35, 42, 49, 56, 63, 70, 77, ...} A2 = 21 A3 = 28 A4 = 35 F(A2) = 3 F(A3) = 1 F(A4) = 8 3+1+8=12 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import fractions import sys f = sys.stdin if len(sys.argv) > 1: f = open(sys.argv[1], "rt") sum_cache = {} def sum_func(x): if x < 10: return x r = sum_cache.get(x) if r is not None: return r xx = 0 while x > 0: xx += x % 10 x /= 10 r = sum_func(xx) sum_cache[x] = r return r def test(): for n in range(1): print(n, sum_func(n)) print(sum_func(int(10**18 - 1))) #~ test() #~ sys.exit(1) cycle_table = [ # Cycle len, markers # D_kfunc [9, [1, 1, 1, 1, 1, 1, 1, 1, 1]], # 1 [9, [1, 1, 1, 1, 1, 1, 1, 1, 1]], # 2 [3, [1, 0, 0, 1, 0, 0, 1, 0, 0]], # 3 [9, [1, 1, 1, 1, 1, 1, 1, 1, 1]], # 4 [9, [1, 1, 1, 1, 1, 1, 1, 1, 1]], # 5 [3, [1, 0, 0, 1, 0, 0, 1, 0, 0]], # 6 [9, [1, 1, 1, 1, 1, 1, 1, 1, 1]], # 7 [9, [1, 1, 1, 1, 1, 1, 1, 1, 1]], # 8 [1, [1, 0, 0, 0, 0, 0, 0, 0, 0]], # 9 ] NUMBER = 9 def calc(A_1, D, L, R): #~ print('calc ===', A_1, D, L, R) A_L = A_1 + D * (L - 1) A_L_kfunc = sum_func(A_L) D_kfunc = sum_func(D) #~ print(A_L, A_L_kfunc, D_kfunc) n = R - L + 1 if D == 0: return n * A_L_kfunc cycle_len = cycle_table[D_kfunc - 1][0] cycle_markers = list(cycle_table[D_kfunc - 1][1]) # copy #~ print('cycle_len', cycle_len) whole_part = n // cycle_len remainder = n % cycle_len #~ print('whole_part, remainder = ', whole_part, remainder) counts = [whole_part * x for x in cycle_markers] #~ print(counts) pos = 0 for i in range(remainder): counts[pos] += 1 pos = (pos + D_kfunc) % NUMBER #~ print(counts) r = 0 for i, x in enumerate(counts): value = (A_L_kfunc - 1 + i) % NUMBER + 1 r += value * x return r def calc_dumb(A_1, D, L, R): #~ print('dumb ===', A_1, D, L, R) a = A_1 + D * (L - 1) n = R - L + 1 r = 0 for i in range(n): value = sum_func(a) #~ print(a, value) r += value a += D return r def test1(): a1 = 1 L = 1 R = 1000 for d in range(100): r1 = calc_dumb(a1, d, L, R) r2 = calc(a1, d, L, R) if r1 != r2: print(a1, d, L, R, ":", r1, r2) def test2(): a1 = 1 d = 9 L = 1 R = 9 r1 = calc_dumb(a1, d, L, R) r2 = calc(a1, d, L, R) print(r1, r2) #~ test1() #~ sys.exit(1) T = int(f.readline().strip()) for case_id in range(1, T+1): A_1, D, L, R = list(map(int, f.readline().strip().split())) r = calc(A_1, D, L, R) print(r) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The life goes up and down, just like nice sequences. Sequence t_1, t_2, ..., t_{n} is called nice if the following two conditions are satisfied: t_{i} < t_{i} + 1 for each odd i < n; t_{i} > t_{i} + 1 for each even i < n. For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not. Bear Limak has a sequence of positive integers t_1, t_2, ..., t_{n}. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements t_{i} and t_{j} in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different. -----Input----- The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence. The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice. -----Output----- Print the number of ways to swap two elements exactly once in order to get a nice sequence. -----Examples----- Input 5 2 8 4 7 7 Output 2 Input 4 200 150 100 50 Output 1 Input 10 3 2 1 4 1 4 1 4 1 4 Output 8 Input 9 1 2 3 4 5 6 7 8 9 Output 0 -----Note----- In the first sample, there are two ways to get a nice sequence with one swap: Swap t_2 = 8 with t_4 = 7. Swap t_1 = 2 with t_5 = 7. In the second sample, there is only one way — Limak should swap t_1 = 200 with t_4 = 50. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): n, l = int(input()), list(map(int, input().split())) if not (n & 1): l.append(0) l.append(150001) i, b, c, fails0, fails1 = 0, 0, 150001, [], [] try: while True: a, b, c = b, c, l[i] if a >= b or b <= c: if len(fails0) + len(fails1) > 5: print(0) return fails1.append(i - 1) i += 1 a, b, c = b, c, l[i] if a <= b or b >= c: if len(fails0) + len(fails1) > 5: print(0) return fails0.append(i - 1) i += 1 except IndexError: fails, res = fails0 + fails1, 0 for i in fails: a = l[i] for j in range(n): f = fails1 if j & 1 else fails0 f.append(j) l[i], l[j] = l[j], a if (all(l[b - 1] > l[b] < l[b + 1] for b in fails0) and all(l[b - 1] < l[b] > l[b + 1] for b in fails1)): res += 1 if j in fails else 2 l[j] = l[i] del f[-1] l[i] = a print(res // 2) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chefland has all the cities on a straight line. There are $N$ cities in Chefland numbered $1$ to $N$. City $i$ is located at coordinate $x_i$ on the x-axis. Guru wants to travel from city $A$ to city $B$. He starts at time t=0. He has following choices to travel. - He can walk $1$ metre in $P$ secs. - There is a train that travels from city $C$ to city $D$ which travels $1$ metre in $Q$ secs which starts at time t=$Y$ secs. Guru can take the train only at city $C$ and leave the train only at city $D$. Can you help Guru find the minimum time he will need to travel from city $A$ to $B$. Note that you cannot board the train after time t =$Y$. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - First line of each testcase contains eight space separated integers $N, A, B, C, D, P, Q, Y $. - Second line of each testcase contains $N$ space-separated integers with the $i$-th integer representing $x_i$. -----Output:----- For each testcase, output in a single line containing the minimum travel time. -----Constraints----- - $1 \leq T \leq 300$ - $2 \leq N \leq 300$ - $-1000 \leq x_i \leq 1000$ - $0 \leq Y \leq 100000$ - $1 \leq A,B,C,D \leq n $ - $A \neq B$ - $C \neq D$ - $1 \leq P, Q \leq 100$ - $x_i < x_j$ if $i < j$ -----Sample Input:----- 1 4 1 3 2 4 3 2 4 1 2 3 4 -----Sample Output:----- 6 -----EXPLANATION:----- Guru can walk directly in 6 secs. If Guru takes train, then he will need atleast 11 secs. 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,a,b,c,d,p,q,y=list(map(int,input().split())) l=list(map(int,input().split())) ans = abs((l[b-1]-l[a-1]))*p x=abs(l[c-1]-l[a-1])*p if x<=y: x=y+abs(l[d-1]-l[c-1])*q+abs(l[b-1]-l[d-1])*p ans=min(ans,x) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: We all know how great ABD aka AB-DE-VILLIERS is. However his team mates were jealous of him and posed a problem for him to solve.The problem description is as follows : Given an array of integers,find the length of the largest subarray(contiguous) of the given array with the maximum possible GCD (Greatest Common Divisor). For info on GCD ,see this link: https://en.wikipedia.org/wiki/Greatest_common_divisor GCD of the subarray is defined as the GCD of all the elements of the subarray. As ABD is not aware of competitive programming he asks your help. Help him! -----Input----- First line will contain integer N denoting the size of array. Second line will contain N integers denoting array elements. -----Output----- The answer as specified in the problem statement . -----Constraints----- 1 <= N <= 1000000 1 <= array[i] <=100000000000 -----Example----- Input: 4 2 4 8 3 Output: 1 Explanation GCD of all possible subarrays of the given array are : 2 , 2 , 2 , 1 , 4 , 4, 1 , 8 , 1 , 3 Largest GCD possible : 8 Length of the largest subarray with GCD as 8 is 1 Hence 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 n=eval(input()) a=list(map(int,input().split())) c=m=0 maxi=max(a) for i in range(n): if a[i]==maxi: c+=1 m=max(c,m) else: c=0 print(m) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a prime number $p$, $n$ integers $a_1, a_2, \ldots, a_n$, and an integer $k$. Find the number of pairs of indexes $(i, j)$ ($1 \le i < j \le n$) for which $(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$. -----Input----- The first line contains integers $n, p, k$ ($2 \le n \le 3 \cdot 10^5$, $2 \le p \le 10^9$, $0 \le k \le p-1$). $p$ is guaranteed to be prime. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le p-1$). It is guaranteed that all elements are different. -----Output----- Output a single integer — answer to the problem. -----Examples----- Input 3 3 0 0 1 2 Output 1 Input 6 7 2 1 2 3 4 5 6 Output 3 -----Note----- In the first example: $(0+1)(0^2 + 1^2) = 1 \equiv 1 \bmod 3$. $(0+2)(0^2 + 2^2) = 8 \equiv 2 \bmod 3$. $(1+2)(1^2 + 2^2) = 15 \equiv 0 \bmod 3$. So only $1$ pair satisfies the condition. In the second example, there are $3$ such pairs: $(1, 5)$, $(2, 3)$, $(4, 6)$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def check(num1, num2, p, k): v = num1 + num2 v *= num1 * num1 + num2 * num2 v %= p v += p v %= p return v == k % p def __starting_point(): n, p, k = (int(x) for x in input().split()) idx___number = [int(x) for x in input().split()] idx___precount = [((pow(x, 4, p) - k * x) % p + p) % p for x in idx___number] met_precount___vals = {} ans = 0 for number, precount in zip(idx___number[::-1], idx___precount[::-1]): if precount not in met_precount___vals: met_precount___vals[precount] = [] else: for val in met_precount___vals[precount]: if check(number, val, p, k): ans += 1 met_precount___vals[precount].append(number) print(ans) __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ziota found a video game called "Monster Invaders". Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns. For the sake of simplicity, we only consider two different types of monsters and three different types of guns. Namely, the two types of monsters are: a normal monster with $1$ hp. a boss with $2$ hp. And the three types of guns are: Pistol, deals $1$ hp in damage to one monster, $r_1$ reloading time Laser gun, deals $1$ hp in damage to all the monsters in the current level (including the boss), $r_2$ reloading time AWP, instantly kills any monster, $r_3$ reloading time The guns are initially not loaded, and the Ziota can only reload 1 gun at a time. The levels of the game can be considered as an array $a_1, a_2, \ldots, a_n$, in which the $i$-th stage has $a_i$ normal monsters and 1 boss. Due to the nature of the game, Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the $a_i$ normal monsters. If Ziota damages the boss but does not kill it immediately, he is forced to move out of the current level to an arbitrary adjacent level (adjacent levels of level $i$ $(1 < i < n)$ are levels $i - 1$ and $i + 1$, the only adjacent level of level $1$ is level $2$, the only adjacent level of level $n$ is level $n - 1$). Ziota can also choose to move to an adjacent level at any time. Each move between adjacent levels are managed by portals with $d$ teleportation time. In order not to disrupt the space-time continuum within the game, it is strictly forbidden to reload or shoot monsters during teleportation. Ziota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value. -----Input----- The first line of the input contains five integers separated by single spaces: $n$ $(2 \le n \le 10^6)$ — the number of stages, $r_1, r_2, r_3$ $(1 \le r_1 \le r_2 \le r_3 \le 10^9)$ — the reload time of the three guns respectively, $d$ $(1 \le d \le 10^9)$ — the time of moving between adjacent levels. The second line of the input contains $n$ integers separated by single spaces $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^6, 1 \le i \le n)$. -----Output----- Print one integer, the minimum time to finish the game. -----Examples----- Input 4 1 3 4 3 3 2 5 1 Output 34 Input 4 2 4 4 1 4 5 1 2 Output 31 -----Note----- In the first test case, the optimal strategy is: Use the pistol to kill three normal monsters and AWP to kill the boss (Total time $1\cdot3+4=7$) Move to stage two (Total time $7+3=10$) Use the pistol twice and AWP to kill the boss (Total time $10+1\cdot2+4=16$) Move to stage three (Total time $16+3=19$) Use the laser gun and forced to move to either stage four or two, here we move to stage four (Total time $19+3+3=25$) Use the pistol once, use AWP to kill the boss (Total time $25+1\cdot1+4=30$) Move back to stage three (Total time $30+3=33$) Kill the boss at stage three with the pistol (Total time $33+1=34$) Note that here, we do not finish at level $n$, but when all the bosses are killed. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n,r1,r2,r3,D = map(int,input().split()) state = [0,0] # after odd number of 2 (1st), or not (2nd) a = list(map(int,input().split())) # First element # Choosing P~P + A state[0] = r1 * a[0] + r3 # Choosing L + P later or all P state[1] = min(r2 + r1 + D, r1 * (a[0] + 2) + D) # Second to Second Last element for i in range(1,n-1): newState = [-1,-1] newState[0] = min(state[1] + D + r1 * a[i] + r3, state[0] + r1 * a[i] + r3, state[1] + r2 + r1 + D, state[1] + r1 * (a[i] + 2) + D) newState[1] = min(state[0] + r2 + r1 + D, state[0] + r1 * (a[i] + 2) + D) state = newState # Last Element ans = min(state[0] + r1 * a[-1] + r3, state[0] + 2 * D + r2 + r1, state[0] + 2 * D + r1 * (a[-1] + 2), state[1] + r1 * a[-1] + r3, state[1] + r2 + r1 + D, state[1] + r1 * (a[-1] + 2) + D) print(ans + D * (n-1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a grid with $R$ rows (numbered $1$ through $R$) and $C$ columns (numbered $1$ through $C$). A cell in row $r$ and column $c$ is denoted by $(r, c)$. Two cells in the grid are adjacent if they have a common side. For each valid $i$ and $j$, there is a value $a_{i, j}$ written in cell $a_{i, j}$. A cell in the grid is stable if the number of cells in the grid which are adjacent to this cell is strictly greater than the value written in this cell. The whole grid is stable if all cells in the grid are stable. Can you determine whether the grid is stable? -----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 $R$ and $C$. - $R$ lines follow. For each $i$ ($1 \le i \le R$), the $i$-th of these lines contains $C$ space-separated integers $a_{i, 1}, a_{i, 2}, \ldots, a_{i, C}$. -----Output----- For each test case, print a single line containing the string "Stable" if the grid is stable or "Unstable" if it is unstable (without quotes). -----Constraints----- - $1 \le T \le 3,000$ - $3 \le R, C \le 10$ - $0 \le a_{i, j} \le 4$ for each valid $i, j$ -----Example Input----- 2 3 3 1 2 1 2 3 2 1 2 1 3 4 0 0 0 0 0 0 0 0 0 0 4 0 -----Example Output----- Stable Unstable -----Explanation----- Example case 1: Each cell of the grid is stable, so the grid is stable. Example case 2: The cell in row $3$ and column $3$ is unstable since the number of cells adjacent to this cell is $3$. 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())): r,c = map(int,input().split()) l = [] for k in range(r): a = list(map(int,input().split())) l.append(a) ans = "Stable" for i in range(r): for j in range(c): p = l[i][j] count=0 if i-1>=0 and j>=0: count+=1 if i>=0 and j-1>=0: count+=1 if i+1<=r-1 and j<=c-1: count+=1 if i<=r-1 and j+1<=c-1: count +=1 if count<=p: ans = "Unstable" break print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square. You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. -----Output----- Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. -----Examples----- Input 5 4 WWWW WWWB WWWB WWBB WWWW Output 5 Input 1 2 BB Output -1 Input 3 3 WWW WWW WWW Output 1 -----Note----- In the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2). In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square. In the third example all cells are colored white, so it's sufficient to color any cell black. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python h, w = map(int, input().split()) x0, y0, x1, y1, c = 1000, 1000, -1, -1, 0 for i in range(h): row = str(input()) for j in range(w): if row[j] == 'B': x0, y0, x1, y1, c = min(x0, i), min(y0, j), max(x1, i), max(y1, j), c + 1 ln = max(x1 - x0 + 1, y1 - y0 + 1) if ln > min(h, w): print(-1) elif x1 == -1: print(1) else: print(ln * ln - c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Masha and Grisha like studying sets of positive integers. One day Grisha has written a set A containing n different integers a_{i} on a blackboard. Now he asks Masha to create a set B containing n different integers b_{j} such that all n^2 integers that can be obtained by summing up a_{i} and b_{j} for all possible pairs of i and j are different. Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 10^6, and all numbers in B must also be in the same range. Help Masha to create the set B that satisfies Grisha's requirement. -----Input----- Input data contains multiple test cases. The first line contains an integer t — the number of test cases (1 ≤ t ≤ 100). Each test case is described in the following way: the first line of the description contains one integer n — the number of elements in A (1 ≤ n ≤ 100). The second line contains n integers a_{i} — the elements of A (1 ≤ a_{i} ≤ 10^6). -----Output----- For each test first print the answer: NO, if Masha's task is impossible to solve, there is no way to create the required set B. YES, if there is the way to create the required set. In this case the second line must contain n different positive integers b_{j} — elements of B (1 ≤ b_{j} ≤ 10^6). If there are several possible sets, output any of them. -----Example----- Input 3 3 1 10 100 1 1 2 2 4 Output YES 1 2 3 YES 1 YES 1 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python d = [-1] * 1000001 for t in range(int(input())): n, a = int(input()), list(map(int, input().split())) a.sort() for i in range(n): for j in range(i + 1, n): d[a[j] - a[i]] = t i = 1 while any(d[i * j] == t for j in range(1, n)): i += 1 print("YES\n" + ' '.join(str(j * i + 1) for j in range(n))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Jones Trucking Company tracks the location of each of its trucks on a grid similar to an (x, y) plane. The home office is at the location (0, 0). Read the coordinates of truck A and the coordinates of truck B and determine which is closer to the office. -----Input:----- The first line of the data set for this problem is an integer representing the number of collections of data that follow. Each collection contains 4 integers: the x-coordinate and then the y-coordinate of truck A followed by the x-coordinate and then the y-coordinate of truck B. -----Output:----- All letters are upper case. The output is to be formatted exactly like that for the sample output given below. -----Assumptions:----- The x-coordinate is in the range –20 .. 20. The y-coordinate is in the range –20 .. 20. -----Discussion:----- The distance between point #1 with coordinates (x1, y1) and point #2 with coordinates (x2, y2) is: -----Sample Input:----- 4 3 -2 -5 -3 0 6 1 2 -7 8 4 -1 3 3 -2 2 -----Sample Output:----- A IS CLOSER B IS CLOSER B IS CLOSER B IS CLOSER 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 i in range(t): ar=list(map(int,input().split())) if (ar[0]**2 + ar[1]**2 > ar[2]**2 + ar[3]**2): print("B IS CLOSER") else: print("A IS CLOSER") except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The MEX of a set of integers is defined as the smallest non-negative integer that does not belong to this set. For example, $\mathrm{MEX}(\{0,2,3\}) = 1$ and $\mathrm{MEX}(\{1,3\}) = 0$. Chef has a tree with $N$ nodes (numbered $1$ through $N$). The tree is rooted at node $1$. Chef wants to assign a non-negative integer to each node in such a way that each integer between $0$ and $N-1$ (inclusive) is assigned to exactly one node. For each node $u$, consider the integers assigned to the nodes in the subtree of $u$ (including $u$); let $a_u$ denote the MEX of these integers. Chef wants $a_1 + a_2 + \ldots + a_N$ to be as large as possible. Find the maximum possible value of this sum. -----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-1$ space-separated integers $p_1, p_2, \ldots, p_{N-1}$. For each valid $i$, the node $p_i$ is the parent of the node $i+1$. -----Output----- For each test case, print a single line containing one integer ― the maximum sum of subtree MEX-s which can be obtained if you assign the weights optimally. -----Constraints----- - $1 \le T \le 5$ - $2 \le N \le 10^5$ - $1 \le p_i < i$ for each valid $i$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 2 3 1 1 5 1 1 2 2 -----Example Output----- 4 9 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here from math import log2; import sys; sys.setrecursionlimit(10 ** 7) from collections import defaultdict inf = float("inf") def find_height(node): nodes[node]=1 for i in graph[node]: nodes[node]+=find_height(i) return nodes[node] def find_sum(node): suma=nodes[node] maxa=0 for i in graph[node]: maxa=max(find_sum(i),maxa) return maxa+suma for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) graph=defaultdict(set) for i in range(len(l)): graph[l[i]].add(i+2) nodes=defaultdict(int) find_height(1) ans=find_sum(1) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Head Chef is receiving a lot of orders for cooking the best of the problems lately. For this, he organized an hiring event to hire some talented Chefs. He gave the following problem to test the skills of the participating Chefs. Can you solve this problem and be eligible for getting hired by Head Chef. A non-negative number n is said to be magical if it satisfies the following property. Let S denote the multi-set of numbers corresponding to the non-empty subsequences of the digits of the number n in decimal representation. Please note that the numbers in the set S can have leading zeros. Let us take an element s of the multi-set S, prod(s) denotes the product of all the digits of number s in decimal representation. The number n will be called magical if sum of prod(s) for all elements s in S, is even. For example, consider a number 246, its all possible non-empty subsequence will be S = {2, 4, 6, 24, 46, 26, 246}. Products of digits of these subsequences will be {prod(2) = 2, prod(4) = 4, prod(6) = 6, prod(24) = 8, prod(46) = 24, prod(26) = 12, prod(246) = 48, i.e. {2, 4, 6, 8, 24, 12, 48}. Sum of all of these is 104, which is even. Hence 246 is a magical number. Please note that multi-set S can contain repeated elements, e.g. if number is 55, then S = {5, 5, 55}. Products of digits of these subsequences will be {prod(5) = 5, prod(5) = 5, prod(55) = 25}, i.e. {5, 5, 25}. Sum of all of these is 35 which is odd. Hence 55 is not a magical number. Consider a number 204, then S = {2, 0, 4, 20, 04, 24, 204}. Products of digits of these subsequences will be {2, 0, 4, 0, 0, 8, 0}. Sum of all these elements will be 14 which is even. So 204 is a magical number. The task was to simply find the Kth magical number. -----Input----- - First line of the input contains an integer T denoting the number of test cases. - Each of the next T lines contains a single integer K. -----Output----- For each test case, print a single integer corresponding to the Kth magical number. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ K ≤ 1012. -----Subtasks----- Subtask #1 : (20 points) - 1 ≤ T ≤ 100 - 1 ≤ K ≤ 104. Subtask 2 : (80 points) Original Constraints -----Example----- Input: 2 2 5 Output: 2 8 -----Explanation----- Example case 1. 2 is the 2nd magical number, since it satisfies the property of the magical number. The first magical number will be of course 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def base5(n): if n == 0: return for x in base5(n // 5): yield x yield n % 5 def seq(n): return int(''.join(str(2 * x) for x in base5(n)) or '0') for i in range(eval(input())): k=eval(input()) while(i<k): i=i+1 print(seq(i-1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has a strip of length $N$ units and he wants to tile it using $4$ kind of tiles -A Red tile of $2$ unit length -A Red tile of $1$ unit length -A Blue tile of $2$ unit length -A Blue tile of $1$ unit length Chef is having an infinite supply of each of these tiles. He wants to find out the number of ways in which he can tile the strip. Help him find this number. Since this number can be large, output your answer modulo 1000000007 ($10^9 + 7$). -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, an integer $N$. -----Output:----- For each testcase, output in a single line your answer modulo 1000000007. -----Constraints----- - $1 \leq T \leq 1000$ - $2 \leq N \leq 10^{18}$ -----Sample Input:----- 1 2 -----Sample Output:----- 6 -----EXPLANATION:----- It can be seen that for a strip of length $2$, there are $6$ possible configurations. $NOTE : $ 2 tiles of 1 unit length are different from 1 tile of 2 unit length. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Fibonacci Series using # Optimized Method # function that returns nth # Fibonacci number MOD = 1000000007 def fib(n): F = [[2, 2], [1, 0]] power(F, n - 1) ans = [6, 2] return (F[0][0] * 6 + F[0][1] * 2) % MOD # return F[0][0] def multiply(F, M): x = (F[0][0] * M[0][0] + F[0][1] * M[1][0]) % MOD y = (F[0][0] * M[0][1] + F[0][1] * M[1][1]) % MOD z = (F[1][0] * M[0][0] + F[1][1] * M[1][0]) % MOD w = (F[1][0] * M[0][1] + F[1][1] * M[1][1]) % MOD F[0][0] = x F[0][1] = y F[1][0] = z F[1][1] = w def power(F, n): if n == 0 or n == 1: return M = [[2, 2], [1, 0]] power(F, n // 2) multiply(F, F) if n % 2 != 0: multiply(F, M) for _ in range(int(input())): n = int(input()) ans = 1 if n == 0: ans = 1 elif n == 1: ans = 2 elif n == 2: ans = 6 else: ans = fib(n-1) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Probably everyone has experienced an awkward situation due to shared armrests between seats in cinemas. A highly accomplished cinema manager named "Chef" decided to solve this problem. When a customer wants to buy a ticket, the clerk at the ticket window asks the visitor if they need the armrests, and if so, which of them: left, right, or both. We know that out of the audience expected to show up, L of them only need the left armrest, R of them need just the right one, Z need none and B need both. Your task is to calculate the maximum number of people that can attend the show. In the cinema hall there are N rows with M seats each. There is only one armrest between two adjacent seats. Seats at the beginning and at the end of the row have two armrests -----Input----- Input begins with an integer T: the number of test cases. Each test case consists of a single line with 6 space-separated integers: N, M, Z, L, R, B. -----Output----- For each test case, output a line containing the answer for the task. -----Constraints and Subtasks----- - 1 ≤ T ≤ 105 Subtask 1 : 10 points - 1 ≤ N, M ≤ 3 - 0 ≤ Z, L, R, B ≤ 3 Subtask 2 : 20 points - 1 ≤ N, M ≤ 30 - 0 ≤ Z, L, R ≤ 30 - 0 ≤ B ≤ 109 Subtask 3 : 30 points - 1 ≤ N, M ≤ 106 - 0 ≤ Z, L, R ≤ 106 - 0 ≤ B ≤ 1016 Subtask 4 : 40 points - 1 ≤ N, M ≤ 108 - 0 ≤ Z, L, R, B ≤ 1016 -----Example----- Input:2 2 2 3 2 1 1 3 3 1 2 0 9 Output:4 8 -----Explanation----- 'L' - needs left 'R - needs right 'Z' - doesn't need any 'B' - needs both '-' - empty place Example case 1. ZZ ZB Example case 2. LLB BZB B-B 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(eval(input())): n,m,z,l,r,b = list(map(int, input().split())) rows=n columns=m hand_rest=n*(m+1) if(m%2==0): hand_rest -=max(0,n-l-r) if(l+r+(2*b)<=hand_rest): # print "kanu" print(min(n*m,l+r+z+b)) else: temp=l+r+(hand_rest-l-r)/2 # print "parth" print(min(n*m,temp+z)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: All strings in Chefland are beautiful because they are binary strings (a binary string contains only characters '0' and '1'). The beauty of a binary string $S$ is defined as the number of pairs $(i, j)$ ($1 \le i \le j \le |S|$) such that the substring $S_i, S_{i+1}, \ldots, S_j$ is special. For a binary string $U$, let's denote the number of occurrences of the characters '1' and '0' in $U$ by $cnt_1$ and $cnt_0$ respectively; then, $U$ is special if $cnt_0 = cnt_1 \cdot cnt_1$. Today, Chef's friend Araspa is celebrating her birthday. Chef wants to give Araspa the most beautiful binary string he can find. Currently, he is checking out binary strings in a shop, but he needs your help to calculate their beauties. Tell Chef the beauty of each binary string he gives you. -----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 beauty of the string $S$. -----Constraints----- - $1 \le T \le 10$ - $1 \le |S| \le 10^5$ - each character of $S$ is '0' or '1' -----Example Input----- 2 010001 10 -----Example Output----- 4 1 -----Explanation----- Example case 1: The special substrings correspond to $(i, j) = (1, 2), (1, 6), (2, 3), (5, 6)$. 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): s = input() pref = [0]*len(s) if s[0]=="1": pref[0]+=1 for i in range(1,len(s)): if s[i]=="1": pref[i]+=1 pref[i]=pref[i]+pref[i-1] k=1 cnt=0 while (k+k*k)<=len(s): r = k+k*k i=r-1 while i<len(s): if (i-r)>=0: if pref[i]-pref[i-r]==k: cnt+=1 i+=1 else: i+=abs(k-(pref[i]-pref[i-r])) else: if pref[i]==k: cnt+=1 i+=1 else: i+=abs(k-(pref[i])) k+=1 print(cnt) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Problem Statement:Captain America and Iron Man are at WAR and the rage inside Iron Man is rising. But Iron Man faces a problem to identify the location of Captain America. There are N buildings situtaed adjacently to each other and Captain America can be at any building. Iron Man has to arrange the Buildings from 1 to N is such a way that Value(i.e abs(Building Number -Position of Building))=K for every building. Can You help Iron Man to Find The Arrangement of the Buildings? P.S- If no arrangement exist, then print “CAPTAIN AMERICA EVADES”. Input Format: The first line of input contains a single integer,T, denoting the number of test cases. Each of the T subsequent lines contains 2 space-separated integers describing the respective N and K values for a test case. Output Format: On a new line for each test case, Print the lexicographically smallest arrangement; If no absolute arrangement exists, print “CAPTAIN AMERICA EVADES”. Constraints: SubTask#1 1<=T<=10 1<=N<=10^5 0<=K<=N SubTask#2 Original Constraints.. SubTask#3 Original Constraints.. Sample Input: 3 2 1 3 0 3 2 Sample Output: 2 1 1 2 3 CAPTAIN AMERICA EVADES Explanation: Case 1: N=2 and K=1 Therefore the arrangement is [2,1]. Case 2: N=3 and K=0 Therefore arrangement is [1,2,3]. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) while t> 0: t =t -1 n,k = list(map(int,input().split())) a = [0]*n done = True def swap(z): for j in range(0,n): if a[j] == 0: a[j] = z done = True break else: if a[j] > z: swap(j) a[j] = z else: done = False break for i in range(0,n): for j in range(0,n): if abs(i-j) == k: if a[j] == 0: a[j] = i + 1 done = True break else: if a[j] > i + 1: swap(a[j]) a[j] = i + 1 else: done = False if 0 in a: print('CAPTAIN AMERICA EVADES') else: if done: for c in a: print(c, end=' ') print() else: print('CAPTAIN AMERICA EVADES') # for i in range(1,n+1): # if i - k >=0 : # if a[abs(i-k-1)] == 0: # a[abs(i-k-1)] = i # done = True # else: # done = False # break # else: # done = False # break # if done: # for c in a: # print c, # print # else: # print "CAPTAIN AMERICA EVADES" ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. $u \in A$ or $v \in A$ (or both). Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover. They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself). -----Input----- The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n), denoting an undirected edge between u_{i} and v_{i}. It's guaranteed the graph won't contain any self-loops or multiple edges. -----Output----- If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty. -----Examples----- Input 4 2 1 2 2 3 Output 1 2 2 1 3 Input 3 3 1 2 2 3 1 3 Output -1 -----Note----- In the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish). In the second sample, there is no way to satisfy both Pari and Arya. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): n, m = list(map(int, input().split())) l = [[] for _ in range(n + 1)] for _ in range(m): u, v = list(map(int, input().split())) l[u].append(v) l[v].append(u) res = [0] * (n + 1) for u, x in enumerate(res): if not x: x, nxt = -1, [u] while nxt: x, cur, nxt = -x, nxt, [] for u in cur: if l[u]: res[u] = x for v in l[u]: if not res[v]: nxt.append(v) elif res[v] == x: print(-1) return for x in -1, 1: l = [u for u in range(1, n + 1) if res[u] == x] print(len(l)) print(' '.join(map(str, l))) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: — Hey folks, how do you like this problem? — That'll do it. BThero is a powerful magician. He has got $n$ piles of candies, the $i$-th pile initially contains $a_i$ candies. BThero can cast a copy-paste spell as follows: He chooses two piles $(i, j)$ such that $1 \le i, j \le n$ and $i \ne j$. All candies from pile $i$ are copied into pile $j$. Formally, the operation $a_j := a_j + a_i$ is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $k$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power? -----Input----- The first line contains one integer $T$ ($1 \le T \le 500$) — the number of test cases. Each test case consists of two lines: the first line contains two integers $n$ and $k$ ($2 \le n \le 1000$, $2 \le k \le 10^4$); the second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le k$). It is guaranteed that the sum of $n$ over all test cases does not exceed $1000$, and the sum of $k$ over all test cases does not exceed $10^4$. -----Output----- For each test case, print one integer — the maximum number of times BThero can cast the spell without losing his magic power. -----Example----- Input 3 2 2 1 1 3 5 1 2 3 3 7 3 2 2 Output 1 5 4 -----Note----- In the first test case we get either $a = [1, 2]$ or $a = [2, 1]$ after casting the spell for the first time, and it is impossible to cast it again. 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 test in range(t): n,k = map(int,input().split()) A = list(map(int,input().split())) A.sort() ans = 0 for i in range(1,n): if(A[i]>k): ans = 0 break rem = k-A[i] ans+=rem//A[0] print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website. Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic. Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "n', where n is the total number of tests. Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only. The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command. Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run: all examples are the first several tests having filenames "1", "2", ..., "e", where e is the total number of examples; all other files contain regular tests with filenames "e + 1", "e + 2", ..., "n", where n is the total number of all tests. -----Input----- The first line contains single integer n (1 ≤ n ≤ 10^5) — the number of files with tests. n lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the i-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct. -----Output----- In the first line print the minimum number of lines in Vladimir's script file. After that print the script file, each line should be "move file_1 file_2", where "file_1" is an existing at the moment of this line being run filename, and "file_2" — is a string of digits and small English letters with length from 1 to 6. -----Examples----- Input 5 01 0 2 1 2extra 0 3 1 99 0 Output 4 move 3 1 move 01 5 move 2extra 4 move 99 3 Input 2 1 0 2 1 Output 3 move 1 3 move 2 1 move 3 2 Input 5 1 0 11 1 111 0 1111 1 11111 0 Output 5 move 1 5 move 11 1 move 1111 2 move 111 4 move 11111 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()) t = [1] + [0] * n b, a = d = [], [] h, s = [], [] for i in range(n): f, k = input().split() d[int(k)].append(f) m = len(a) for i in a: if i.isdigit() and i[0] != '0': j = int(i) if 0 < j <= m: t[j] = 1 elif m < j <= n: t[j] = -1 else: s.append(i) else: s.append(i) for i in b: if i.isdigit() and i[0] != '0': j = int(i) if m < j <= n: t[j] = 1 elif 0 < j <= m: t[j] = -1 else: s.append(i) else: s.append(i) x = [j for j in range(1, m + 1) if t[j] < 0] y = [j for j in range(m + 1, n + 1) if t[j] < 0] u = [j for j in range(1, m + 1) if not t[j]] v = [j for j in range(m + 1, n + 1) if not t[j]] if not s and (x or y): s = ['0'] if y: i = y.pop() v.append(i) else: i = x.pop() u.append(i) h.append(str(i) + ' 0') t[i] = 0 while x or y: if v and x: i = x.pop() j = v.pop() t[j] = 1 h.append(str(i) + ' ' + str(j)) u.append(i) else: u, v, x, y = v, u, y, x k = 1 for j in s: while t[k] == 1: k += 1 h.append(j + ' ' + str(k)) k += 1 d = '\nmove ' print(str(len(h)) + d + d.join(h) if h else 0) ```
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 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 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 200$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $200$. It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----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 from operator import itemgetter import sys input = sys.stdin.readline MAX_A = 200 t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) ruiseki = [[0] * MAX_A for i in range(n + 1)] for i in range(n): for j in range(MAX_A): ruiseki[i + 1][j] = ruiseki[i][j] if a[i] - 1 == j: ruiseki[i + 1][j] += 1 ans = 0 for num in set(a): l = 0 r = n - 1 cnt = 0 while True: while True: if a[l] != num: l += 1 else: break while True: if a[r] != num: r -= 1 else: break if l == r: ans = max(ans, cnt + 1) break elif l > r: break cnt += 1 tmp_max = 0 for j in range(MAX_A): tmp_max = max(tmp_max, ruiseki[r][j] - ruiseki[l + 1][j]) ans = max(ans, cnt * 2 + tmp_max) l += 1 r -= 1 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given an Array of length $N$ containing elements $Ai$ ( i = 1 to n ) . You have to handle $Q$ queries on this array . Each Query is of two types k=(1 or 2). Type 1:- $k$ $l$ $r$ in which you have to tell whether the product of numbers in range l to r results in a perfect square or not. if product of numbers in range $l$ to$r$ is a perfect square then simply output YES else output NO. Type 2:- $k$ $i$ $val$ Multiply the value present at index $i$ with $val$. Note#1: 1 based indexing in each query. Note#2: Values of prime factors of all numbers $val$ and $Ai$ is between 2 to 100 only. -----Input:----- - First line will contain $N$, denoting the size of the array. Then the next line follow. - N integers $Ai - An$. - Third line will contain $Q$, denoting the number of queries. Then the next $Q$ lines follow -description of each query. - Each query consists of either type 1 or type 2 and each query gives you three elements either -{$k$ $l$ $r$} or {$k$ $i$ $val$} -----Output:----- For each Query of Type 1 Output either "YES" or "NO" Without Quotes. -----Constraints----- - $1 \leq N \leq 20000$ - $1 \leq Q \leq 20000$ - $2 \leq Ai \leq 1000000$ - $1 \leq i ,l,r \leq N$ - $1 \leq val \leq 1000000$ - $1 \leq l \leq r$ -----Subtasks----- Subtask 1 :-40 points - Values of prime factors of all numbers $val$ and $Ai$ is between 2 to 40 only. Subtask 2 :- 60 points - Original Constraints -----Sample Input:----- 4 2 2 3 4 4 1 1 2 1 3 4 2 3 3 1 1 4 -----Sample Output:----- YES NO YES -----EXPLANATION:----- -Query 1 :- product of numbers in range 1 to 2=2 * 2=4 (perfect square so YES) -Query 2:- product of numbers in range 3 to 4 = 3 * 4 = 12 (not perfect square so NO) -Query 3:- multiply number at index3 with 3 so number at index 3= 3*3 = 9 . -Query 4:- product of numbers in range 1 to 4 = 2 * 2 * 9 * 4 = 144 (perfect square so YES) The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def update(index, value, bi_tree): while index < len(bi_tree): bi_tree[index] += value index += index & -index def get_sum(index, bi_tree): ans = 0 while index > 0: ans += bi_tree[index] index -= index & -index return ans def get_range_sum(left, right, bi_tree): ans = get_sum(right, bi_tree) - get_sum(left - 1, bi_tree) return ans def solve(x): s = set() res = 1 i = 2 while (i * i <= x): count = 0 while (x % i == 0): x = x // i count += 1 if (count % 2): s.add(i) i += 1 if (x > 0): s.add(x) return s n = int(input()) l = [0] + [int(i) for i in input().split()] bit = [[0 for i in range(n + 1)] for i in range(101)] for i in range(1, n + 1): s = solve(l[i]) for j in s: update(i, 1, bit[j]) q = int(input()) for i in range(q): k, a, b = [int(i) for i in input().split()] if (k == 1): f = 1 for i in range(2, 100): res = get_range_sum(a, b, bit[i]) if (res % 2): f = 0 break if (f): print("YES") else: print("NO") else: s = solve(b) for j in s: update(a, 1, bit[j]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a binary string S of N bits. The bits in the string are indexed starting from 1. S[i] denotes the ith bit of S. Let's say that a sequence i1, i2, …, iK(1 ≤ K; 1 ≤ i1 < i2 < … < iK ≤ N) produces a palindrome when applied to S, if the string S[i1] S[i2] … S[ik] is a palindrome (that is, reads the same backward or forward). In addition, a sequence i1, i2, …, iK(1 ≤ K; 1 ≤ i1 < i2 < … < iK ≤ N) is said to be exponential, if ij + 1 = p * ij for each integer 1 ≤ j < K and for some integer p > 1. Note, that a sequence of one element is always exponential. Your task is to count the number of exponential sequences that produce a palindrome when applied to S. -----Input----- The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of description for each test case contains a binary string S of N bits. -----Output----- For each test case, output a single line containing the number of exponential sequences that produce a palindrome. -----Constraints----- - 1 ≤ T ≤ 10 - Subtask 1(20 points): 1 ≤ N ≤ 20 - Subtask 2(30 points): 1 ≤ N ≤ 1000 - Subtask 3(50 points): 1 ≤ N ≤ 5 × 105 -----Note----- The first test of the first subtask is the example test. It's made for you to make sure that your solution produces the same verdict both on your machine and our server. -----Time Limits----- Time limit for the first and the second subtasks is 3s. Time limit for the third subtask is 6s. -----Example----- Input: 2 11010 101001011 Output: 9 18 -----Explanation of the first case in the example test----- The following sequences are counted in the answer: {1}, {2}, {3}, {4}, {5}, {1, 2}, {1, 4}, {2, 4}, {1, 2, 4}. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def powerset(s): n = len(s) masks = [1 << j for j in range(n)] for i in range(2**n): yield [j + 1 for j in range(n) if (masks[j] & i)] def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) def special(l): n = len(l) for i in range(n): lis = [i + 1] yield lis for j in range(i + 1, n): p = l[j] / l[i] if p <= 1 or int(p) != p: continue lis = [i + 1, j + 1] yield lis sk = (j + 1) * int(p) while sk <= n: lis.append(sk) sk *= int(p) yield lis def expIndices(l): a = list(zip(l, l[1:])) if len(a) == 0: return True else: p = a[0][1] / a[0][0] if p <= 1 or int(p) != p: return False for i in range(1, len(a)): if a[i][1] / a[i][0] != p: return False return True def main(): for _ in range(eval(input())): S = input() count = 0 for i in special(range(1, len(S) + 1)): s = [S[j - 1] for j in i] if s == s[::-1]: count += 1 print(count) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (l — left, s — straight, r — right) and a light p for a pedestrian crossing. [Image] An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time. Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible. -----Input----- The input consists of four lines with each line describing a road part given in a counter-clockwise order. Each line contains four integers l, s, r, p — for the left, straight, right and pedestrian lights, respectively. The possible values are 0 for red light and 1 for green light. -----Output----- On a single line, print "YES" if an accident is possible, and "NO" otherwise. -----Examples----- Input 1 0 0 1 0 1 0 0 0 0 1 0 0 0 0 1 Output YES Input 0 1 1 0 1 0 1 0 1 1 0 0 0 0 0 1 Output NO Input 1 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 Output NO -----Note----- In the first example, some accidents are possible because cars of part 1 can hit pedestrians of parts 1 and 4. Also, cars of parts 2 and 3 can hit pedestrians of part 4. In the second example, no car can pass the pedestrian crossing of part 4 which is the only green pedestrian light. So, no accident can occur. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python lanes = [] for i in range(4): lanes.append(list(map(int, input().split()))) lanes.extend(lanes) for i in range(4): ln = lanes[i] if (ln[3] and (ln[0] or ln[1] or ln[2])) or \ (ln[0] and lanes[i + 3][3]) or \ (ln[1] and lanes[i + 2][3]) or \ (ln[2] and lanes[i + 1][3]): print('YES') break else: print('NO') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: -----Problem Statement----- One of the things JEC is known for is its GR (Group Recreation) where juniors and seniors do friendly interaction ;P As for the new session of 2020 seniors decided to have their first GR and give them some treat. Juniors were excited about it they came to college canteen aligned in a line and counted themselves one by one from left to right so that every junior gets his/her treat. But seniors played a game and they will treat only the ones who passes in this game. Game is simple all they need to do is to alternate their language (between Hindi and English) while telling their positions that is if the junior just before you told 2 in English you need to say 3 in Hindi . You do not want to be the one left without a treat. You are the junior standing at position $X$ from left and the counting could start from left or right you have to predict which number you have to speak and in which language when your turn comes. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains 2 lines first consist 2 space separated integers, $N$ (total count) , $X$ (your position from left), next line consist of 2 space separated characters L or R (Direction from which counting starts L-left, R-Right) and H or E (the language to start counting). -----Output:----- For each testcase, output a single line consisting space seperated Integer P and Character L where P is the number you will speak and L is the language (H or E). -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 120$ - $1 \leq X \leq N$ -----Sample Input:----- 2 15 5 L H 20 14 R E *try to trim extra white spaces like new line during input in case of wrong answer -----Sample Output:----- 5 H 7 E -----EXPLANATION:----- - When counting starts from left with H it alternates like H E H E H….. on the fifth position H comes - When Count starts from right with E it alternates like E H E H E H E….. with E on the position of 14th student from right. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) while t: t=t-1 n,x=input().split() n=int(n) x=int(x) d,l=input().split() if d=='L': p=x elif d=='R': p=(n-x)+1 if p%2==1: if l=='H': lang='H' else: lang='E' elif p%2==0: if l=='H': lang='E' else: lang='H' print(p,lang) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sunita has lots of tasks pending and she has no time to complete. She needs your help and wants you complete the task. You are given a list of integers and two values $N$ and $K$ $-$ the size of array of integers and the numbers of partitions to be made respectively. You have to partition the list of integers without changing the order of elements ,into exactly $K$ parts. Calculate Greatest Common Divisor of all $K$ partition and sum up the gcd values for each partition. Maximize the sum obtained. Can you help Sunita ? -----Input:----- - First line will contain $T$, number of test cases. Then the test cases follow. - Each test case contains of a single line of input, two integers $N, K$. - Next line contains $N$ integers $-$ the list of integers. -----Output:----- For each test case, output in a single line integer $-$ the maximal result. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N, K \leq 250$ - $1 \leq K \leq N$ - $1 \leq A[i] \leq 1e5$ -----Sample Input:----- 1 4 2 5 6 3 2 -----Sample Output:----- 6 -----EXPLANATION:----- [5] [6 3 2] is the best partition [5 + GCD(6,3,2)] = 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin,stdout from math import gcd for _ in range(int(stdin.readline())): # n=int(stdin.readline()) k-pieces n,k=list(map(int,stdin.readline().split())) a=list(map(int,stdin.readline().split())) gr=[[0 for _ in range(n)]for _ in range(n)];ans=0;k-=1 for sz in range(n): for i in range(n-sz): j=i+sz if sz==0:gr[i][j]=a[i] else: gr[i][j]=gcd(gr[i+1][j],gr[i][j-1]) # print(*gr,sep='\n') dp=[[0 for _ in range(n)]for _ in range(k+1)] for i in range(n): dp[0][i]=gr[0][i] for i in range(1,k+1): for j in range(i,n): for par in range(j-1,-1,-1): dp[i][j]=max(dp[i][j],gr[par+1][j]+dp[i-1][par]) # print(*dp,sep='\n') print(dp[k][n-1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Kabir likes Tara's smile and wants to look at her smile. They are sitting in the class and you are friends with Kabir. You have to place a mirror (point size) in the front wall of the class so that Kabir can have a glimpse of Tara's smile. Consider the front wall as x-axis . You are given the coordinates of position of Kabir (x1,y1)$(x1,y1)$ and Tara (x2,y2)$(x2,y2)$. Find the position where the mirror should be placed. -----Input:----- - First line will contain T$T$, number of testcases. Then the testcases follow. - First line of each testcase contains two integers x1,y1$x1, y1$. - Second line of each testcase contains two integers x2,y2$x2, y2$. -----Output:----- For each testcase, print the x-coordinate of the mirror. Absolute error of 10−2$10^{−2}$ is allowed. -----Constraints:----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤x1,y1,x2,y2≤105$1 \leq x1,y1,x2,y2 \leq 10^5 $ -----Sample Input:----- 1 1 1 4 4 -----Sample Output:----- 1.60 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): p = [int(x) for x in input().split()] q = [int(x) for x in input().split()] q[1] *= -1 m = (q[1]-p[1])/(q[0]-p[0]) c = p[1] - m*p[0] print("{:.2f}".format(-c/m)) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ashish and Vivek play a game on a matrix consisting of $n$ rows and $m$ columns, where they take turns claiming cells. Unclaimed cells are represented by $0$, while claimed cells are represented by $1$. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends. If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally. Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. -----Input----- The first line consists of a single integer $t$ $(1 \le t \le 50)$ — the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $n$, $m$ $(1 \le n, m \le 50)$ — the number of rows and columns in the matrix. The following $n$ lines consist of $m$ integers each, the $j$-th integer on the $i$-th line denoting $a_{i,j}$ $(a_{i,j} \in \{0, 1\})$. -----Output----- For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes). -----Example----- Input 4 2 2 0 0 0 0 2 2 0 0 0 1 2 3 1 0 1 1 1 0 3 3 1 0 0 0 0 0 1 0 0 Output Vivek Ashish Vivek Ashish -----Note----- For the first case: One possible scenario could be: Ashish claims cell $(1, 1)$, Vivek then claims cell $(2, 2)$. Ashish can neither claim cell $(1, 2)$, nor cell $(2, 1)$ as cells $(1, 1)$ and $(2, 2)$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $(1, 1)$, the only cell that can be claimed in the first move. After that Vivek has no moves left. For the third case: Ashish cannot make a move, so Vivek wins. For the fourth case: If Ashish claims cell $(2, 3)$, Vivek will have no moves left. 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 = [int(x) for x in input().split()] grid = [[int(x) for x in input().split()] for _ in range(n)] rows = sum(1 for x in grid if all(y == 0 for y in x)) cols = sum(1 for j in range(m) if all(grid[i][j] == 0 for i in range(n))) res = min(rows, cols) print("Ashish" if res % 2 else "Vivek") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time. Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order they came. The i-th request is characterized by two values: s_{i} — the day when a client wants to start the repair of his car, d_{i} — duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on. Polycarp is making schedule by processing requests in the order from the first to the n-th request. He schedules the i-th request as follows: If the car repair shop is idle for d_{i} days starting from s_{i} (s_{i}, s_{i} + 1, ..., s_{i} + d_{i} - 1), then these days are used to repair a car of the i-th client. Otherwise, Polycarp finds the first day x (from 1 and further) that there are d_{i} subsequent days when no repair is scheduled starting from x. In other words he chooses the smallest positive x that all days x, x + 1, ..., x + d_{i} - 1 are not scheduled for repair of any car. So, the car of the i-th client will be repaired in the range [x, x + d_{i} - 1]. It is possible that the day x when repair is scheduled to start will be less than s_{i}. Given n requests, you are asked to help Polycarp schedule all of them according to the rules above. -----Input----- The first line contains integer n (1 ≤ n ≤ 200) — the number of requests from clients. The following n lines contain requests, one request per line. The i-th request is given as the pair of integers s_{i}, d_{i} (1 ≤ s_{i} ≤ 10^9, 1 ≤ d_{i} ≤ 5·10^6), where s_{i} is the preferred time to start repairing the i-th car, d_{i} is the number of days to repair the i-th car. The requests should be processed in the order they are given in the input. -----Output----- Print n lines. The i-th line should contain two integers — the start day to repair the i-th car and the finish day to repair the i-th car. -----Examples----- Input 3 9 2 7 3 2 4 Output 9 10 1 3 4 7 Input 4 1000000000 1000000 1000000000 1000000 100000000 1000000 1000000000 1000000 Output 1000000000 1000999999 1 1000000 100000000 100999999 1000001 2000000 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from bisect import bisect_left, insort_left a = [] n = int(input()) for _ in range(n): #print(a) s, d = list(map(int, input().split())) if len(a) == 0: print(s, s+d - 1) a.append((s, s + d - 1)) continue p = bisect_left(a, (s, s + d - 1)) #print('p', p) ok = True if p > 0 and a[p-1][1] >= s: ok = False if p < len(a) and a[p][0] <= s + d - 1: ok = False if ok: insort_left(a, (s, s + d - 1)) print(s, s + d - 1) else: ok = False for i in range(len(a)): if i == 0: if a[0][0] > d: print(1,d) a = [(1, d)] + a ok = True break else: if a[i - 1][1] + d < a[i][0]: print(a[i - 1][1] + 1, a[i - 1][1] + d) insort_left(a, (a[i - 1][1] + 1, a[i - 1][1] + d)) ok = True break if not ok: print(a[-1][1] + 1, a[-1][1] + d) insort_left(a, (a[-1][1] + 1, a[-1][1] + d)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given a Complete Binary Tree of ‘n’ depth, you can perform 4 types of mirror operation on the tree:- Mirror on the right. The tree is mirrored to the right and rightmost node on every level is connected with the mirrored corresponding node. Mirror on the left. The tree is mirrored to the left and leftmost node on every level is connected with the mirrored corresponding node. Mirror on the top. The tree is mirrored to the top and topmost nodes are connected with corresponding nodes. Mirror on the bottom. The tree is mirrored to the bottom and bottom most nodes are connected with the corresponding nodes. See the image for details. Mirror Right: Mirror Bottom: You are given ‘q’ queries, each performing this type of operation or asking for the no of edges in the produced graph. Queries are of the form “1 x” or “2” where x is 1 for right, 2 for left, 3 for top or 4 for bottom. 1 x: Perform x operation on the result graph. 2: Print the no of edges in the graph. Since it can be very large, print it modulo 1000000007. -----Input:----- - First line will contain $n$, the depth of the initial tree and $q$, the number of queries. - Next $q$ lines contain queries of the form "1 $x$" or "2". -----Output:----- For each query of type "2", output a single line containing the no of edges in the graph modulo 1000000007. -----Constraints----- - $1 \leq n \leq 1000$ - $1 \leq q \leq 10^5$ - $1 \leq x \leq 4$ -----Sample Input:----- 2 3 1 1 1 4 2 -----Sample Output:----- 38 -----EXPLANATION:----- Initial no of edges = 6 After the operation 1 1, no of edges = 15 After the operation 1 4, no of edges = 38 At operation 2, we print the no of edges that is 38. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import os,sys from io import BytesIO, IOBase def ii(): return int(input()) def si(): return input() def mi(): return list(map(int,input().split())) def li(): return list(mi()) import math import collections def CountFrequency(arr): return collections.Counter(arr) for i in range(1): n,q=mi() p=pow(2,n+1)-2 t=1 b=pow(2,n) s=n+1 for i in range(q): a=li() if len(a)==2: if a[1]==1 or a[1]==2: p*=2 p+=s t*=2 b*=2 else: p*=2 if a[1]==3: p+=t t=b s*=2 else: p+=b b=t s*=2 else: print(p%1000000007) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Three Best Friends $AMAN$ , $AKBAR$ , $ANTHONY$ are planning to go to “GOA” , but just like every other goa trip plan there is a problem to their plan too. Their parents will only give permission if they can solve this problem for them They are a given a number N and they have to calculate the total number of triplets (x ,y ,z) Satisfying the given condition y * x +z=n. For ex if N=3 Then there exist 3 triplets( x ,y ,z): (1,1,2) , (1,2,1) , (2,1,1) which satisfy the condition Help the group to get permission for the trip -----Input:----- - First line will contain the number $N$. -----Output:----- the possible number of triplets satisfying the given condition -----Constraints----- - $2 \leq N \leq 10^6$ -----Sample Input:----- 3 -----Sample Output:----- 3 -----EXPLANATION:----- there exist 3 triplets ( x ,y ,z): (1,1,2) , (1,2,1) , (2,1,1) which satisfy the condition 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 get_array(): return list(map(int , sys.stdin.readline().strip().split())) def get_ints(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() import sys sys.setrecursionlimit(10**9) from math import sqrt,ceil,floor n=int(input()) co=0 ans=0 for i in range(1,n): ans+=n//i if n%i==0: ans-=1 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: 3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or alive NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a $2 \times n$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $(1, 1)$ to the gate at $(2, n)$ and escape the maze. The girl can only move between cells sharing a common side. However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type. After hours of streaming, NEKO finally figured out there are only $q$ such moments: the $i$-th moment toggles the state of cell $(r_i, c_i)$ (either from ground to lava or vice versa). Knowing this, NEKO wonders, after each of the $q$ moments, whether it is still possible to move from cell $(1, 1)$ to cell $(2, n)$ without going through any lava cells. Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her? -----Input----- The first line contains integers $n$, $q$ ($2 \le n \le 10^5$, $1 \le q \le 10^5$). The $i$-th of $q$ following lines contains two integers $r_i$, $c_i$ ($1 \le r_i \le 2$, $1 \le c_i \le n$), denoting the coordinates of the cell to be flipped at the $i$-th moment. It is guaranteed that cells $(1, 1)$ and $(2, n)$ never appear in the query list. -----Output----- For each moment, if it is possible to travel from cell $(1, 1)$ to cell $(2, n)$, print "Yes", otherwise print "No". There should be exactly $q$ answers, one after every update. You can print the words in any case (either lowercase, uppercase or mixed). -----Example----- Input 5 5 2 3 1 4 2 4 2 3 1 4 Output Yes No No No Yes -----Note----- We'll crack down the example test here: After the first query, the girl still able to reach the goal. One of the shortest path ways should be: $(1,1) \to (1,2) \to (1,3) \to (1,4) \to (1,5) \to (2,5)$. After the second query, it's impossible to move to the goal, since the farthest cell she could reach is $(1, 3)$. After the fourth query, the $(2, 3)$ is not blocked, but now all the $4$-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline N, Q = list(map(int, readline().split())) state = [[False]*(N+2) for _ in range(2)] cnt = 0 Ans = [None]*Q for qu in range(Q): r, c = list(map(int, readline().split())) r -= 1 c -= 1 state[r][c] = not state[r][c] res = state[r-1][c-1] + state[r-1][c] + state[r-1][c+1] if state[r][c]: cnt += res else: cnt -= res Ans[qu] = 'No' if cnt else 'Yes' print('\n'.join(Ans)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: One day Chef was playing with numbers. He loves Lowest Common Multiple (LCM) too much and he is a very curious guy. He always try to do new things. Now he want to make a large number with it. But he doesn't want to take too many numbers. He is willing to take only three numbers less than or equal to N (not necessarily distinct ) and from those three number he want get the maximum number by taking LCM of the numbers. As he is busy in playing some more tricks of maths, he assign this task to you. -----Input----- First line of input contains an integer t ( t<=1000 ), Number of test cases. t line follows an integer N -----Output----- Print t lines contains a single integer — the maximum possible LCM of three not necessarily distinct positive integers that are not greater than N. -----Constraints----- 1<= N <= 10^6 -----Example----- Input: 2 9 7 Output: 504 210 -----Explanation----- Example case 2. For the last example, we can chose numbers 7, 6, 5 and the LCM of them is 7•6•5 = 210. It is the maximum value we can get. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from fractions import gcd for testCases in range(eval(input())): n = eval(input()) if n == 1: print('1') elif n == 2: print('2') elif n == 3: print('6') else: c = n*(n-1) k = n - 2 while True: if gcd(k,n-1) == 1 and gcd(k,n) == 1: break k -= 1 d = (n-1)*(n - 2) k1 = n - 3 while True: if gcd(k1,n-1) == 1 and gcd(k1,n-2) == 1: break k1 -= 1 print(max(c*k,d*k1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Consider the following algorithm order(arr, i) { if length(arr) <= 1 { return arr } l = [] r = [] n = length(arr) - 1 for j in 0, 1, ..., n { if ( (arr[j] modulo power(2,i+1)) < power(2,i) ) { append arr[j] to l }else{ append arr[j] to r } } l = order(l, i + 1) r = order(r, i + 1) c = concatenate(l, r) return c } Note that $concatenate(l, r)$ returns an array which is the array $l$, followed by the array $r$. Similarly $power(x,y)$ returns $x^y$. Let $a$ be the array $a_0,a_1,a_2,a_3, \ldots,a_n$ where $a_j = j$ for each index $j$ and the last index $n = (2^p-1)$ for a fixed integer parameter $p$. Given an integer $p$ and an index $idx$, your task is calculate the element at index $idx$ in the array returned by executing $order(a, 0)$. For example, suppose $ p = 3$ and $idx = 3$. - The initial array is $a = [0, 1, 2, 3, 4, 5, 6, 7]$. - Executing $order(a, 0)$ first creates two new arrays $l == [0, 2, 4, 6]$ and $r == [1, 3, 5, 7]$. - Next, $order(l, 1)$ and $order(r, 1)$ are executed. - $order(l, 1)$, in turn, executes $order([0, 4], 2)$ and $order([2, 6], 2)$ which return $[0, 4]$ and $[2, 6]$, respectively. These are then concatenated, so $order(l, 1)$ returns $[0, 4, 2, 6]$. - Similarly, $order(r, 1)$ returns $[1, 5, 3, 7]$. - These two are concatenated as the final result, so the array returned by $order(a, 0)$ is $[0, 4, 2, 6, 1, 5, 3, 7]$. So, if the input is $p = 3$, and $idx = 3$, the answer is $6$. If $p = 3$ and $idx = 7$, the answer should be $7$. -----Input Format:----- - The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows. - Each testcase is described by a single line with two integers: $p$ and $idx$, where $p$ is the parameter that determines the length of the array $a$ and $idx$ is the index at which you have to report the value in the output of $order(a, 0)$. -----Output Format:----- - You should print the answer in a new line for each testcase, which should be a single integer, the element at index $idx$ after executing $order(a, 0)$ for the array $a$ defined by the parameter $p$. -----Constraints:----- - $1 \leq T \leq 10$ - $1 \leq p \leq 50$ - $0 \leq idx \leq 2^p-1$ -----SUBTASKS:----- - Subtask 1: 20% points : $1 \leq p \leq 20$ - Subtask 2: 80% points: Original constraints -----Sample Input:----- 2 3 3 3 7 -----Sample Output:----- 6 7 -----Explanation:----- Both the testcases have been explained in the problem statement. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): p, idx = map(int, input().split()) b = bin(idx)[2:] b = ('0' * (p - len(b)) + b)[::-1] print(int(b, 2)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's define the niceness of a sequence of positive integers X1,X2,…,XN$X_1, X_2, \dots, X_N$ as the sum of greatest common divisors of all pairs of its elements, i.e. N∑i=1N∑j=i+1gcd(Xi,Xj).∑i=1N∑j=i+1Ngcd(Xi,Xj).\sum_{i=1}^N \sum_{j=i+1}^N \mathrm{gcd}(X_i, X_j)\;. For example, the niceness of the sequence [1,2,2]$[1, 2, 2]$ is gcd(1,2)+gcd(1,2)+gcd(2,2)=4$gcd(1, 2) + gcd(1, 2) + gcd(2, 2) = 4$. You are given a sequence A1,A2,…,AN$A_1, A_2, \dots, A_N$; each of its elements is either a positive integer or missing. Consider all possible ways to replace each missing element of A$A$ by a positive integer (not necessarily the same for each element) such that the sum of all elements is equal to S$S$. Your task is to find the total niceness of all resulting sequences, i.e. compute the niceness of each possible resulting sequence and sum up all these values. Since the answer may be very large, compute it modulo 109+7$10^9 + 7$. -----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 two space-separated integers N$N$ and S$S$. - The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$. Missing elements in this sequence are denoted by −1$-1$. -----Output----- For each test case, print a single line containing one integer — the total niceness modulo 109+7$10^9 + 7$. -----Constraints----- - 1≤T≤20$1 \le T \le 20$ - 1≤N,S≤50$1 \le N, S \le 50$ - 1≤Ai≤50$1 \le A_i \le 50$ or Ai=−1$A_i = -1$ for each valid i$i$ -----Subtasks----- Subtask #1 (30 points): - 1≤N,S≤18$1 \le N, S \le 18$ - 1≤Ai≤18$1 \le A_i \le 18$ or Ai=−1$A_i = -1$ for each valid i$i$ Subtask #2 (70 points): original constraints -----Example Input----- 3 3 3 1 1 -1 4 8 1 -1 -1 3 3 10 -1 -1 -1 -----Example Output----- 3 23 150 -----Explanation----- Example case 1: There is only one possible way to fill in the missing element; the resulting sequence is [1,1,1]$[1, 1, 1]$. Its niceness is 3$3$. Example case 2: There is only three possible ways to fill in the missing elements; the resulting sequences are [1,1,3,3]$[1, 1, 3, 3]$, [1,3,1,3]$[1, 3, 1, 3]$, and [1,2,2,3]$[1, 2, 2, 3]$. The sum of their niceness is 8+8+7=23$8 + 8 + 7 = 23$. 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 mod = 10**9 + 7 from math import gcd def fac50(): f = [0]*51 f[0] ,f[1] = 1,1 for i in range(1,51):f[i] = (f[i-1]*i)%mod return f def gcd110(): gc = [[0]*111 for i in range(111)] for i in range(111): for j in range(111):gc[i][j] = gcd(i,j) return gc factorials,gcds = fac50(),gcd110() def rule_asc(n,l): a,k = [0 for i in range(n + 1)],1 a[1] = n while k != 0: x,y = a[k - 1] + 1,a[k] - 1 k -= 1 while x <= y and k < l - 1: a[k],y = x,y-x k += 1 a[k] = x + y yield a[:k + 1] def niceness(s): t = 0 for i in range(len(s)): for j in range(i+1,len(s)):t = (t + gcds[s[i]][s[j]])%mod return t def permcount(s,c): f,p = [s.count(x) for x in set(s)],factorials[c] for e in f:p = (p*pow(factorials[e],mod-2,mod))%mod return p def main(): for i in range(int(input())): n,s = [int(item) for item in input().split()] a = [int(item) for item in input().split()] b = [i for i in a if i != -1] s , ones = s - sum(b),a.count(-1) if s < 0:print(0) elif (s == 0 and ones == 0):print(niceness(a)%mod) elif (s > 0 and ones == 0):print(0) else: t = 0 for seq in rule_asc(s,ones): if len(seq) == ones: t = (t + (((permcount(seq,ones))%mod)*(niceness(b+seq)%mod))%mod)%mod print(t) def __starting_point():main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle. In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n. For each cell i you are given two values: l_{i} — cell containing previous element for the element in the cell i; r_{i} — cell containing next element for the element in the cell i. If cell i contains information about the element which has no previous element then l_{i} = 0. Similarly, if cell i contains information about the element which has no next element then r_{i} = 0. [Image] Three lists are shown on the picture. For example, for the picture above the values of l and r are the following: l_1 = 4, r_1 = 7; l_2 = 5, r_2 = 0; l_3 = 0, r_3 = 0; l_4 = 6, r_4 = 1; l_5 = 0, r_5 = 2; l_6 = 0, r_6 = 4; l_7 = 1, r_7 = 0. Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values l_{i}, r_{i}. Any other action, other than joining the beginning of one list to the end of another, can not be performed. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located. Each of the following n lines contains two integers l_{i}, r_{i} (0 ≤ l_{i}, r_{i} ≤ n) — the cells of the previous and the next element of list for cell i. Value l_{i} = 0 if element in cell i has no previous element in its list. Value r_{i} = 0 if element in cell i has no next element in its list. It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells. -----Output----- Print n lines, the i-th line must contain two integers l_{i} and r_{i} — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them. -----Example----- Input 7 4 7 5 0 0 0 6 1 0 2 0 4 1 0 Output 4 7 5 6 0 5 6 1 3 2 2 4 1 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) arr = [] for i in range(n): l,r = map(int, input().split()) arr.append([l,r]) lts = [] for i in range(n): if arr[i][0] == 0: l = i j = i while arr[j][1] != 0: j = arr[j][1] - 1 r = j lts.append([l,r]) for i in range(1, len(lts)): arr[lts[i-1][1]][1] = lts[i][0] + 1 arr[lts[i][0]][0] = lts[i-1][1] + 1 for i in range(n): print(arr[i][0], arr[i][1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a permutation $p=[p_1, p_2, \ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \le m \le n$) beautiful, if there exists two indices $l, r$ ($1 \le l \le r \le n$), such that the numbers $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$. For example, let $p = [4, 5, 1, 3, 2, 6]$. In this case, the numbers $1, 3, 5, 6$ are beautiful and $2, 4$ are not. It is because: if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$; if $l = 3$ and $r = 5$ we will have a permutation $[1, 3, 2]$ for $m = 3$; if $l = 1$ and $r = 5$ we will have a permutation $[4, 5, 1, 3, 2]$ for $m = 5$; if $l = 1$ and $r = 6$ we will have a permutation $[4, 5, 1, 3, 2, 6]$ for $m = 6$; it is impossible to take some $l$ and $r$, such that $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$ for $m = 2$ and for $m = 4$. You are given a permutation $p=[p_1, p_2, \ldots, p_n]$. For all $m$ ($1 \le m \le n$) determine if it is a beautiful number or not. -----Input----- The first line contains the only integer $t$ ($1 \le t \le 1000$)  — the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the given permutation $p$. The next line contains $n$ integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$, all $p_i$ are different) — the given permutation $p$. It is guaranteed, that the sum of $n$ from all test cases in the input doesn't exceed $2 \cdot 10^5$. -----Output----- Print $t$ lines — the answers to test cases in the order they are given in the input. The answer to a test case is the string of length $n$, there the $i$-th character is equal to $1$ if $i$ is a beautiful number and is equal to $0$ if $i$ is not a beautiful number. -----Example----- Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 -----Note----- The first test case is described in the problem statement. In the second test case all numbers from $1$ to $5$ are beautiful: if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$; if $l = 3$ and $r = 4$ we will have a permutation $[1, 2]$ for $m = 2$; if $l = 2$ and $r = 4$ we will have a permutation $[3, 1, 2]$ for $m = 3$; if $l = 2$ and $r = 5$ we will have a permutation $[3, 1, 2, 4]$ for $m = 4$; if $l = 1$ and $r = 5$ we will have a permutation $[5, 3, 1, 2, 4]$ for $m = 5$. 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())): input() nums = [int(x) for x in input().split()] new_ar = list(zip(nums,[i for i in range(len(nums))])) new_ar.sort() maxx = new_ar[0][1] minn = new_ar[0][1] s="1" for j in range(1,len(new_ar)): if(new_ar[j][1]>maxx): maxx = new_ar[j][1] if(new_ar[j][1]<minn): minn = new_ar[j][1] if(maxx-minn<j+1): s+="1" else: s+="0" print(s) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Oliver and Nova are true lovers. Inspite of knowing that Nova will die Oliver married her at the lake where they met. But they had a conflict about even and odd numbers. Nova likes the odd numbers and Oliver prefers even. One day they went to a fair where Oliver bought some square shaped marshmallows and Nova bought some round shaped. Then they decided to play a game. They will pick a natural number N . Nova will sum up the odd numbers from 1 to N and and she will notedown LCM of R(R is defined in the picture) and the sum she calculated before. And Oliver will sum up the even numbers from 1 to N and and he will notedown LCM of S(S is defined in the picture) and the sum he calculated before. You must use the ceil value of R and S. Now whose LCM is strictly greater than the other will win.If both of their LCM is equal Nova will win because Oliver is afraid of Nova. $N.B.$ define the value of pi with $acos(-1)$. $N.B.$ Sum of all odd number and sum of all even number will not exceed 10^18. -----Input:----- The first line contains an integer $T$ — the number of test cases in the input. Next, T test cases are given, one per line. Each test case is a positive integer $N$ . -----Output:----- Print T answers to the test cases. In each test cases, If Oliver wins the game, print "Nova's gonna kill me" (without quotes) . If Nova wins the game, print "YESS(sunglass emo)" (without quotes) . -----Constraints----- - $1 \leq T \leq 2000$ - $1 \leq N \leq 1845271$ -----Sample Input:----- 1 111 -----Sample Output:----- YESS(sunglass emo) 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 lcm(a, b): return (a*b)//gcd(a, b) def gcd(a, b): if b == 0: return a return gcd(b, a%b) for _ in range(int(input())): n = int(input()) na = math.ceil((2*n)/math.acos(-1)) nb = ((n+1)//2)**2 nlcm = lcm(na, nb) oa = math.ceil(n/2) ob = (n//2)*(n//2+1) olcm = lcm(oa, ob) if olcm > nlcm: print("Nova's gonna kill me") else: print("YESS(sunglass emo)") # cook your dish here ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef would like go shopping to buy ingredients for his special dish. The local grocery store has some special discount offers. If you want to buy some set of ingredients you will pay for all ingredients except the cheapest one. Chef would like to spend as little money as possible. You have to help him. :) The store is pretty small and stocks only one unit of each ingredients. Opposite each ingredient is a hanging price tag corresponding to it. The salesman walked away for a minute, giving Chef an opportunity to swap some price tags. He would like to swap some tags to minimize his purchase cost. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the number of ingredients Chef needs to buy. The second line contains N space-separated integers A1, A2, ... , AN denoting the value written on the price tags opposite the needed ingredients. The third line contains a single integer M denoting the number of special offers. The following M lines lists inventory of special offers, one offer per line. Each line contains an integer Ci followed by Ci integers denoting the indices of ingredients constituting the ith discount offer. -----Output----- For each test case, output a single line containing the minimal purchase cost. -----Constraints----- - T ≤ 5 - 1 ≤ N ≤ 15 - 1 ≤ Ai ≤ 106 - 0 ≤ M ≤ 2N-1 - 2 ≤ Ci ≤ N - Subtask 1 (15 points): 1 ≤ N ≤ 5 - Subtask 2 (25 points): 1 ≤ N ≤ 10 - Subtask 3 (60 points): 1 ≤ N ≤ 15 -----Example----- Input: 1 4 1 2 3 4 3 2 1 2 2 3 4 3 1 2 3 Output: 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from itertools import permutations as p def disc(a,b): for ai in a: for bi in b: if ai==bi: return False return True for i in range(eval(input())): n = eval(input()) arr = list(map(int,input().split())) perms = list(p(arr)) m = eval(input()) offer = {} for i in range(m): dup = list(map(int,input().split())) try: offer[dup[0]].append(dup[1:]) except: offer[dup[0]] = [dup[1:]] ans = sum(arr) if n==1: print(ans) elif n==2: try: if len(offer[2])>=1: ans -= min(arr) except: pass print(ans) elif n==3: try: if len(offer[3])>=1: ans -= min(arr) except: pass try: if len(offer[2])>=1: value = 9999999999 for item in perms: cur = 0 cur += item[0] cur += max(item[1],item[2]) if cur<value: value = cur if value<ans: ans = value except: pass print(ans) elif n==4: try: if len(offer[4])>=1: ans -= min(arr) except: pass #print ans try: if len(offer[3])>=1: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[2],item[3]) if cur<value: value = cur if value<ans: ans = value except: pass #print ans try: if len(offer[2])>=1: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[2]) if cur<value: value = cur if value<ans: ans = value #print ans #print offer[2] if len(offer[2])>=2: flg = False end = len(offer[2]) for i in range(end): for j in range(i+1,end): if disc(offer[2][i],offer[2][j]): flg = True break #print flg if flg: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[0]) cur -= min(item[2],item[3]) if cur<value: value = cur if value<ans: ans = value except: pass print(ans) elif n==5: try: if len(offer[5])>=1: ans -= min(arr) except: pass try: if len(offer[4])>=1: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[2],item[3],item[4]) if cur<value: value = cur if value<ans: ans = value except: pass try: if len(offer[2])>=1: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[2]) if cur<value: value = cur if value<ans: ans = value if len(offer[2])>=2: flg = False end = len(offer[2]) for i in range(end): for j in range(i+1,end): if disc(offer[2][i],offer[2][j]): flg = True break if flg: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[0]) cur -= min(item[2],item[3]) if cur<value: value = cur if value<ans: ans = value except: pass try: if len(offer[3])>=1: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[2],item[3]) if cur<value: value = cur if value<ans: ans = value except: pass try: if len(offer[3])>=1 and len(offer[2])>=1: flg = False for i in offer[3]: for j in offer[2]: if disc(i,j): flg = True break if flg: value = 9999999999 for item in perms: cur = 0 cur = sum(item) cur -= min(item[1],item[0]) cur -= min(item[2],item[3],item[4]) if cur<value: value = cur if value<ans: ans = value except: pass print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a directed graph with N vertices and N edges. The vertices are numbered 1, 2, ..., N. The graph has the following N edges: (p_1, 1), (p_2, 2), ..., (p_N, N), and the graph is weakly connected. Here, an edge from Vertex u to Vertex v is denoted by (u, v), and a weakly connected graph is a graph which would be connected if each edge was bidirectional. We would like to assign a value to each of the vertices in this graph so that the following conditions are satisfied. Here, a_i is the value assigned to Vertex i. - Each a_i is a non-negative integer. - For each edge (i, j), a_i \neq a_j holds. - For each i and each integer x(0 ≤ x < a_i), there exists a vertex j such that the edge (i, j) exists and x = a_j holds. Determine whether there exists such an assignment. -----Constraints----- - 2 ≤ N ≤ 200 000 - 1 ≤ p_i ≤ N - p_i \neq i - The graph is weakly connected. -----Input----- Input is given from Standard Input in the following format: N p_1 p_2 ... p_N -----Output----- If the assignment is possible, print POSSIBLE; otherwise, print IMPOSSIBLE. -----Sample Input----- 4 2 3 4 1 -----Sample Output----- POSSIBLE The assignment is possible: {a_i} = {0, 1, 0, 1} or {a_i} = {1, 0, 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 sys sys.setrecursionlimit(10**6) n = int(input()) p = list(map(int, input().split())) c = [[] for _ in range(n)] is_leaf = [True for _ in range(n)] for i in range(n): p[i] -= 1 c[p[i]].append(i) is_leaf[p[i]] = False if sum(is_leaf) == 0: if n%2 == 0: print("POSSIBLE") else: print("IMPOSSIBLE") return for i in range(n): if is_leaf[i]: cur = i break visited_set = {cur} visited_list = [cur] while p[cur] not in visited_set: visited_list.append(p[cur]) visited_set.add(p[cur]) cur = p[cur] root = p[cur] grundy = [-1 for _ in range(n)] g_set = [set() for _ in range(n)] def dfs(x): res = 0 for v in c[x]: dfs(v) g_set[x].add(grundy[v]) while res in g_set[x]: res += 1 grundy[x] = res return res loop = [False for _ in range(n)] loop[root] = True ind = len(visited_list)-1 while visited_list[ind] != root: loop[visited_list[ind]] = True ind -= 1 #print(loop) for i in range(n): if loop[i]: for x in c[i]: if not loop[x]: dfs(x) g_set[i].add(grundy[x]) cand = [] num = 0 while num in g_set[root]: num += 1 cand.append(num) num += 1 while num in g_set[root]: num += 1 cand.append(num) for x in cand: cur = root grundy[root] = x while True: num = 0 while num in g_set[p[cur]] or num == grundy[cur]: num += 1 grundy[p[cur]] = num if p[cur] == root: break cur = p[cur] if grundy[root] == x: #print(grundy) print("POSSIBLE") return print("IMPOSSIBLE") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Humpy, the little elephant, has his birthday coming up. He invited all his cousins but doesn’t know how many of them are really coming as some of them are having exams coming up. He will only get to know how many of them are coming on the day of his birthday. He ordered sugarcane for his party, of length L. Humpy’s mom decided that she will be dividing the sugarcane among Humty and his friends in a way such that they get the sugarcane in ratio of their ages. Your task is to determine whether it is possible to serve sugarcane to everyone as integral multiples of their ages. -----INPUT----- First line of input contains an integer N, denoting the number of test cases. Then N test cases follow. The first line of each test case contains three integers K, L and E. K denoting the number of friends coming; L denoting the length of the sugarcane and E denoting the age of the little elephant. Next line has K space separated integers denoting the age of friends who came to the party. -----OUTPUT----- For each test case, output “YES” (without quotes) if everyone gets their part as integral multiples of their ages; otherwise output “NO”(without quotes). -----CONSTRAINTS----- - 1 <= T<=30 - 1 <= K<=1000 - 1 <= L<=1000000 - 1 <= E<=100000 - 1 <= Age of Cousins<=100000 -----Example----- Input: 2 4 10 2 2 2 3 1 4 12 3 6 5 7 3 Output: YES NO The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # your code goes here from sys import stdin, stdout n = int(stdin.readline()) while n: n -= 1 k, l, e = map(int, stdin.readline().strip().split(' ')) a = map(int, stdin.readline().strip().split(' ')) x = float(l) / float(e + sum(a)) if x - int(x): stdout.write("NO\n") else: stdout.write("YES\n") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a tree rooted at node $1$ with $N$ vertices. The $i$$th$ vertex initially has value $A_i (1 \leq i \leq N)$. You are also given $Q$ queries. In each query you are given a vertex $V$. Let $S = \{ S_1 , S_2 , ... S_x \} $ denote the set of vertices such that $S_i$ is in the subtree of $V$, distance between $S_i$ and $V$ is even and $S_i \neq V$ for all $i$. For all $S_i$ , add $A$$S_i$ to $A_V$ and change the value of $A$$S_i$ to zero. Find the values of all the vertices after all queries are performed. Note-The distance between two vertices is defined as the number of edges traversed on the shortest path from one vertex to the other. -----Input:----- - The first line contains an integer $T$ denoting the number of test cases. - The first line of each test case contain two integers $N$ and $Q$. - The second line contains $N$ space separated integers, $A_1, A_2, ..., A_n$ denoting the initial values of the vertices. - The next $N-1$ lines contain two integers $u$ and $v$ denoting an edge between $u$and $v$. - The next $Q$ lines contain a single integer which is the query. -----Output:----- - Print a single line containing $N$ integers for each test case which is the final values of the vertices. -----Constraints:----- - $1\leq T \leq 10$ - $1 \leq N \leq 200000$ - $1 \leq Q \leq 200000$ - $0 \leq A_i \leq 10^9$ - The sum of $N$ over all test cases does not exceed $200000$. - The sum of $Q$ over all test cases does not exceed $200000$. -----Sample Input----- 1 4 3 6 2 7 3 1 2 2 3 3 4 3 2 1 -----Sample Output----- 13 5 0 0 -----Explanation----- Node $3$ has no child in its subtree which is at an even distance so there is no change in the values. Values of nodes after $1st$ query: $6, 2, 7, 3$. Node $4$ is at an even distance in the subtree of node $2$ so $A_4$ gets added to $A_2$ and $A_4$ becomes 0. Values of nodes after $2nd$ query: $6, 5, 7, 0$. Node $3$ is at an even distance in the subtree of node $1$ so $A_3$ gets added to $A_1$ and $A_3$ becomes 0. Values of nodes after $3rd$ query: $13, 5, 0, 0$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import defaultdict as dd,deque as dq def opbfs(u,vis,ll,parr): q=dq([(u,0)]) uu=u su=0 while q: u,lol=q.pop() par=parr[u] if(lol%2==0): vis[u]=1 su+=ll[u-1] ll[u-1]=0 for j in d[u]: if(j!=par): q.appendleft((j,lol+1)) ll[uu-1]=su def bfs(height,d,parr): q=dq([1]) while q: u=q.pop() height[u]=height[parr[u]]+1 for i in d[u]: if(i!=parr[u]): q.appendleft(i) parr[i]=u t=int(input()) while t: n,q=map(int,input().split()) ll=list(map(int,input().split())) d=dd(list) for i in range(n-1): u,v=map(int,input().split()) d[u].append(v) d[v].append(u) vis=[0]*(n+1) l=[] height=[0]*(n+1) parr=[0]*(n+1) bfs(height,d,parr) for i in range(q): u=int(input()) l.append((height[u],u,i)) l.sort() vis=[0]*(n+1) #print(l) for i in l: he,u,ind=i if(vis[u]==0): #print(u) opbfs(u,vis,ll,parr) print(*ll) t-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: An area named Renus, is divided into $(N \times M)$ cells. According to archaeological survey the area contains huge amount of treasure. Some cells out of $(N \times M)$ cells contain treasure. But problem is, you can't go to every cell as some of the cells are blocked. For every $a_{ij}$ cell($1 \leq i \leq N$,$1 \leq j \leq M$), your task is to find the distance of the nearest cell having treasure. Note: - You can only traverse up, down, left and right from a given cell. - Diagonal movements are not allowed. - Cells having treasure can't be blocked, only empty cells ( cells without treasure) can be blocked. -----Input Format:------ - First line contains $T$, the number of test cases. - Second line contains two space-separated integers $N\ and\ M$. - Third line contains a single integer $X$ denoting number of cells having treasures, followed by $X$ lines containing two space-separated integers $x_i$ and $y_i$ denoting position of row and column of $i^{th}$ treasure, for every $1\leq i \leq X$ - The next line contains a single integer $Y$ denoting the number of cells that are blocked, and it is followed by subsequent $Y$ lines containing two space-separated integers $u_i$ and $v_i$ denoting position of row and column of blocked cells , for every $1\leq i \leq Y$ -----Constraints:------ - $1\le T \le 100$ - $1 \le N, M \le 200$ - $1 \le X < N*M$ - $0 \le Y <(N*M) - X$ - $1 \le x_i,u_j \le N, for\ every\ 1 \le i \le X\ and\ 1 \le j \le Y$ - $1 \le y_i,v_j \le M, for\ every\ 1 \le i \le X\ and\ 1 \le j \le Y$ -----Output Format:------ For each test case print a $N \times M$ matrix where each cell consists of distance of nearest treasure. Cells that are blocked will show "$X$" (without quotes). Also cells that doesn't have access to any treasure will show "$-1$" (without quotes). Note: Co-ordinate of top left cell is $(1,1)$. -----Sample Input----- 1 3 3 2 1 1 1 3 2 2 1 2 2 -----Sample Output----- 0 1 0 X X 1 4 3 2 -----Explanation:----- - Coordinates (1,1) and (1,3) shows "0" because they contain treasure and nearest distance is 0. - Coordinates (2,1) and (2,2) shows "X" as they are blocked. - Rest shows distance of nearest cell having treasure. 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=[int(x) for x in input().split()] mat=[] ans=[] for i in range(n+2): l=[] p=[] for j in range(m+2): l.append(0) p.append(1000000000) mat.append(l) ans.append(p) y=int(input()) for i in range(y): a,b=[int(x) for x in input().split()] mat[a][b]=1 ans[a][b]=0 y=int(input()) for i in range(y): a,b=[int(x) for x in input().split()] mat[a][b]=1000000000 ans[a][b]=1000000000 for i in range(1,n+1): for j in range(1,m+1): if mat[i][j]==1 or mat[i][j]==1000000000: continue else: ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1) for i in range(n,0,-1): for j in range(m,0,-1): if mat[i][j] == 1 or mat[i][j] == 1000000000: continue else: ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1) for i in range(1,n+1): for j in range(m, 0, -1): if mat[i][j] == 1 or mat[i][j] == 1000000000: continue else: ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1) for i in range(n, 0, -1): for j in range(1,m+1): if mat[i][j] == 1 or mat[i][j] == 1000000000: continue else: ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1) for i in range(1,n+1): for j in range(1,m+1): if mat[i][j]==1 or mat[i][j]==1000000000: continue else: ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1) for i in range(n,0,-1): for j in range(m,0,-1): if mat[i][j] == 1 or mat[i][j] == 1000000000: continue else: ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1) for i in range(1,n+1): for j in range(m, 0, -1): if mat[i][j] == 1 or mat[i][j] == 1000000000: continue else: ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1) for i in range(n, 0, -1): for j in range(1,m+1): if mat[i][j] == 1 or mat[i][j] == 1000000000: continue else: ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1) for i in range(1,n+1): for j in range(1,m+1): if mat[i][j]==1000000000: print('X',end=" ") elif ans[i][j]>=1000000000: print('-1',end=" ") else: print(ans[i][j],end=" ") print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Dhote and Shweta went on a tour by plane for the first time.Dhote was surprised by the conveyor belt at the airport.As Shweta was getting bored Dhote had an idea of playing a game with her.He asked Shweta to count the number of bags whose individual weight is greater than or equal to the half of the total number of bags on the conveyor belt.Shweta got stuck in the puzzle! Help Shweta. -----Input:----- - First line will contain T$T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, one integers N$N$. - next line conatins N$N$ integers that represents weight of bag -----Output:----- For each testcase, print required answer in new line . -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤N≤105$1 \leq N \leq 10^5$ - 1≤weightofbag≤105$ 1\leq weight of bag \leq 10^5$ -----Sample Input:----- 1 4 1 2 3 4 -----Sample Output:----- 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 _ in range(t): size=int(input()) li=list(map(int,input().split())) c = 0 for i in li: if(i >=len(li)/2): c += 1 print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: -----General Statement:----- Given the actual high and low temperatures for the day and the normal high and low temperatures for that day, calculate the average difference from normal. -----Input:----- The first line of the data set for this problem is an integer that represents the number of data sets that follow. Each data set is on a separate line and consists of today’s high, today’s low, normal high, and normal low – in that order. -----Output:----- If the average difference is negative, do not output the negative sign (-). Output the amount of deviation from normal, followed by the words DEGREE(S) ABOVE NORMAL, or by the words DEGREE(S) BELOW NORMAL. Round to 1 decimal place. A trailing zero is required if the average is an integer. The output is to be formatted exactly like that for the sample output given below. -----Assumptions:----- Temperatures are in the range –15..100 degrees. The average temperature difference will not be zero. -----Discussion:----- Determine the average of the difference of the high temperatures and the difference of the low temperatures. -----Sample Input:----- 3 75 45 78 40 50 32 45 30 56 48 62 45 -----Sample Output:----- 1.0 DEGREE(S) ABOVE NORMAL 3.5 DEGREE(S) ABOVE NORMAL 1.5 DEGREE(S) BELOW NORMAL 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())): x1,y1,x2,y2=map(int,input().split()) av1=(x1+y1)/2 av2=(x2+y2)/2 if(av1>av2): print(av1-av2," DEGREE(S) ABOVE NORMAL") else: print(av2-av1," DEGREE(S) BELOW NORMAL") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Ho, Ho, Ho! It's Christmas time and our friendly grandpa Santa Claus is busy distributing gifts to all the nice children. With the rising population, Santa's workload every year gets increased and he seeks your help to wrap the gifts with fancy wrapping papers while he gets them distributed. Everything was going great until you realised that you'll fall short of wrapping paper. But luckily, you get a very innovative idea, that will allow you to pack all the remaining gifts without worrying about lack of wrapping paper. Any guesses what the idea is? Using ice for wrapping, obviously! That's the only thing available at the North Pole. Now, in order to reduce your trips to the ice factory, you decide to write a program that helps you visualize how much ice is needed for a particular gift. -----Input:----- Input will consist of a single line with size $n$. -----Output:----- Print the ice wrapped gift box for the given size. -----Constraints----- - $0 \leq n \leq 1000$ -----Sample Input:----- 4 -----Sample Output:----- 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 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 def read_i_l(l=False): m = list(map(int, input().strip().split(" "))) if l: return list(m) else: return m def i(): return int(input().strip()) T = i() L = [] """for current in range(T): line = "" for i in range(current): line+=str((T-i)%10) for i in range(2*(T-current)-1): line+=str((T-current)%10) for i in range(current-1,-1,-1): line+=str((T-i)%10) L.append(line) L += L[-2::-1]""" if T >= 1: L = ["1"] for i in range(2,T+1): nL = [str(i)+(2*i-2)*(" "+str(i))] for l in L: nL.append(str(i)+" "+l+" "+str(i)) nL.append(str(i)+(2*i-2)*(" "+str(i))) L = nL for l in L: print(l) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Everybody is worried about Rakesh as the boy does not have much knowledge about the real world. He can not go from one place to another on his own. It's high time he learned to explore the city. He is going to a relative's house situated on the other side of the city on his own. As this is his first time, he is carrying a GPS tracker of a special kind. The tracker continuously sends information to the family of Rakesh about his movement. The information is sent using the following four letters: U, D, R, and L. Those letters indicate the moves taken by Rakesh. The city can be considered as a grid. Rakesh starts his journey from (0, 0) position of the grid. His relative's house is situated at (Rx, Ry). Rakesh can move in four directions: up, down, right, or left indicated by U, D, R, and L respectively. Any position of the city with x ordinate negative or greater than M is considered as dangerous. Also, any position of the city with y ordinate negative or greater than N is considered as dangerous. You will be given the total sequence of Rakesh's movement. You need to determine if Rakesh ended up being at his relative's house, at a dangerous place, or at a random place in the city. To make things clear, - U indicates a move that increases position along y-axis by 1 - D indicates a move that decreases position along y-axis by 1 - R indicates a move that increases position along x-axis by 1 - L indicates a move that decreases position along x-axis by 1 Note that we are interested in the position of Rakesh at the end of his journey only. He may visit some dangerous place or his relative's house at some intermediate point but that won't affect the answer. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. The description of each test case follows. - The first line of each test case contains two integers M and N. - The second line contains two integers Rx and Ry. - The third line contains the length of Rakesh's move sequence. - The next line contains the move sequence containing letters U, D, R, and L only with no space. -----Output----- For each test case, print "Case i: ", and then the answer, where i is the testcase number, 1-indexed. The answer should be any of the following three strings: - "REACHED" if Rakesh could reach his relative's house - "DANGER" if Rakesh ended up being in a dangerous place - "SOMEWHERE" if Rakesh ended up being in somewhere safe place in the city other than his relative's place Don't print any quotation mark. Check the sample output. -----Constraints----- - 1 ≤ T ≤ 10 - 0 ≤ M, N ≤ 10000 - 0 ≤ Rx ≤ M - 0 ≤ Ry ≤ N - 0 ≤ Sum of the lengths of all sequences ≤ 10000 -----Example----- Input: 2 20 20 4 5 13 LLUUUUURRRRRR 10 10 3 4 7 UDUDDRR Output: Case 1: REACHED Case 2: DANGER 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()) for i in range(t): print("Case {}:".format(i+1), end=" ") m, n = map(int,input().split()) x, y = map(int,input().split()) l = int(input()) a=input() destx = a.count("R")-a.count("L") desty = a.count("U")-a.count("D") #print(destx, desty) if (destx<0 or destx>m) or (desty<0 or desty>n): result = "DANGER" elif destx == x and desty == y: result = "REACHED" else: result = "SOMEWHERE" print(result) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $k$ torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: exchange $1$ stick for $x$ sticks (you lose $1$ stick and gain $x$ sticks). exchange $y$ sticks for $1$ coal (you lose $y$ sticks and gain $1$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order. Your task is to find the minimum number of trades you need to craft at least $k$ torches. The answer always exists under the given constraints. 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 only line of the test case contains three integers $x$, $y$ and $k$ ($2 \le x \le 10^9$; $1 \le y, k \le 10^9$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively. -----Output----- For each test case, print the answer: the minimum number of trades you need to craft at least $k$ torches. The answer always exists under the given constraints. -----Example----- Input 5 2 1 5 42 13 24 12 11 12 1000000000 1000000000 1000000000 2 1000000000 1000000000 Output 14 33 25 2000000003 1000000001999999999 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for haaghfj in range(int(input())): x,y,k = list(map(int,input().split())) print(k + (y * k + k - 1 +x-2) // (x - 1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are N pinholes on the xy-plane. The i-th pinhole is located at (x_i,y_i). We will denote the Manhattan distance between the i-th and j-th pinholes as d(i,j)(=|x_i-x_j|+|y_i-y_j|). You have a peculiar pair of compasses, called Manhattan Compass. This instrument always points at two of the pinholes. The two legs of the compass are indistinguishable, thus we do not distinguish the following two states: the state where the compass points at the p-th and q-th pinholes, and the state where it points at the q-th and p-th pinholes. When the compass points at the p-th and q-th pinholes and d(p,q)=d(p,r), one of the legs can be moved so that the compass will point at the p-th and r-th pinholes. Initially, the compass points at the a-th and b-th pinholes. Find the number of the pairs of pinholes that can be pointed by the compass. -----Constraints----- - 2≦N≦10^5 - 1≦x_i, y_i≦10^9 - 1≦a < b≦N - When i ≠ j, (x_i, y_i) ≠ (x_j, y_j) - x_i and y_i are integers. -----Input----- The input is given from Standard Input in the following format: N a b x_1 y_1 : x_N y_N -----Output----- Print the number of the pairs of pinholes that can be pointed by the compass. -----Sample Input----- 5 1 2 1 1 4 3 6 1 5 5 4 8 -----Sample Output----- 4 Initially, the compass points at the first and second pinholes. Since d(1,2) = d(1,3), the compass can be moved so that it will point at the first and third pinholes. Since d(1,3) = d(3,4), the compass can also point at the third and fourth pinholes. Since d(1,2) = d(2,5), the compass can also point at the second and fifth pinholes. No other pairs of pinholes can be pointed by the compass, thus the answer is 4. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python N, a, b = list(map(int, input().split())); a -= 1; b -= 1 P = [] Q = [] for i in range(N): x, y = list(map(int, input().split())) P.append((x-y, x+y, i)) Q.append((x+y, x-y, i)) d = max(abs(P[a][0] - P[b][0]), abs(P[a][1] - P[b][1])) *parent, = list(range(N)) def root(x): if x == parent[x]: return x y = parent[x] = root(parent[x]) return y def unite(x, y): px = root(x); py = root(y) if px < py: parent[py] = px else: parent[px] = py C = [0]*N D = [0]*N def check(P0, i0, j0): return abs(P0[i0][0] - P0[j0][0]) == abs(P0[i0][1] - P0[j0][1]) def solve(P0): P = P0[:] P.sort() s = t = 0; prev = -1 for i in range(N): x, y, i0 = P[i] while t < N and P[t][0] < x-d or (P[t][0] == x-d and P[t][1] <= y+d): t += 1 while s < N and (P[s][0] < x-d or (P[s][0] == x-d and P[s][1] < y-d)): s += 1 if s < t: j0 = P[s][2] unite(i0, j0) if check(P0, i0, j0): D[i0] += 1 else: C[i0] += 1 if s < t-1: j0 = P[t-1][2] if check(P0, i0, j0): D[i0] += 1 C[i0] += t-s-2 else: C[i0] += t-s-1 for j in range(max(prev, s), t-1): unite(P[j][2], P[j+1][2]) prev = t-1 solve(P) solve(Q) S = T = 0 r = root(a) for i in range(N): if root(i) == r: S += C[i]; T += D[i] print((S + T//2)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef was not happy with the binary number system, so he designed a new machine which is having 6 different states, i.e. in binary there is a total of 2 states as 0 and 1. Now, the chef is confused about how to correlate this machine to get an interaction with Integer numbers, when N(Integer number) is provided to the system, what will be the Nth number that system will return(in Integer form), help the chef to design this system. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, $N$. -----Output:----- For each test case, output in a single line answer given by the system. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 10^5$ -----Sample Input:----- 2 3 5 -----Sample Output:----- 7 37 -----EXPLANATION:----- Initial numbers for system = [1, 6, 7, 36, 37, 42, 43, 216, ….. For 1) 3rd Number for the system will be 7. For 2) 5th Number for the system will be 37. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin, stdout #from math import gcd as g #a,b = map(int, stdin.readline().split()) #l1 = list(map(int, stdin.readline().split())) l = [1,6,7] c = 1 for x in range(3,100001): if x%2==1: a = l[c]*6 l.append(a) else: l.append(a+1) c+=1 n = int(stdin.readline()) for _ in range(n): s = int(stdin.readline()) print(l[s-1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have a sequence $a$ with length $N$ created by removing some elements (possibly zero) from a permutation of numbers $(1, 2, \dots, N)$. When an element is removed, the length of the sequence doesn't change, but there is an empty spot left where the removed element was. You also have an integer $K$. Let's call a permutation $p_1, p_2, \dots, p_N$ good if: - it is possible replace empty spots in $a$ by numbers in such a way that we obtain the permutation $p$ - the number of positions $i$ ($1 < i \le N$) such that $p_i > p_{i-1}$ is equal to $K$ Your task is to find the number of good permutations. -----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 $K$. - The second line contains $N$ space-separated integers $a_1, a_2, \dots, a_N$. Each element of this sequence is either $0$ (indicating an empty spot previously occupied by a removed element) or an integer between $1$ and $N$ inclusive. -----Output----- For each test case, print a single line containing one integer — the number of good permutations. -----Constraints----- - $1 \le T \le 300$ - $0 \le K < N \le 8$ - each integer between $1$ and $N$ inclusive appears in $a$ at most once -----Example Input----- 1 3 1 2 0 0 -----Example Output----- 2 -----Explanation----- Example case 1: The two possible good permutations are $(2,3,1)$ and $(2,1,3)$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from itertools import permutations for _ in range(int(input())): N,K=list(map(int,input().split())) arr=list(map(int,input().split())) arr1=[] arr2=[] for i in range(1,len(arr)+1): arr1.append(i) indexzero=[] for i in range(0,len(arr)): if(arr[i]==0): indexzero.append(i) else: arr2.append(arr[i]) # arr3 = [x for x in arr1 if x not in arr2] arr3= list(set(arr1)-set(arr2)) result=permutations(arr3) perm=[] for i in result: perm.append(i) step=0 count=0 for p in range(0,len(perm)): temp=[] for q in range(0,len(arr)): if(arr[q]==0): temp.append(perm[p][step]) step+=1 else: temp.append(arr[q]) k=0 step=0 for m in range(0,len(temp)-1): if(temp[m]<temp[m+1]): k+=1 if(k==K): count+=1 print(count) ```