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: Alice likes prime numbers. According to Alice, only those strings are nice whose sum of character values at a prime position is prime. She has a string $S$. Now, she has to count the number of nice strings which come before string $S$( including $S$) in the dictionary and are of the same length as $S$. Strings are zero-indexed from left to right. To find the character value she uses the mapping {'a': 0, 'b':1, 'c':2 ……. 'y': 24, 'z':25} . For example, for string $abcde$ Characters at prime positions are $'c'$ and $'d'$. c + d = 2 + 3 = 5. Since, 5 is a prime number, the string is $nice$. Since there could be many nice strings print the answer modulo $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, the string $S$. -----Output:----- For each testcase, output in a single line number of nice strings modulo $10^{9}+7$. -----Constraints----- - $1 \leq T \leq 10$ - $2 \leq |S| \leq 10^2$ String $S$ contains only lowercase letters. -----Sample Input:----- 1 abc -----Sample Output:----- 10 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys from collections import defaultdict from copy import copy MOD = 10**9 + 7 R = lambda t = int: t(input()) RL = lambda t = int: [t(x) for x in input().split()] RLL = lambda n, t = int: [RL(t) for _ in range(n)] # primes up to n def primes(n): P = [] n = int(n) U = [1] * (n+1) p = 2 while p <= n: if U[p]: P += [p] x = p while x <= n: U[x] = 0 x += p p += 1 return P def solve(): S = R(str).strip() X = [ord(c)-ord('a') for c in S] P = primes(10000) L = defaultdict(lambda : 0) s = 0 for i in range(len(S)): p = i in P NL = defaultdict(lambda : 0) for a in range(26): for l in L: NL[l + a * p] += L[l] for a in range(X[i]): NL[s + a * p] += 1 s += X[i] * p L = NL L[s] += 1 r = 0 for p in P: r += L[p] print(r % MOD) T = R() for t in range(1, T + 1): solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p_1, p_2, ..., p_{n} for his birthday. Jeff hates inversions in sequences. An inversion in sequence a_1, a_2, ..., a_{n} is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality a_{i} > a_{j} holds. Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get. -----Input----- The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p_1, p_2, ..., p_{n} (|p_{i}| ≤ 10^5). The numbers are separated by spaces. -----Output----- In a single line print the answer to the problem — the minimum number of inversions Jeff can get. -----Examples----- Input 2 2 1 Output 0 Input 9 -2 0 -1 0 -1 2 1 0 -1 Output 6 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()) inp = input() seq = inp.split(' ') seq = [ abs(int(x)) for x in seq ] Max = max(seq) nxt = [0] * n cnt = [0] * n pos = [n] * (Max+1) for i in range(n-1, -1, -1): nxt[i] = pos[seq[i]] pos[seq[i]] = i for i in range(0, Max+1): j = pos[i] while(j<n): front = sum(cnt[0:j]) back = sum(cnt[j+1:n]) if(front < back): seq[j] = 0 - seq[j] j = nxt[j] j = pos[i] while(j < n): cnt[j] = 1 j = nxt[j] #for i in range(0, n-1): # print(seq[i], sep=' ') #print(seq[n-1]) inv = 0 for i in range(len(seq)): for j in range(i+1, len(seq)): if(seq[i] > seq[j]): inv += 1 print(inv) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a graph with $3 \cdot n$ vertices and $m$ edges. You are to find a matching of $n$ edges, or an independent set of $n$ vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. -----Input----- The first line contains a single integer $T \ge 1$ — the number of graphs you need to process. The description of $T$ graphs follows. The first line of description of a single graph contains two integers $n$ and $m$, where $3 \cdot n$ is the number of vertices, and $m$ is the number of edges in the graph ($1 \leq n \leq 10^{5}$, $0 \leq m \leq 5 \cdot 10^{5}$). Each of the next $m$ lines contains two integers $v_i$ and $u_i$ ($1 \leq v_i, u_i \leq 3 \cdot n$), meaning that there is an edge between vertices $v_i$ and $u_i$. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all $n$ over all graphs in a single test does not exceed $10^{5}$, and the sum of all $m$ over all graphs in a single test does not exceed $5 \cdot 10^{5}$. -----Output----- Print your answer for each of the $T$ graphs. Output your answer for a single graph in the following format. If you found a matching of size $n$, on the first line print "Matching" (without quotes), and on the second line print $n$ integers — the indices of the edges in the matching. The edges are numbered from $1$ to $m$ in the input order. If you found an independent set of size $n$, on the first line print "IndSet" (without quotes), and on the second line print $n$ integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size $n$, and an independent set of size $n$, then you should print exactly one of such matchings or exactly one of such independent sets. -----Example----- Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 -----Note----- The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly $n$. The fourth graph does not have an independent set of size 2, but there is a matching of size 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 input = sys.stdin.readline T = int(input()) for _ in range(T): N, M = list(map(int, input().split())) X = [[] for i in range(3*N)] for i in range(M): x, y = list(map(int, input().split())) x, y = min(x,y), max(x,y) X[x-1].append((y-1, i+1)) MAT = [] IND = [] DONE = [0] * 3*N for i in range(3*N): if DONE[i]: continue for j, ind in X[i]: if DONE[j] == 0: MAT.append(ind) DONE[i] = 1 DONE[j] = 1 break else: IND.append(i+1) if len(MAT) >= N: print("Matching") print(*MAT[:N]) else: print("IndSet") print(*IND[:N]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position). Inserting an element in the same position he was erased from is also considered moving. Can Vasya divide the array after choosing the right element to move and its new position? -----Input----- The first line contains single integer n (1 ≤ n ≤ 100000) — the size of the array. The second line contains n integers a_1, a_2... a_{n} (1 ≤ a_{i} ≤ 10^9) — the elements of the array. -----Output----- Print YES if Vasya can divide the array after moving one element. Otherwise print NO. -----Examples----- Input 3 1 3 2 Output YES Input 5 1 2 3 4 5 Output NO Input 5 2 2 3 4 5 Output YES -----Note----- In the first example Vasya can move the second element to the end of the array. In the second example no move can make the division possible. In the third example Vasya can move the fourth element by one position to the left. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def solve(n,a): tot=0 for i in range(n): tot+=a[i] diffs = [] #alla suffix - prefix diffs[i]=prefix-suffix om delas innan element i diffs.append(-tot) for i in range(n): tot-=2*a[i] diffs.append(-tot) if tot==0: return ("YES") for i in range(n): diffmake=2*a[i] j=binary(diffs,diffmake) if j>i and j!=-1: return ("YES") j=binary(diffs,-diffmake) if i>=j and j!=-1: return ("YES") return ("NO") def binary(a,value): hi=len(a) lo=-1 while (lo+1<hi): mi=(lo+hi)//2 if a[mi]==value: return mi if a[mi]<value: lo=mi else: hi=mi return -1 n=int(input()) a = input().split() for i in range (n): a[i]=int(a[i]) print(solve(n,a)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja. -----Input----- The first line contains integer m (1 ≤ m ≤ 10^5) — the number of stages to build a sequence. Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 ≤ x_{i} ≤ 10^5) — the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 ≤ l_{i} ≤ 10^5, 1 ≤ c_{i} ≤ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence. The next line contains integer n (1 ≤ n ≤ 10^5) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Output----- Print the elements that Sereja is interested in, in the order in which their numbers occur in the input. -----Examples----- Input 6 1 1 1 2 2 2 1 1 3 2 5 2 1 4 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output 1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n=int(input()) a=[] for i in range(n): a.append(list(map(int,input().split()))) m=int(input()) b=list(map(lambda x:int(x)-1,input().split())) c=[] now=0 k=0 ans=[] for i in range(n): t=a[i] last=now if t[0]==1: now+=1 if len(c)<100000: c.append(t[1]) if k<m and b[k]==now-1: ans.append(t[1]) k+=1 else: now+=t[1]*t[2] while t[2]: if len(c)<100000: c.extend(c[:t[1]]) else: break t[2]-=1 while k<m and last<=b[k]<now: ans.append(c[(b[k]-last)%t[1]]) k+=1 for i in range(m): print(ans[i],end=' ') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: - If p_i = 1, do nothing. - If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. -----Notes----- For the definition of isomorphism of trees, see wikipedia. Intuitively, two trees are isomorphic when they are the "same" if we disregard the indices of their vertices. -----Constraints----- - 2 \leq n \leq 10^5 - 1 \leq v_i, w_i \leq n - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} -----Output----- If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print -1. If it exists, print the lexicographically smallest such permutation, with spaces in between. -----Sample Input----- 6 1 2 1 3 1 4 1 5 5 6 -----Sample Output----- 1 2 4 5 3 6 If the permutation (1, 2, 4, 5, 3, 6) is used to generate a tree, it looks as follows: This is isomorphic to the given graph. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys from collections import deque def diameter(n, links): q = deque([(0, -1)]) v = 0 while q: v, p = q.popleft() q.extend((u, v) for u in links[v] if u != p) q = deque([(v, -1)]) w = 0 parents = [-1] * n while q: w, p = q.popleft() parents[w] = p q.extend((u, w) for u in links[w] if u != p) parents_rev = [-1] * n p = w while parents[p] != -1: parents_rev[parents[p]] = p p = parents[p] return v, w, parents, parents_rev def construct(s, links, parents, parents_rev): v = s result = [] while v != -1: pv, rv = parents[v], parents_rev[v] child_count = 0 for u in links[v]: if u == pv or u == rv: continue if len(links[u]) != 1: return False child_count += 1 my_value = len(result) + 1 result.extend(list(range(my_value + 1, my_value + child_count + 1))) result.append(my_value) v = parents[v] return result def solve(n, links): d1, d2, parents, parents_rev = diameter(n, links) result1 = construct(d1, links, parents_rev, parents) if result1 is False: return [-1] result2 = construct(d2, links, parents, parents_rev) return min(result1, result2) n = int(input()) links = [set() for _ in range(n)] INF = 10 ** 9 for line in sys.stdin: v, w = list(map(int, line.split())) v -= 1 w -= 1 links[v].add(w) links[w].add(v) print((*solve(n, links))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: ----- CHEF N TIMINGS ----- One day chef was working with some random numbers. Then he found something interesting. He observed that no 240, 567, 9999 and 122 and called these numbers nice as the digits in numbers are in increasing order. Also he called 434, 452, 900 are not nice as digits are in decreasing order Now you are given a no and chef wants you to find out largest "nice" integer which is smaller than or equal to the given integer. -----Constraints----- 1< t < 1000 1< N < 10^18 -----Input Format----- First line contains no. of test cases t. Then t test cases follow. Each test case contain a integer n. -----Output----- Output a integer for each test case in a new line which is largest nice integer smaller or equal to the given integer. -----Example Text Case----- Input: 1 132 Output: 129 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=input().rstrip() n=[ele for ele in n] l=len(n) m=10**18+8 ini=1 for i in range(l-1,-1,-1): if int(n[i])<=m: if ini==1: m=int(n[i]) else: m=max(m,n[i]) else: m=int(n[i])-1 n[i]=str(m) for j in range(l-1,i,-1): n[j]='9' i=0 while n[i]=='0': i+=1 print("".join(n[i:])) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Alice got many presents these days. So she decided to pack them into boxes and send them to her friends. There are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind. Also, there are $m$ boxes. All of them are for different people, so they are pairwise distinct (consider that the names of $m$ friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box. Alice wants to pack presents with the following rules: She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of $n$ kinds, empty boxes are allowed); For each kind at least one present should be packed into some box. Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo $10^9+7$. See examples and their notes for clarification. -----Input----- The first line contains two integers $n$ and $m$, separated by spaces ($1 \leq n,m \leq 10^9$) — the number of kinds of presents and the number of boxes that Alice has. -----Output----- Print one integer  — the number of ways to pack the presents with Alice's rules, calculated by modulo $10^9+7$ -----Examples----- Input 1 3 Output 7 Input 2 2 Output 9 -----Note----- In the first example, there are seven ways to pack presents: $\{1\}\{\}\{\}$ $\{\}\{1\}\{\}$ $\{\}\{\}\{1\}$ $\{1\}\{1\}\{\}$ $\{\}\{1\}\{1\}$ $\{1\}\{\}\{1\}$ $\{1\}\{1\}\{1\}$ In the second example there are nine ways to pack presents: $\{\}\{1,2\}$ $\{1\}\{2\}$ $\{1\}\{1,2\}$ $\{2\}\{1\}$ $\{2\}\{1,2\}$ $\{1,2\}\{\}$ $\{1,2\}\{1\}$ $\{1,2\}\{2\}$ $\{1,2\}\{1,2\}$ For example, the way $\{2\}\{2\}$ is wrong, because presents of the first kind should be used in the least one box. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Contest: Codeforces Round #593 (Div. 2) (https://codeforces.com/contest/1236) # Problem: B: Alice and the List of Presents (https://codeforces.com/contest/1236/problem/B) def rint(): return int(input()) def rints(): return list(map(int, input().split())) M = 10**9 + 7 n, m = rints() print(pow((pow(2, m, M) + M - 1) % M, n, M)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $[l; r]$. If $r-l+1$ is odd (not divisible by $2$) then assign (set) $a[\frac{l+r}{2}] := i$ (where $i$ is the number of the current action), otherwise (if $r-l+1$ is even) assign (set) $a[\frac{l+r-1}{2}] := i$. Consider the array $a$ of length $5$ (initially $a=[0, 0, 0, 0, 0]$). Then it changes as follows: Firstly, we choose the segment $[1; 5]$ and assign $a[3] := 1$, so $a$ becomes $[0, 0, 1, 0, 0]$; then we choose the segment $[1; 2]$ and assign $a[1] := 2$, so $a$ becomes $[2, 0, 1, 0, 0]$; then we choose the segment $[4; 5]$ and assign $a[4] := 3$, so $a$ becomes $[2, 0, 1, 3, 0]$; then we choose the segment $[2; 2]$ and assign $a[2] := 4$, so $a$ becomes $[2, 4, 1, 3, 0]$; and at last we choose the segment $[5; 5]$ and assign $a[5] := 5$, so $a$ becomes $[2, 4, 1, 3, 5]$. Your task is to find the array $a$ of length $n$ after performing all $n$ actions. Note that the answer exists and unique. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. The only line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $a$. 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 array $a$ of length $n$ after performing $n$ actions described in the problem statement. Note that the answer exists and unique. -----Example----- Input 6 1 2 3 4 5 6 Output 1 1 2 2 1 3 3 1 2 4 2 4 1 3 5 3 4 1 5 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 collections import defaultdict as dd from collections import deque import bisect import heapq def ri(): return int(input()) def rl(): return list(map(int, input().split())) def solve(): n = ri() output = [0] * (n) Q = [(-n, 0 ,n - 1)] for i in range(1, n + 1): prev = heapq.heappop(Q) lo, hi = prev[1], prev[2] mid = (lo + hi) // 2 output[mid] = i if mid > lo: heapq.heappush(Q, (-(mid - 1 - lo), lo, mid - 1)) if hi > mid: heapq.heappush(Q, (-(hi - 1 - mid), mid + 1, hi)) print(*output) mode = 'T' if mode == 'T': t = ri() for i in range(t): solve() else: solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Find the minimum area of a square land on which you can place two identical rectangular $a \times b$ houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, You are given two identical rectangles with side lengths $a$ and $b$ ($1 \le a, b \le 100$) — positive integers (you are given just the sizes, but not their positions). Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding. [Image] The picture shows a square that contains red and green rectangles. -----Input----- The first line contains an integer $t$ ($1 \le t \le 10\,000$) —the number of test cases in the input. Then $t$ test cases follow. Each test case is a line containing two integers $a$, $b$ ($1 \le a, b \le 100$) — side lengths of the rectangles. -----Output----- Print $t$ answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions $a \times b$. -----Example----- Input 8 3 2 4 2 1 1 3 1 4 7 1 3 7 4 100 100 Output 16 16 4 9 64 9 64 40000 -----Note----- Below are the answers for the first two test cases: [Image] [Image] 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): a, b = list(map(int, input().split())) print(max(max(a, b), min(a, b) * 2)**2) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: For a vector $\vec{v} = (x, y)$, define $|v| = \sqrt{x^2 + y^2}$. Allen had a bit too much to drink at the bar, which is at the origin. There are $n$ vectors $\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}$. Allen will make $n$ moves. As Allen's sense of direction is impaired, during the $i$-th move he will either move in the direction $\vec{v_i}$ or $-\vec{v_i}$. In other words, if his position is currently $p = (x, y)$, he will either move to $p + \vec{v_i}$ or $p - \vec{v_i}$. Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position $p$ satisfies $|p| \le 1.5 \cdot 10^6$ so that he can stay safe. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of moves. Each of the following lines contains two space-separated integers $x_i$ and $y_i$, meaning that $\vec{v_i} = (x_i, y_i)$. We have that $|v_i| \le 10^6$ for all $i$. -----Output----- Output a single line containing $n$ integers $c_1, c_2, \cdots, c_n$, each of which is either $1$ or $-1$. Your solution is correct if the value of $p = \sum_{i = 1}^n c_i \vec{v_i}$, satisfies $|p| \le 1.5 \cdot 10^6$. It can be shown that a solution always exists under the given constraints. -----Examples----- Input 3 999999 0 0 999999 999999 0 Output 1 1 -1 Input 1 -824590 246031 Output 1 Input 8 -67761 603277 640586 -396671 46147 -122580 569609 -2112 400 914208 131792 309779 -850150 -486293 5272 721899 Output 1 1 1 1 1 1 1 -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import random n = int(input()) v = [] a = [] for i in range(n): a.append(i) for _ in range(0, n): x, y = list(map(int, input().split())) v.append([x, y, x*x+y*y]) while 1>0: x = 0 y = 0 ans = [0]*n random.shuffle(a) for i in range(n): if (x+v[a[i]][0])**2+(y+v[a[i]][1])**2 <= (x-v[a[i]][0])**2+(y-v[a[i]][1])**2: x += v[a[i]][0] y += v[a[i]][1] ans[a[i]] = 1 else: x -= v[a[i]][0] y -= v[a[i]][1] ans[a[i]] = -1 if x*x+y*y <= 1500000**2: print(*ans) break ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's call an array $a_1, a_2, \dots, a_m$ of nonnegative integer numbers good if $a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$, where $\oplus$ denotes the bitwise XOR operation. For example, array $[1, 2, 3, 6]$ is good, as $1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplus 6)$. At the same time, array $[1, 2, 1, 3]$ isn't good, as $1 + 2 + 1 + 3 = 7 \neq 2\cdot 1 = 2\cdot(1\oplus 2 \oplus 1 \oplus 3)$. You are given an array of length $n$: $a_1, a_2, \dots, a_n$. Append at most $3$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10\,000$). The description of the test cases follows. The first line of each test case contains a single integer $n$ $(1\le n \le 10^5)$ — the size of the array. The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($0\le a_i \le 10^9$) — the elements of the array. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case, output two lines. In the first line, output a single integer $s$ ($0\le s\le 3$) — the number of elements you want to append. In the second line, output $s$ integers $b_1, \dots, b_s$ ($0\le b_i \le 10^{18}$) — the elements you want to append to the array. If there are different solutions, you are allowed to output any of them. -----Example----- Input 3 4 1 2 3 6 1 8 2 1 1 Output 0 2 4 4 3 2 6 2 -----Note----- In the first test case of the example, the sum of all numbers is $12$, and their $\oplus$ is $6$, so the condition is already satisfied. In the second test case of the example, after adding $4, 4$, the array becomes $[8, 4, 4]$. The sum of numbers in it is $16$, $\oplus$ of numbers in it is $8$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for nt in range(int(input())): n=int(input()) l=list(map(int,input().split())) s=sum(l) e=l[0] for i in range(1,n): e=e^l[i] if s==2*e: print(0) print () else: print(2) print(e,s+e) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: We all know Gru loves Agnes very much. One day Agnes asked Gru to answer some of her queries. She lined up $N$ minions in a straight line from $1$ to $N$. You are given an array $A$ which contains the height of minions. Agnes will ask him several queries. In each query, Gru has to tell whether the bitwise AND of $A[L \ldots R]$ is EVEN or ODD. Since Gru is busy planning the biggest heist on Earth, he asks for your help. -----Input:----- - First line of the input contains an integer $T$ denoting the number of test cases. For each test case:- - First line contains an integer $N$ denoting the number of elements. - Second line contains $N$ spaced integer representing array elements. - Third line contains $Q$ representing number of query. - Next $Q$ lines contains two integer $L$ and $R$ as defined above. -----Output:----- For each query, output "EVEN" or "ODD" without quotes. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 10^5$ - $1 \leq A_i \leq 10^5$ - $1 \leq Q \leq 10^5$ -----Sample Input:----- 1 5 1 3 2 4 5 3 1 2 1 5 3 4 -----Sample Output:----- ODD EVEN EVEN -----Explanation----- - For the first query, the bitwise AND of 1 and 3 is 1, which is Odd. Hence the first output is ODD. - For the third query, the bitwise AND of 2 and 4 is 0, which is Even. Hence the third output is EVEN. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n=int(input()) a=[int(x) for x in input().split()] sum=0 for i in range(n): if a[i]%2==0: sum+=1 a[i]=sum q=int(input()) while q: l,r=map(int,input().split()) if l!=1: c=a[r-1]-a[l-2] else: c=a[r-1] if c==0: print("ODD") else: print("EVEN") q-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well. We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the greatest common divisor of a and b, and LCM(a, b) denotes the least common multiple of a and b. You are given two integers x and y. You are to find the number of good pairs of integers (a, b) such that l ≤ a, b ≤ r. Note that pairs (a, b) and (b, a) are considered different if a ≠ b. -----Input----- The only line contains four integers l, r, x, y (1 ≤ l ≤ r ≤ 10^9, 1 ≤ x ≤ y ≤ 10^9). -----Output----- In the only line print the only integer — the answer for the problem. -----Examples----- Input 1 2 1 2 Output 2 Input 1 12 1 12 Output 4 Input 50 100 3 30 Output 0 -----Note----- In the first example there are two suitable good pairs of integers (a, b): (1, 2) and (2, 1). In the second example there are four suitable good pairs of integers (a, b): (1, 12), (12, 1), (3, 4) and (4, 3). In the third example there are good pairs of integers, for example, (3, 30), but none of them fits the condition l ≤ a, b ≤ r. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import sqrt from fractions import gcd l, r, x, y = list(map(int, input().split())) if y % x != 0: print(0) return lo = (l + x - 1) // x hi = r // x p = y // x s = 0 k1 = 1 while k1 * k1 <= p: k2 = p // k1 if lo <= k1 <= hi and lo <= k2 <= hi and gcd(k1, k2) == 1 and k1 * k2 == p: s += 1 + (k1 != k2) k1 += 1 print(s) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has the string s of length n consisted of digits 4 and 7. The string s is called balanced if there exits such integer x (1 ≤ x ≤ n) that the number of digits 4 in substring s[1; x) is equal to the number of digits 7 in substring s(x; n], where s[1; x) is the substring from the 1st digit to (x-1)th digit of s, and s(x; n] is the substring from the (x+1)th digit to nth digit of s. For example, s = 747474 is a balanced string, because s[1; 4) = 747 has one 4 and s(4; 6] = 74 has one 7. Note that x can be 1 or n and s[1; 1) and s(n; n] denote an empty string. In one turn Chef can choose any pair of consecutive digits and swap them. Find for Chef the total number of different balanced string that can be obtained from string s using any (even 0) number of turns. Print the result modulo 1000000007. -----Input----- The first line of the input contains one integer T, the number of test cases. Then T lines follow, each of which contains string s for the corresponding test. -----Output----- T lines, each of which contains single integer - the answer for the corresponding test modulo 109+7. -----Constraints----- 1 ≤ T ≤ 10 1 ≤ n ≤ 5000 -----Example----- Input: 2 47 4477 Output: 1 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import factorial def Ncr(n,r): if r<0:return 0 return factorial(n)/(factorial(n-r)*factorial(r)) def solve(m,n): modulo=10**9+7 if m==n: return (Ncr(2*n-1,n-1)+Ncr(2*n-2,n-2))%modulo elif m>n: return (Ncr(m+n,n)-Ncr(m+n-2,n-1))%modulo else: return (Ncr(m+n,m)-Ncr(m+n-2,m-1))%modulo t=int(input()) for i in range(t): inp=list(map(int,input())) m=inp.count(4) n=inp.count(7) print(solve(m,n)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vietnamese and Bengali as well. An $N$-bonacci sequence is an infinite sequence $F_1, F_2, \ldots$ such that for each integer $i > N$, $F_i$ is calculated as $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N})$, where $f$ is some function. A XOR $N$-bonacci sequence is an $N$-bonacci sequence for which $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N}) = F_{i-1} \oplus F_{i−2} \oplus \ldots \oplus F_{i−N}$, where $\oplus$ denotes the bitwise XOR operation. Recently, Chef has found an interesting sequence $S_1, S_2, \ldots$, which is obtained from prefix XORs of a XOR $N$-bonacci sequence $F_1, F_2, \ldots$. Formally, for each positive integer $i$, $S_i = F_1 \oplus F_2 \oplus \ldots \oplus F_i$. You are given the first $N$ elements of the sequence $F$, which uniquely determine the entire sequence $S$. You should answer $Q$ queries. In each query, you are given an index $k$ and you should calculate $S_k$. It is guaranteed that in each query, $S_k$ does not exceed $10^{50}$. -----Input----- - The first line of the input contains two space-separated integers $N$ and $Q$. - The second line contains $N$ space-separated integers $F_1, F_2, \ldots, F_N$. - The following $Q$ lines describe queries. Each of these lines contains a single integer $k$. -----Output----- For each query, print a single line containing one integer $S_k$. -----Constraints----- - $1 \le N, Q \le 10^5$ - $0 \le F_i \le 10^9$ for each $i$ such that $1 \le i \le N$ - $1 \le k \le 10^9$ -----Example Input----- 3 4 0 1 2 7 2 5 1000000000 -----Example Output----- 3 1 0 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here n,q=map(int,input().split()) ls=[int(i) for i in input().split()] cur=0 s=[0] for i in ls: cur=cur^i s.append(cur) for i in range(q): k=int(input()) print(s[k%(n+1)]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A reversed arabic no is one whose digits have been written in the reversed order. However in this any trailing zeroes are omitted. The task at hand here is a simple one. You need to add two numbers which have been written in reversed arabic and return the output back in reversed arabic form, assuming no zeroes were lost while reversing. -----Input----- The input consists of N cases. The first line of the input contains only a positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers seperated by space. These are the reversednumbers you are to add. -----Output----- For each case, print exactly one line containing only one integer- the reversed sum of two reversed numbers. Omit any leading zeroes in the output. -----Example----- Input: 1 24 1 Output: 34 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) for index in range(0, n): a, b = list(map(str, input().split())) a = int(a[::-1]) b = int(b[::-1]) a = str(a + b) a = int(a[::-1]) print(a) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given a regular bracket sequence $s$ and an integer number $k$. Your task is to find a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$. It is guaranteed that such sequence always exists. -----Input----- The first line contains two integers $n$ and $k$ ($2 \le k \le n \le 2 \cdot 10^5$, both $n$ and $k$ are even) — the length of $s$ and the length of the sequence you are asked to find. The second line is a string $s$ — regular bracket sequence of length $n$. -----Output----- Print a single string — a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$. It is guaranteed that such sequence always exists. -----Examples----- Input 6 4 ()(()) Output ()() Input 8 8 (()(())) Output (()(())) 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()) a = [0] * n b = ['0'] * n c = [] s = input() for i in range(n): if k != 0: if s[i] == '(': c.append(i) else: d = c.pop() a[i] = 1 a[d] = 1 k -= 2 for i in range(n): if a[i] == 1: print(s[i], end = '') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Forgotten languages (also known as extinct languages) are languages that are no longer in use. Such languages were, probably, widely used before and no one could have ever imagined that they will become extinct at some point. Unfortunately, that is what happened to them. On the happy side of things, a language may be dead, but some of its words may continue to be used in other languages. Using something called as the Internet, you have acquired a dictionary of N words of a forgotten language. Meanwhile, you also know K phrases used in modern languages. For each of the words of the forgotten language, your task is to determine whether the word is still in use in any of these K modern phrases or not. -----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 a test case description contains two space separated positive integers N and K. The second line of the description contains N strings denoting a dictionary of the forgotten language. Each of the next K lines of the description starts with one positive integer L denoting the number of words in the corresponding phrase in modern languages. The integer is followed by L strings (not necessarily distinct) denoting the phrase. -----Output----- For each test case, output a single line containing N tokens (space-separated): if the ith word of the dictionary exists in at least one phrase in modern languages, then you should output YES as the ith token, otherwise NO. -----Constraints----- - 1 ≤ T ≤ 20 - 1 ≤ N ≤ 100 - 1 ≤ K, L ≤ 50 - 1 ≤ length of any string in the input ≤ 5 -----Example----- Input: 2 3 2 piygu ezyfo rzotm 1 piygu 6 tefwz tefwz piygu ezyfo tefwz piygu 4 1 kssdy tjzhy ljzym kegqz 4 kegqz kegqz kegqz vxvyj Output: YES YES NO NO NO NO YES The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python test_case = int(input()) for w in range(test_case): n, k = map(int,input().split()) l = list(map(str,input().split())) ans = [] for q in range(k): l2 = list(map(str,input().split())) ans.extend(l2[1:]) for i in l: if i in ans: print('YES',end=' ') else: print('NO',end=' ') print()# cook your dish here ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be w_{i}, then 0 < w_1 ≤ w_2 ≤ ... ≤ w_{k} holds. Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights w_{i} (not necessary integers), such that the fish caught by Alice has a strictly larger total weight? -----Input----- The first line contains three integers n, m, k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 10^9) — the number of fish caught by Alice and Bob respectively, and the number of fish species. The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob. Note that one may have caught more than one fish for a same species. -----Output----- Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise. -----Examples----- Input 3 3 3 2 2 2 1 1 3 Output YES Input 4 7 9 5 2 7 3 3 5 2 7 3 8 7 Output NO -----Note----- In the first sample, if w_1 = 1, w_2 = 2, w_3 = 2.5, then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5. In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python rd = lambda: list(map(int, input().split())) rd() a = sorted(rd(), reverse=True) b = sorted(rd(), reverse=True) if len(a) > len(b): print("YES"); return for i in range(len(a)): if a[i] > b[i]: print("YES"); return print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it. Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant. The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially. Each customer is characterized by three values: $t_i$ — the time (in minutes) when the $i$-th customer visits the restaurant, $l_i$ — the lower bound of their preferred temperature range, and $h_i$ — the upper bound of their preferred temperature range. A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $i$-th customer is satisfied if and only if the temperature is between $l_i$ and $h_i$ (inclusive) in the $t_i$-th minute. Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers. -----Input----- Each test contains one or more test cases. The first line contains the number of test cases $q$ ($1 \le q \le 500$). Description of the test cases follows. The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 100$, $-10^9 \le m \le 10^9$), where $n$ is the number of reserved customers and $m$ is the initial temperature of the restaurant. Next, $n$ lines follow. The $i$-th line of them contains three integers $t_i$, $l_i$, and $h_i$ ($1 \le t_i \le 10^9$, $-10^9 \le l_i \le h_i \le 10^9$), where $t_i$ is the time when the $i$-th customer visits, $l_i$ is the lower bound of their preferred temperature range, and $h_i$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $0$. -----Output----- For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower). -----Example----- Input 4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 Output YES NO YES NO -----Note----- In the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $0$-th minute, change the state to heating (the temperature is 0). At $2$-nd minute, change the state to off (the temperature is 2). At $5$-th minute, change the state to heating (the temperature is 2, the $1$-st customer is satisfied). At $6$-th minute, change the state to off (the temperature is 3). At $7$-th minute, change the state to cooling (the temperature is 3, the $2$-nd customer is satisfied). At $10$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $0$-th minute and leave it be. Then all customers will be satisfied. Note that the $1$-st customer's visit time equals the $2$-nd customer's visit time. In the second and the fourth case, Gildong has to make at least one customer unsatisfied. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python q = int(input()) for _ in range(q): n, m = list(map(int, input().split())) info = [list(map(int, input().split())) for i in range(n)] info = sorted(info) now =(m, m) time = 0 flag = True for i in range(n): t, l, h = info[i] l_now = now[0] - (t - time) h_now = now[1] + (t - time) time = t if h < l_now or h_now < l: flag = False else: l_now = max(l_now, l) h_now = min(h_now, h) now = (l_now, h_now) if flag: print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $u$ and go by a simple path to city $v$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex. A filling station is located in every city. Because of strange law, Nut can buy only $w_i$ liters of gasoline in the $i$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last. He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 3 \cdot 10^5$) — the number of cities. The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \leq w_{i} \leq 10^9$) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next $n - 1$ lines describes road and contains three integers $u$, $v$, $c$ ($1 \leq u, v \leq n$, $1 \leq c \leq 10^9$, $u \ne v$), where $u$ and $v$ — cities that are connected by this road and $c$ — its length. It is guaranteed that graph of road connectivity is a tree. -----Output----- Print one number — the maximum amount of gasoline that he can have at the end of the path. -----Examples----- Input 3 1 3 3 1 2 2 1 3 2 Output 3 Input 5 6 3 2 5 0 1 2 10 2 3 3 2 4 1 1 5 1 Output 7 -----Note----- The optimal way in the first example is $2 \to 1 \to 3$. [Image] The optimal way in the second example is $2 \to 4$. [Image] 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 from collections import Counter def getpar(Edge, p): N = len(Edge) par = [0]*N par[0] = -1 par[p] -1 stack = [p] visited = set([p]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn stack.append(vf) return par def topological_sort_tree(E, r): Q = [r] L = [] visited = set([r]) while Q: vn = Q.pop() L.append(vn) for vf in E[vn]: if vf not in visited: visited.add(vf) Q.append(vf) return L def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res N = int(readline()) We = list(map(int, readline().split())) Edge = [[] for _ in range(N)] Cost = Counter() geta = N+1 for _ in range(N-1): a, b, c = list(map(int, readline().split())) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) Cost[b*geta+a] = c Cost[a*geta+b] = c P = getpar(Edge, 0) L = topological_sort_tree(Edge, 0) C = getcld(P) dp = [0]*N candi = [[0, 0] for _ in range(N)] ans = 0 for l in L[::-1][:-1]: dp[l] += We[l] p = P[l] k = dp[l] - Cost[l*geta + p] if k > 0: dp[p] = max(dp[p], k) candi[p].append(k) res = max(candi[l]) candi[l].remove(res) ans = max(ans, We[l] + res + max(candi[l])) res = max(candi[0]) candi[0].remove(res) ans = max(ans, We[0] + res + max(candi[0])) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a set $S$ and $Q$ queries. Initially, $S$ is empty. In each query: - You are given a positive integer $X$. - You should insert $X$ into $S$. - For each $y \in S$ before this query such that $y \neq X$, you should also insert $y \oplus X$ into $S$ ($\oplus$ denotes the XOR operation). - Then, you should find two values $E$ and $O$: the number of elements of $S$ with an even number of $1$-s and with an odd number of $1$-s in the binary representation, respectively. Note that a set cannot have duplicate elements, so if you try to insert into $S$ an element that is already present in $S$, then nothing happens. -----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 $Q$. - Each of the next $Q$ lines contains a single integer $X$ describing a query. -----Output----- For each query, print a single line containing two space-separated integers $E$ and $O$. -----Constraints----- - $1 \le T \le 5$ - $1 \le Q, X \le 10^5$ -----Subtasks----- Subtask #1 (30 points): - $1 \le Q \le 1,000$ - $1 \le X \le 128$ Subtask #2 (70 points): original constraints -----Example Input----- 1 3 4 2 7 -----Example Output----- 0 1 1 2 3 4 -----Explanation----- Example case 1: - Initially, the set is empty: $S = \{\}$. - After the first query, $S = \{4\}$, so there is only one element with an odd number of $1$-s in the binary representation ("100"). - After the second query, $S = \{4,2,6\}$, there is one element with an even number of $1$-s in the binary representation ($6$ is "110") and the other two elements have an odd number of $1$-s. - After the third query, $S = \{4,2,6,7,3,5,1\}$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # fast io import sys def fop(s): sys.stdout.write(str(s)+'\n') def fip(): return sys.stdin.readline() fintinp = lambda : int(fip()) def flistinp(func= int): return list(map(func,fip().split())) def fnsepline(n,func=str): return [func(fip()) for _ in range(n)] #-------------------code------------------------ def even(x): x = bin(x).count('1') return x%2==0 for _ in range(fintinp()): q =fintinp() o = e =0 nums = set() for qn in range(q): qn = fintinp() if qn not in nums: if even(qn): e+=1 else: o+=1 for n in set(nums): x = n^qn if x not in nums: if even(x): e+=1 else: o+=1 nums.add(x) nums.add(qn) print(e,o) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point. Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers x, y and z to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options: a_1 = x^{y}^{z}; a_2 = x^{z}^{y}; a_3 = (x^{y})^{z}; a_4 = (x^{z})^{y}; a_5 = y^{x}^{z}; a_6 = y^{z}^{x}; a_7 = (y^{x})^{z}; a_8 = (y^{z})^{x}; a_9 = z^{x}^{y}; a_10 = z^{y}^{x}; a_11 = (z^{x})^{y}; a_12 = (z^{y})^{x}. Let m be the maximum of all the a_{i}, and c be the smallest index (from 1 to 12) such that a_{c} = m. Rat's goal is to find that c, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that a_{c}. -----Input----- The only line of the input contains three space-separated real numbers x, y and z (0.1 ≤ x, y, z ≤ 200.0). Each of x, y and z is given with exactly one digit after the decimal point. -----Output----- Find the maximum value of expression among x^{y}^{z}, x^{z}^{y}, (x^{y})^{z}, (x^{z})^{y}, y^{x}^{z}, y^{z}^{x}, (y^{x})^{z}, (y^{z})^{x}, z^{x}^{y}, z^{y}^{x}, (z^{x})^{y}, (z^{y})^{x} and print the corresponding expression. If there are many maximums, print the one that comes first in the list. x^{y}^{z} should be outputted as x^y^z (without brackets), and (x^{y})^{z} should be outputted as (x^y)^z (quotes for clarity). -----Examples----- Input 1.1 3.4 2.5 Output z^y^x Input 2.0 2.0 2.0 Output x^y^z Input 1.9 1.8 1.7 Output (x^y)^z The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import log from decimal import Decimal s = ['x^y^z', 'x^z^y', '(x^y)^z', 'y^x^z', 'y^z^x', '(y^x)^z', 'z^x^y', 'z^y^x', '(z^x)^y'] x, y, z = list(map(Decimal, input().split())) f = [] f += [(Decimal(log(x)) * (y ** z), 0)] f += [(Decimal(log(x)) * (z ** y), -1)] f += [(Decimal(log(x)) * (y * z), -2)] f += [(Decimal(log(y)) * (x ** z), -3)] f += [(Decimal(log(y)) * (z ** x), -4)] f += [(Decimal(log(y)) * (x * z), -5)] f += [(Decimal(log(z)) * (x ** y), -6)] f += [(Decimal(log(z)) * (y ** x), -7)] f += [(Decimal(log(z)) * (x * y), -8)] f.sort() print(s[-f[-1][1]]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This year $p$ footballers and $q$ cricketers have been invited to participate in IPL (Indian Programming League) as guests. You have to accommodate them in $r$ rooms such that- - No room may remain empty. - A room may contain either only footballers or only cricketers, not both. - No cricketers are allowed to stay alone in a room. Find the number of ways to place the players. Note though, that all the rooms are identical. But each of the cricketers and footballers are unique. Since the number of ways can be very large, print the answer modulo $998,244,353$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains three space-separated integers $p$, $q$ and $r$ denoting the number of footballers, cricketers and rooms. -----Output----- For each test case, output the number of ways to place the players modulo $998,244,353$. -----Constraints----- - $1 \le T \le 100$ - $1 \le p, q, r \le 100$ -----Example Input----- 4 2 1 4 2 4 4 2 5 4 2 8 4 -----Example Output----- 0 3 10 609 -----Explanation----- Example case 2: Three possible ways are: - {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 2}, {Cricketer 3, Cricketer 4} - {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 3}, {Cricketer 2, Cricketer 4} - {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 4}, {Cricketer 2, Cricketer 3} Please note that the rooms are identical. 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 = 998244353 fball = [ [0]*101 for _ in range(101) ] cric = [ [0]*101 for _ in range(101) ] def calSNum(n, r): if n == r or r == 1: fball[r][n] = 1 return if n > 0 and r > 0 and n > r: fball[r][n] = (fball[r-1][n-1]%MOD + (r*fball[r][n-1])%MOD )%MOD return fball[r][n] = 0 def calASNum(n, r): if n == 0 and r == 0 : cric[r][n] = 0 return if n >= 2 and r == 1: cric[r][n] = 1 return if r > 0 and n > 0 and n >= 2*r: cric[r][n] = ((r*cric[r][n-1])%MOD + ((n-1)*cric[r-1][n-2])%MOD )%MOD return cric[r][n] = 0 def preCompute(): for r in range(1,101): for n in range(1, 101): calSNum(n, r) calASNum(n, r) def main(): preCompute() for _ in range(int(input())): f, c, r = list(map(int, input().split())) ans = 0 if f + (c//2) >= r: minv = min(f, r) for i in range(1, minv+1): if r-i <= c//2: ans = (ans + (fball[i][f] * cric[r-i][c])%MOD )%MOD print(ans) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are a lot of problems related to the shortest paths. Nevertheless, there are not much problems, related to the shortest paths in average. Consider a directed graph G, consisting of N nodes and M edges. Consider a walk from the node A to the node B in this graph. The average length of this walk will be total sum of weight of its' edges divided by number of edges. Every edge counts as many times as it appears in this path. Now, your problem is quite simple. For the given graph and two given nodes, find out the shortest average length of the walk between these nodes. Please note, that the length of the walk need not to be finite, but average walk length will be. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a pair of space-separated integers N and M denoting the number of nodes and the number of edges in the graph. Each of the following M lines contains a triple of space-separated integers Xi Yi Zi, denoting the arc, connecting the node Xi to the node Yi (but not vice-versa!) having the weight of Zi. The next line contains a pair of space separated integers A and B, denoting the first and the last node of the path. -----Output----- For each test case, output a single line containing the length of the shortest path in average. If there is no path at all, output just -1 on the corresponding line of the output. -----Constraints----- - 1 ≤ N ≤ 500 - 1 ≤ M ≤ 1000 - A is not equal to B - 1 ≤ A, B, Xi, Yi ≤ N - 1 ≤ Zi ≤ 100 - There are no self-loops and multiple edges in the graph. - 1 ≤ sum of N over all test cases ≤ 10000 - 1 ≤ sum of M over all test cases ≤ 20000 -----Subtasks----- - Subtask #1 (45 points): 1 ≤ N ≤ 10, 1 ≤ M ≤ 20; Your answer will be considered correct in case it has an absolute or relative error of no more than 10-2. - Subtask #2 (55 points): no additional constraints; Your answer will be considered correct in case it has an absolute or relative error of no more than 10-6. -----Example----- Input:2 3 3 1 2 1 2 3 2 3 2 3 1 3 3 3 1 2 10 2 3 1 3 2 1 1 3 Output:1.5 1.0 -----Explanation----- Example case 1. The walk 1 -> 2 and 2 -> 3 has average length of 3/2 = 1.5. Any other walks in the graph will have more or equal average length than this. 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 import copy #def dfs(l,r,dct): def dfs(l,r,dct): visit=[0 for i in range(n+1)] arr=[l] while(arr): node=arr.pop() if node==r:return True visit[node]=1 for lnk in dct[node]: if not visit[lnk]: arr.append(lnk) return False def ok(mid,cst): for i,j in edges: cst[i][j]-=mid d=[10**9]*(n+1) d[l]=0 for _ in range(n-1): for i,j in edges: d[j]=min(d[j],d[i]+cst[i][j]) if d[r]<=0:return 1 for i,j in edges: if d[j]>d[i]+cst[i][j] and dfs(l,i,dct) and dfs(j,r,dct): return 1 return 0 for _ in range(int(input())): n,m=map(int,input().split()) dct=defaultdict(list) cost=[[1000 for i in range(n+1)] for j in range(n+1)] edges=[] for i in range(m): a,b,w=map(int,input().split()) edges.append([a,b]) dct[a].append(b) cost[a][b]=min(cost[a][b],w) l,r=map(int,input().split()) if not dfs(l,r,dct): print(-1) continue #print(cost) lo=1 hi=101 for i in range(100): cst=copy.deepcopy(cost) mid=(lo+hi)/2 if ok(mid,cst):hi=mid-1 else:lo=mid+1 print("%.7f"%mid) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sandy is a professor at a very reputed institute. The institute mandates that all the lectures be communicated in English. As Sandy is not very good at English(or anything actually) the presentations he displays in class have a lot of spelling mistakes in them. As you have a dictionary on you containing $N$ words in it, the responsibility of correctly deducing the misspelt word falls upon your shoulders. Sandy's presentation contains in them, $Q$ words which you $think$ are wrongly spelt. A word is misspelt if a $single$ letter in it is missing or is different from the corresponding correctly spelled word in your dictionary. For each of the misspelt word in the presentation find out the corresponding correct word from your dictionary. Note : - For each misspelt word in Sandy's presentation, there exists one and only one correctly spelt word in your dictionary that corresponds to it. - Out of the $Q$ misspelt words given to you, there might be some which are correctly spelt i.e., that word completely matches a word in your dictionary. (Give Sandy some credit, he's a teacher after all). For such words print the word corresponding to it in your dictionary. - The maximum length of each string can be $L$. -----Input:----- - First line contains a single integer $T$ denoting the number of testcases. Then the testcases follow. - The first line of each test case contains two space-separated integers $N, Q$ corresponding to the number of words in your dictionary and the number of misspelt word in Sandy's dictionary respectively. - $N$ lines follow each containing a single string $S$ denoting a word in your dictionary. - $Q$ lines follow each containing a single string $M$ denoting a misspelt word in Sandy's presentation. -----Output:----- In each testcase, for each of the $Q$ misspelt words, print a single word $S$ corresponding to the correctly spelt word in your dictionary. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N \leq 200$ - $1 \leq Q \leq 200$ - $1 \leq L \leq 100$ - None of the words contain any spaces in them. - Each letter in every word is in lower case. -----Subtasks----- - Subtask 1 : 10 points - $1 \leq N \leq 50$ - $1 \leq Q \leq 10$ - Subtask 2 : 90 points - Original Constraints -----Sample Input:----- 1 5 2 szhbdvrngk qzhxibnuec jfsalpwfkospl levjehdkjy wdfhzgatuh szhbdvcngk qzhxbnuec -----Sample Output:----- szhbdvrngk qzhxibnuec -----EXPLANATION:----- - In the first misspelt word $szhbdvcngk$, a single letter $c$ is different from the original word $szhbdvrngk$. - The second misspelt word $qzhxbnuec$ is missing the letter $i$ that was in the original word $qzhxibnuec$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from difflib import get_close_matches import sys, os def closeMatches(patterns, word): return get_close_matches(word, patterns, 1, 0.9)[0] def get_string(): return sys.stdin.readline().strip() def get_ints(): return map(int, sys.stdin.readline().strip().split()) ans = [] test = int(input()) for i in range(test): n,q = get_ints() #ans = [] n = int(n) q = int(q) patterns=[] for j in range(n): s = get_string() patterns.append(s) for j in range(q): word = get_string() ans.append(closeMatches(patterns, word)) for j in ans: sys.stdout.write(j+"\n") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given a string s. Can you make it a palindrome by deleting exactly one character? Note that size of the string after deletion would be one less than it was before. -----Input----- First line of the input contains a single integer T denoting number of test cases. For each test case, you are given a single line containing string s. -----Output----- For each test case, print YES or NO depending on the answer of the problem. -----Constraints----- Subtask 1, 35 points - 1 ≤ T ≤ 100 - 2 ≤ size of string s ≤ 1000 - String s contains lowercase English alphabets (ie. from 'a' to 'z'). Subtask 2, 65 points - 2 ≤ size of string s ≤ 10^5 - Sum of size of string s over all the input test cases won't exceed 10^6 - String s contains lowercase English alphabets (ie. from 'a' to 'z'). -----Example----- Input: 4 aaa abc abdbca abba Output: YES NO YES YES -----Explanation----- Example case 1. Delete any one 'a', resulting string is "aa" which is a palindrome. Example case 2. It is not possible to delete exactly one character and having a palindrome. Example case 3. Delete 'c', resulting string is "abdba" which is a palindrome. Example case 4. Delete 'b', resulting string is "aba" which is a palindrome. 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())): s=str(input()) n=len(s) k=s[::-1] a,b="","" for i in range(n): if s[i]!=k[i]: a+=s[i+1:] b+=k[i+1:] break else: a+=s[i] b+=k[i] #print(a,b) if a==a[::-1] or b==b[::-1]: print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The EEE classes are so boring that the students play games rather than paying attention during the lectures. Harsha and Dubey are playing one such game. The game involves counting the number of anagramic pairs of a given string (you can read about anagrams from here). Right now Harsha is winning. Write a program to help Dubey count this number quickly and win the game! -----Input----- The first line has an integer T which is the number of strings. Next T lines each contain a strings. Each string consists of lowercase english alphabets only. -----Output----- For each string, print the answer in a newline. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ length of each string ≤ 100 -----Example----- Input: 3 rama abba abcd Output: 2 4 0 -----Explanation----- rama has the following substrings: - r - ra - ram - rama - a - am - ama - m - ma - a Out of these, {5,10} and {6,9} are anagramic pairs. Hence the answer is 2. Similarly for other strings as well. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def sort_str(s): o = [] for c in s: o.append(c) o.sort() return "".join(o) def find_ana(s): if len(s) <= 1: return 0 h = {} c = 0 for i in range(len(s)): for j in range(i+1, len(s)+1): t = sort_str(s[i:j]) if t in h: c += h[t] h[t] += 1 else: h[t] = 1 return c t = int(input()) for _ in range(t): print(find_ana(input())) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today is Chef's birthday. His mom decided to surprise him with a truly fantastic gift: his favourite binary string B. But, unfortunately, all the stocks of binary string B have been sold out, and only a binary string A (A ≠ B) is available in the market. She purchases the string A and tries to convert it to string B by applying any of following three operations zero or more times. AND Operation: She will choose a pair of indices i and j such that i != j and perform following sequence of operations. - result = Ai & Aj - Ai = result & Ai - Aj = result & Aj OR Operation: She will choose a pair of indices i and j such that i != j and perform following sequence of operations. - result = Ai | Aj - Ai = result | Ai - Aj = result | Aj XOR Operation: She will choose a pair of indices i and j such that i != j and perform following sequence of operations. - result = Ai ^ Aj - Ai = result ^ Ai - Aj = result ^ Aj Chef's mom is eagerly waiting to surprise him with his favourite gift and therefore, she wants to convert string A to string B as fast as possible. Can you please help her by telling her the minimum number of operations she will require? If it is impossible to do so, then let Chef's mom know about it. -----Input----- First line of input contains a single integer T denoting the number of test cases. T test cases follow. First line of each test case, will contain binary string A. Second line of each test case, will contain binary string B. -----Output----- For each test case, Print "Lucky Chef" (without quotes) in first line and minimum number of operations required to convert string A to sting B in second line if conversion is possible. Print "Unlucky Chef" (without quotes) in a new line otherwise. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ |A| ≤ 106 - 1 ≤ |B| ≤ 106 - A != B - |A| = |B| - sum of |A| over all test cases does not exceed 106 - sum of |B| over all test cases does not exceed 106 -----Subtasks----- - Subtask #1 (40 points) : Sum of |A| & |B| over all test cases does not exceed 103 - Subtask #2 (60 points) : Sum of |A| & |B| over all test cases does not exceed 106 -----Example----- Input 2 101 010 1111 1010 Output Lucky Chef 2 Unlucky Chef -----Explanation----- Example case 1. - Applying XOR operation with indices i = 1 and j = 2. Resulting string will be 011. - Then, Applying AND operation with indices i = 1 and j = 3. Resulting string will be 010. Example case 2. - It is impossible to convert string A to string B. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for j in range(int(input())): a=input() b=input() c,d=0,0 a0=a.count("0") a1=a.count("1") if(a0==len(a) or a1==len(a)): print("Unlucky Chef") else: print("Lucky Chef") for i in range(len(a)): if(a[i]!=b[i]): if(a[i]=="0"): c+=1 else: d+=1 print(max(c,d)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Raavan gave a problem to his son, Indrajeet, and asked him to solve the problem to prove his intelligence and power. The Problem was like: Given 3 integers, $N$, $K$, and $X$, produce an array $A$ of length $N$, in which the XOR of all elements of each contiguous sub-array, of length $K$, is exactly equal to $X$. Indrajeet found this problem very tricky and difficult, so, help him to solve this problem. -----Note:----- - $A$i must be an integer between $0$ to $10$$18$ (both inclusive), where $A$i denotes the $i$$th$ element of the array, $A$. - If there are multiple solutions, satisfying the problem condition(s), you can print any "one" solution. -----Input:----- - First line will contain $T$, number of testcases. Then, the testcases follow. - Each testcase, contains a single line of input, of 3 integers, $N$, $K$, and $X$. -----Output:----- For each testcase, output in a single line, an array $A$ of $N$ integers, where each element of the array is between $0$ to $10$$18$ (both inclusive), satisfying the conditions of the problem, given by Raavan to his son. -----Constraints:----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^3$ - $1 \leq K \leq N$ - $0 \leq X \leq 10$$18$ -----Sample Input:----- 3 5 1 4 5 2 4 5 3 4 -----Sample Output:----- 4 4 4 4 4 3 7 3 7 3 11 6 9 11 6 -----Explanation:----- $Sample$ $Case$ $-$ $1$: Since, we can see, the XOR of all elements of all sub-arrays of length $1$, is equal to $4$, hence, the array {$4,4,4,4,4$}, is a valid solution to the $Sample$ $Case$ $-$ $1$. All contiguous sub-arrays of length $1$, of the output array $A$, are as follows: [1,1]: {4} - XOR([1,1]) = $4$ [2,2]: {4} - XOR([2,2]) = $4$ [3,3]: {4} - XOR([3,3]) = $4$ [4,4]: {4} - XOR([4,4]) = $4$ [5,5]: {4} - XOR([5,5]) = $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 for _ in range(int(input())): l,n,x=map(int,input().split()) m=[] pw1 = (1 << 17); pw2 = (1 << 18); if (n == 1) : m.append(x) elif (n == 2 and x == 0) : m.append(-1) elif (n == 2) : m.append(x) m.append(0) else : ans = 0; for i in range(1, n - 2) : m.append(i) ans = ans ^ i; if (ans == x) : m.append(pw1+pw2) m.append(pw1) m.append(pw2) else: m.append(pw1) m.append((pw1 ^ x) ^ ans) m.append(0) p=(m)*l for i in range(0,l): print(p[i],end=' ') print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given Name of chef's friend and using chef's new method of calculating value of string , chef have to find the value of all the names. Since chef is busy , he asked you to do the work from him . The method is a function $f(x)$ as follows - - $f(x)$ = $1$ , if $x$ is a consonent - $f(x)$ = $0$ , if $x$ is a vowel Your task is to apply the above function on all the characters in the string $S$ and convert the obtained binary string in decimal number N. Since the number N can be very large, compute it modulo $10^9+7$ . Input: - First line will contain $T$, number of testcases. Then the testcases follow. - Each test line contains one String $S$ composed of lowercase English alphabet letters. -----Output:----- For each case, print a single line containing one integer $N$ modulo $10^9+7$ . -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq |S| \leq 10^5$ -----Sample Input:----- 1 codechef -----Sample Output:----- 173 -----EXPLANATION:----- The string "codechef" will be converted to 10101101 ,using the chef's method function . Which is equal to 173. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python vow = ['a', 'e', 'i','o', 'u'] for _ in range(int(input())): name = str(input()) tmp = '' for i in range(len(name)): if name[i] not in vow and name[i].isalpha(): tmp+='1' elif name[i] in vow and name[i].isalpha(): tmp+='0' print( int(tmp, 2)% (10**9 + 7)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This is the easy version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix. For example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$. Your task is to transform the string $a$ into $b$ in at most $3n$ operations. It can be proved that it is always possible. -----Input----- The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $3t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 1000$)  — the length of the binary strings. The next two lines contain two binary strings $a$ and $b$ of length $n$. It is guaranteed that the sum of $n$ across all test cases does not exceed $1000$. -----Output----- For each test case, output an integer $k$ ($0\le k\le 3n$), followed by $k$ integers $p_1,\ldots,p_k$ ($1\le p_i\le n$). Here $k$ is the number of operations you use and $p_i$ is the length of the prefix you flip in the $i$-th operation. -----Example----- Input 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 Output 3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1 -----Note----- In the first test case, we have $01\to 11\to 00\to 10$. In the second test case, we have $01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$. In the third test case, the strings are already the same. Another solution is to flip the prefix of length $2$, which will leave $a$ unchanged. 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 from collections import deque t=int(input()) for tests in range(t): n=int(input()) a=input().strip() b=input().strip() Q=deque(a) L=[] while Q: L.append(Q.popleft()) if Q: L.append(Q.pop()) ANS=[] for i in range(n): if i%2==0: if L[i]==b[-1-i]: ANS.append(1) else: if L[i]!=b[-1-i]: ANS.append(1) ANS.append(n-i) print(len(ANS),*ANS) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After acquiring an extraordinary amount of knowledge through programming contests, Malvika decided to harness her expertise to train the next generation of Indian programmers. So, she decided to hold a programming camp. In the camp, she held a discussion session for n members (n-1 students, and herself). They are sitting in a line from left to right numbered through 1 to n. Malvika is sitting in the nth spot. She wants to teach m topics of competitive programming to the students. As the people taking part in the camp are all newbies, they know none of the topics being taught, i.e., initially, the first n - 1 people in the line know none of the topics, while the nth knows all of them. It takes one hour for a person to learn a topic from his neighbour. Obviously, one person cannot both teach a topic as well as learn one during the same hour. That is, in any particular hour, a person can either teach a topic that he knows to one of his neighbors, or he can learn a topic from one of his neighbors, or he can sit idly. It is also obvious that if person x is learning from person y at a particular hour, then person y must be teaching person x at that hour. Also, note that people can work parallely too, i.e., in the same hour when the 4th person is teaching the 3rd person, the 1st person can also teach the 2nd or learn from 2nd. Find out the minimum number of hours needed so that each person learns all the m topics. -----Input----- - The first line of input contains a single integer T denoting number of test cases. - The only line of each test case contains two space separated integers n, m as defined in the statement. -----Output----- - For each test case, output a single integer in a line corresponding to the answer of the problem. -----Constraints----- - 1 ≤ T, n, m ≤ 100 -----Example----- Input: 2 2 1 3 2 Output: 1 4 -----Explanation----- In the first example, there are two people. Second person is Malvika and she has to teach only one topic to the first person. It will take only one hour to do so. In the second example, there are three people. The 3rd person is Malvika and she has to teach only two topics to 1st and 2nd person. In the 1st hour, she teaches the 1st topic to the 2nd person. Now, in the 2nd hour, the 2nd person will teach the 1st topic to the 1st person. In the 3rd hour, Malvika will teach the 2nd topic to the 2nd person. Now the 2nd person will teach that topic to the 1st in the 4th hour. So, it takes a total of 4 hours for all the people to know all the topics. 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=map(int, input().split()) if n==1: print(0) elif n==2: print(m) else: print(m*2+n-3) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is crazy man named P29892P. He always tries to do crazy things as he thinks. One day he invented a machine and named it as ANGEN. The ANGEN is used to perform range operations. The range operation means performing operations on range values from {L..R}. At any time it performs operations on values in between L to R. ANGEN can perform following operations U I V - Update the value present at I with value V A L R - Find the sum between range L and R M L R - Find the maximum number between L and R m L R - Find the minimum number between L and R S L R - Find second maximum value in between L and R s L R - Find second mimimum value in between L and R If it is not possible perform operation ANGEN returns “NA” with out quotes. For Invalid operations ANGEN returns “!!!” with out quotes. Now P29892P challenging his friends and you too, to build his invention with yourown code. So it's your time to defeat P29892P by implementing his invention with your own ability. Let's go and solve the problem. -----Input----- Input description. - The first line of the input contains an integer N denoting the number of integers. - The next line contains N space separated integers." - The next line contains a single integer Q denoting the number of Questions. - The next Q lines contains T Question type , L and R. -----Output----- Print output for each question in separate line. -----Constraints----- Should contain all the constraints on the input data that you may have. Format it like: - 1 ≤ N ≤ 100000 - 1 ≤ values[i] ≤ 1000000000 - 1 ≤ Q ≤ 10000 - T in { A..Z, a..z } - 1 ≤ L ≤ R ≤ N -----Example----- Input: 6 1 2 5 3 10 6 6 A 1 5 M 1 3 m 5 6 s 3 6 U 1 7 S 1 2 Output: 21 5 6 5 2 -----Explanation----- ... The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python VQ = "UAMmSs" n = int(input()) a = list(map(int, input().split())) for _ in range(int(input())): q, x, y = input().split() if q not in VQ: print("!!!") continue if q == "U": a[int(x) - 1] = int(y) continue l = int(x) - 1 r = int(y) if q == "A": print(sum(a[l:r])) continue if q == "M": print(max(a[l:r])) continue if q == "m": print(min(a[l:r])) continue s = sorted(set(a[l:r])) if len(s) < 2: print("NA") else: print(s[1] if q == "s" else s[-2]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef wants you to distribute candies among $N$ kids who are sitting in a circle. However, he wants to make some kids jealous of others. Thus, he wants you to distribute candies in such a way that there is a difference of at least $K$ candies between two adjacent kids. Given the value of $N$ and $K$, you need to find the minimum number of candies you need to satisfy the given conditions, such that, each kid gets at least one candy. -----Input:----- - First line will contain $T$, the number of testcases. Then the testcases follow. - The only line of each testcase contains two space-separated integers $N$ and $K$. -----Output:----- For each test case, print a single line containing one integer ― the number of candies you need. -----Constraints----- - $1 \leq T \leq 10^6$ - $2 \leq N \leq 10^3$ - $0 \leq K \leq 10^4$ -----Sample Input:----- 1 2 1 -----Sample Output:----- 3 -----EXPLANATION:----- The minimum number of candies required is $3$. One kid needs to have $1$ candy and the other needs to have $2$ candy to have a difference of $1$ candy between them. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n,k = [int(v) for v in input().split()] ans = (n//2)*(k+2) if n%2 == 0: ans = ans else: ans += 1 + 2*k print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Henry and Derek are waiting on a room, eager to join the Snackdown 2016 Qualifier Round. They decide to pass the time by playing a game. In this game's setup, they write N positive integers on a blackboard. Then the players take turns, starting with Henry. In a turn, a player selects one of the integers, divides it by 2, 3, 4, 5 or 6, and then takes the floor to make it an integer again. If the integer becomes 0, it is erased from the board. The player who makes the last move wins. Henry and Derek are very competitive, so aside from wanting to win Snackdown, they also want to win this game. Assuming they play with the optimal strategy, your task is to predict who wins the game. -----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 integers they wrote on the board. The second line contains N space-separated integers A1, A2, ..., AN denoting the integers themselves. -----Output----- For each test case, output a single line containing either “Henry” or “Derek” (without quotes), denoting the winner of the game. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ N ≤ 100 - 1 ≤ Ai ≤ 1018 -----Example----- Input:2 2 3 4 3 1 3 5 Output:Henry Derek -----Explanation----- Example case 1. In this test case, the numbers on the board are [3,4]. Henry can win by selecting 4 and then dividing it by 2. The integers on the board are now [3,2]. Derek now has a couple of choices: - Derek can divide 2 by 3, 4, 5 or 6, making it 0 and removing it. Now only one integer remains on the board, 3, and Henry can just divide it by 6 to finish, and win, the game. - Derek can divide 3 by 4, 5 or 6, making it 0 and removing it. Now only one integer remains on the board, 2, and Henry can just divide it by 6 to finish, and win, the game. - Derek can divide 2 by 2. Now the integers are [1,3]. Henry can respond by dividing 3 by 3. The integers are now [1,1]. Now Derek has no choice but to divide 1 by 2, 3, 4, 5 or 6 and remove it (because it becomes 0). Henry can respond by dividing the remaining 1 by 2 to finish, and win, the game. - Derek can divide 3 by 2 or 3. Now the integers are [1,2]. Henry can respond by dividing 2 by 2. The integers are now [1,1]. This leads to a situation as in the previous case and Henry wins. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python gb = [0, 1, 2, 2, 3, 3] ga = [0 for x in range(70)] gag = [0 for x in range(70)] ga[0] = 1 gag[0] = 0 for i in range(1, 70): if i % 4 == 0: ga[i] = 1.5 * ga[i-1] gag[i] = 0 else: ga[i] = 2 * ga[i-1] gag[i] = gag[i-1] + 1 def g(n): if n < 6: return gb[n] else: x = n / 6 a = 0 for i, k in enumerate(ga): if k <= x: a = i else: break return gag[a] t = int(input()) for q in range(t): n = int(input()) a = list(map(int, input().split())) res = g(a[0]) for i in range(1, n): res ^= g(a[i]) if res == 0: print("Derek") else: print("Henry") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This is a simple game you must have played around with during your school days, calculating FLAMES of you and your crush! Given the names of two people, cancel out the common letters (repeated occurrence of a letter is treated separately, so 2A's in one name and one A in the other would cancel one A in each name), count the total number of remaining letters (n) and repeatedly cut the letter in the word FLAMES which hits at the nth number when we count from F in cyclic manner. For example: NAME 1: SHILPA NAME 2: AAMIR After cutting the common letters: NAME 1: SHILPA NAME 2: AAMIR Total number of letters left=7 FLAMES, start counting from F : 1=F, 2=L, 3=A, 4=M, 5=E, 6=S,7=F...So cut F FLAMES: repeat this process with remaining letters of FLAMES for number 7 (start count from the letter after the last letter cut) . In the end, one letter remains. Print the result corresponding to the last letter: F=FRIENDS L=LOVE A=ADORE M=MARRIAGE E=ENEMIES S=SISTER -----Input----- The no. of test cases (<100) two names (may include spaces) for each test case. -----Output----- FLAMES result (Friends/Love/...etc) for each test case -----Example----- Input: 2 SHILPA AAMIR MATT DENISE Output: ENEMIES LOVE By: Chintan, Asad, Ashayam, Akanksha The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys def joseph(k, n=6): if k==0: k = 1 x = 0 for i in range(2,n+1): x = (x+k)%i return x FLAMES = ['FRIENDS', 'LOVE', 'ADORE', 'MARRIAGE', 'ENEMIES', 'SISTER'] nCase = int(sys.stdin.readline()) for _ in range(nCase): a = ''.join(sys.stdin.readline().split()) b = ''.join(sys.stdin.readline().split()) n = 0 for ch in set(a+b): n += abs(a.count(ch)-b.count(ch)) print(FLAMES[joseph(n)]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n. The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least l_{i} and at most r_{i} have fought for the right to continue taking part in the tournament. After the i-th fight among all participants of the fight only one knight won — the knight number x_{i}, he continued participating in the tournament. Other knights left the tournament. The winner of the last (the m-th) fight (the knight number x_{m}) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a. Write the code that calculates for each knight, the name of the knight that beat him. -----Input----- The first line contains two integers n, m (2 ≤ n ≤ 3·10^5; 1 ≤ m ≤ 3·10^5) — the number of knights and the number of fights. Each of the following m lines contains three integers l_{i}, r_{i}, x_{i} (1 ≤ l_{i} < r_{i} ≤ n; l_{i} ≤ x_{i} ≤ r_{i}) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle. -----Output----- Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0. -----Examples----- Input 4 3 1 2 1 1 3 3 1 4 4 Output 3 1 4 0 Input 8 4 3 5 4 3 7 6 2 8 8 1 8 1 Output 0 8 4 6 4 8 6 1 -----Note----- Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = map(int, input().split()) p, d = [0] * (n + 2), [0] * (n + 2) for i in range(m): l, r, x = map(int, input().split()) while l < x: if d[l]: k = d[l] d[l] = x - l l += k else: d[l], p[l] = x - l, x l += 1 l += 1 r += 1 while d[r]: r += d[r] while l < r: if d[l]: k = d[l] d[l] = r - l l += k else: d[l], p[l] = r - l, x l += 1 print(' '.join(map(str, p[1: -1]))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are provided with an input containing a number. Implement a solution to find the largest sum of consecutive increasing digits , and present the output with the largest sum and the positon of start and end of the consecutive digits. Example : Input :> 8789651 Output :> 24:2-4 where 24 is the largest sum and 2-4 is start and end of the consecutive increasing digits. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python l=list(map(int,input())) t=-1 x=-1 y=-1 for i in range(len(l)): s=l[i] a=i+1 b=i+1 for j in range(i+1,len(l)): if l[i]<l[j]: s=s+l[j] b=j+1 else: break if s>t: t=s x=a y=b print(t,end=":") print(x,y,sep="-") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Toad Zitz has an array of integers, each integer is between $0$ and $m-1$ inclusive. The integers are $a_1, a_2, \ldots, a_n$. In one operation Zitz can choose an integer $k$ and $k$ indices $i_1, i_2, \ldots, i_k$ such that $1 \leq i_1 < i_2 < \ldots < i_k \leq n$. He should then change $a_{i_j}$ to $((a_{i_j}+1) \bmod m)$ for each chosen integer $i_j$. The integer $m$ is fixed for all operations and indices. Here $x \bmod y$ denotes the remainder of the division of $x$ by $y$. Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations. -----Input----- The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 300\,000$) — the number of integers in the array and the parameter $m$. The next line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i < m$) — the given array. -----Output----- Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print $0$. It is easy to see that with enough operations Zitz can always make his array non-decreasing. -----Examples----- Input 5 3 0 0 0 1 2 Output 0 Input 5 7 0 6 1 3 2 Output 1 -----Note----- In the first example, the array is already non-decreasing, so the answer is $0$. In the second example, you can choose $k=2$, $i_1 = 2$, $i_2 = 5$, the array becomes $[0,0,1,3,3]$. It is non-decreasing, so the answer is $1$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline n,m=list(map(int,input().split())) A=list(map(int,input().split())) MIN=0 MAX=m while MIN!=MAX: x=(MIN+MAX)//2 #print(x,MIN,MAX) #print() M=0 for a in A: #print(a,M) if a<=M and a+x>=M: continue elif a>M and a+x>=m and (a+x)%m>=M: continue elif a>M: M=a else: MIN=x+1 break else: MAX=x print(MIN) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- 1 13 57 135 7911 131517 1357 9111315 17192123 25272931 -----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 n = int(input()) l = [0] * n for x in range(n): l[x] = int(input()) for i in range(n): z = 1 for j in range(1,l[i]+1): for k in range(1,l[i]+1): print(z,end='') z += 2 print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring $s[l \ldots r]$ ($1 \leq l \leq r \leq |s|$) of a string $s = s_{1}s_{2} \ldots s_{|s|}$ is the string $s_{l}s_{l + 1} \ldots s_{r}$. Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $s$ is changed into its longest substring that is not a palindrome. If all the substrings of $s$ are palindromes, she skips the word at all. Some time ago Ann read the word $s$. What is the word she changed it into? -----Input----- The first line contains a non-empty string $s$ with length at most $50$ characters, containing lowercase English letters only. -----Output----- If there is such a substring in $s$ that is not a palindrome, print the maximum length of such a substring. Otherwise print $0$. Note that there can be multiple longest substrings that are not palindromes, but their length is unique. -----Examples----- Input mew Output 3 Input wuffuw Output 5 Input qqqqqqqq Output 0 -----Note----- "mew" is not a palindrome, so the longest substring of it that is not a palindrome, is the string "mew" itself. Thus, the answer for the first example is $3$. The string "uffuw" is one of the longest non-palindrome substrings (of length $5$) of the string "wuffuw", so the answer for the second example is $5$. All substrings of the string "qqqqqqqq" consist of equal characters so they are palindromes. This way, there are no non-palindrome substrings. Thus, the answer for the third example is $0$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s = input() mx = 0 n = len(s) for l in range(n): for r in range(l, n): if s[l:r+1] != s[l:r+1][::-1]: mx = max(mx, r - l + 1) print(mx) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef was searching for his pen in the garage but he found his old machine with a display and some numbers on it. If some numbers entered then some different output occurs on the display. Chef wants to crack the algorithm that the machine is following. Example to identify the pattern : Input Output 9 36 5 10 1 0 2 1 -----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 as displayed on the screen. -----Constraints----- - $1 \leq T \leq 10^6$ - $1 \leq N \leq 10^6$ -----Sample Input:----- 1 7 -----Sample Output:----- 21 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here T = int(input()) for t in range(T): N = int(input()) print(int(((N-1)*(N))/2)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sheldon is a little geek living in Texas. While his friends like to play outside, little Sheldon likes to play around with ICs and lasers in his house. He decides to build N clap activated toggle machines each with one power inlet and one outlet. Each machine works when its power source inlet is receiving power. When the machine is in 'ON' state and is receiving power at its inlet, it makes power available at its power outlet to which a bulb or another ToGgLe machine could be attached. Suppose Sheldon attached 2 such machines to one another with the power inlet of the first machine attached to a power source at his house and the outlet of the second machine to a bulb. Initially both machines are in 'OFF' state and power source to first machine is off too. Now the power source is switched on. The first machine receives power but being in the 'OFF' state it does not transmit any power. Now on clapping the first ToGgLe machine toggles to 'ON' and the second machine receives power. On clapping once more the first toggles to 'OFF' and the second toggles to 'ON'. But since the second ToGgLe machine receives no power the bulb does not light up yet. On clapping once more, the first machine which is still receiving power from the source toggles to 'ON' and the second which was already 'ON' does not toggle since it was not receiving power. So both the machine are in 'ON' state and the bulb lights up and little Sheldon is happy. But when Sheldon goes out for a while, his evil twin sister attaches N such ToGgLe machines (after making sure they were all in 'OFF' state) and attaches the first to a power source (the power source is initially switched off) and the last ToGgLe machine to a bulb. Sheldon is horrified to find that his careful arrangement has been disturbed. Coders, help the poor boy by finding out if clapping k times for the N ToGgLe machines (all in 'OFF' state with the first one connected to a switched off power source and last one to a bulb) would light the bulb. Hurry before Sheldon has a nervous breakdown! -----Input----- First line has number of test cases, T. Following T lines have N, k separated by a single space where N is the number of ToGgLe machines and k is the number of times Sheldon clapped. -----Output----- T lines with cach line of the form: "ON" (just the word on without the double quotes) if the bulb is 'ON' for the test case numbered n and "OFF" (just the word off without the double quotes) if the bulb is 'OFF' for the test case numbered n. -----Example----- Input: 4 4 0 4 47 1 0 1 1 Output: OFF ON OFF ON The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n=int(input()) while n>0: i=1 a,b=(int(i) for i in input().split()) if (b+1)%(i<<a)==0: print("ON") else: print("OFF") n=n-1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A manufacturing project consists of exactly $K$ tasks. The board overviewing the project wants to hire $K$ teams of workers — one for each task. All teams begin working simultaneously. Obviously, there must be at least one person in each team. For a team of $A$ workers, it takes exactly $A$ days to complete the task they are hired for. Each team acts independently, unaware of the status of other teams (whether they have completed their tasks or not), and submits their result for approval on the $A$-th day. However, the board approves the project only if all $K$ teams complete their tasks on the same day — it rejects everything submitted on any other day. The day after a team finds out that its result was rejected, it resumes work on the same task afresh. Therefore, as long as a team of $A$ workers keeps getting rejected, it submits a new result of their task for approval on the $A$-th, $2A$-th, $3A$-th day etc. The board wants to hire workers in such a way that it takes exactly $X$ days to complete the project. Find the smallest number of workers it needs to hire. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $K$ and $X$. -----Output----- For each test case, print a single line containing one integer — the smallest required number of workers. -----Constraints----- - $1 \le T \le 40$ - $2 \le K, X \le 10^6$ -----Example Input----- 2 2 3 2 6 -----Example Output----- 4 5 -----Explanation----- Example case 1: We can hire a team of $3$ workers for task $1$ and $1$ worker for task $2$. The one-man team working on task $2$ completes it and submits the result for approval on each day, but it is rejected on the first and second day. On the third day, the team working on task $1$ also completes their task, so the project gets approved after exactly $3$ days. Example case 2: We can hire a team of $3$ workers for task $1$ and a team of $2$ workers for task $2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import log2; import bisect; from bisect import bisect_left,bisect_right import sys; from math import gcd,sqrt sys.setrecursionlimit(10**7) from collections import defaultdict inf=float("inf") # n=int(input()) # n,m=map(int,input().split()) # l=list(map(int,input().split())) def get_factors(x): if x==1: return []; sqrta=int(sqrt(x))+1 for i in range(2,sqrta): if x%i==0: return [i]+get_factors(x//i) return [x] def min_generator(fac,k,index,new_list): if index==len(fac): return sum(new_list) mina=inf; for i in range(0,min(index+1,len(new_list))): new_list[i]*=fac[index] theta=min_generator(fac,k,index+1,new_list) if theta<mina: mina=theta; new_list[i]//=fac[index] return mina; def fun(k,x): dict=defaultdict(lambda :1) factors=get_factors(x) for i in factors: dict[i]*=i; if len(dict)==k: print(sum(dict.values())) return; if len(dict)<k: suma=sum(dict.values()) left=k-len(dict) suma+=left; print(suma) return; if k==1: print(x) return; fac=list(dict.values()) new_list=[1]*k theta=min_generator(fac,k,0,new_list) print(theta) for i in range(int(input())): k,x=map(int,input().split()) fun(k,x) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (counting from the top), then 3 glasses on the third level and so on.The bottom level consists of n glasses. Vlad has seen in the movies many times how the champagne beautifully flows from top levels to bottom ones, filling all the glasses simultaneously. So he took a bottle and started to pour it in the glass located at the top of the pyramid. Each second, Vlad pours to the top glass the amount of champagne equal to the size of exactly one glass. If the glass is already full, but there is some champagne flowing in it, then it pours over the edge of the glass and is equally distributed over two glasses standing under. If the overflowed glass is at the bottom level, then the champagne pours on the table. For the purpose of this problem we consider that champagne is distributed among pyramid glasses immediately. Vlad is interested in the number of completely full glasses if he stops pouring champagne in t seconds. Pictures below illustrate the pyramid consisting of three levels. [Image] [Image] -----Input----- The only line of the input contains two integers n and t (1 ≤ n ≤ 10, 0 ≤ t ≤ 10 000) — the height of the pyramid and the number of seconds Vlad will be pouring champagne from the bottle. -----Output----- Print the single integer — the number of completely full glasses after t seconds. -----Examples----- Input 3 5 Output 4 Input 4 8 Output 6 -----Note----- In the first sample, the glasses full after 5 seconds are: the top glass, both glasses on the second level and the middle glass at the bottom level. Left and right glasses of the bottom level will be half-empty. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, t = list(map(int,input().split())) g = [[0.0] * i for i in range(1,n+1)] for _ in range(t): g[0][0] += 1.0 for i in range(n): for j in range(i+1): spill = max(0, g[i][j] - 1.0) g[i][j] -= spill if i < n - 1: g[i + 1][j] += spill / 2 g[i + 1][j + 1] += spill / 2 if g[n-1][0] == 1.0: break cnt = 0 for i in range(n): for j in range(i + 1): if g[i][j] == 1.0: cnt += 1 print(cnt) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist. First, Andrew counted all the pokémon — there were exactly $n$ pikachu. The strength of the $i$-th pokémon is equal to $a_i$, and all these numbers are distinct. As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $b$ from $k$ indices such that $1 \le b_1 < b_2 < \dots < b_k \le n$, and his army will consist of pokémons with forces $a_{b_1}, a_{b_2}, \dots, a_{b_k}$. The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$. Andrew is experimenting with pokémon order. He performs $q$ operations. In $i$-th operation Andrew swaps $l_i$-th and $r_i$-th pokémon. Note: $q=0$ in this version of the task. Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation. Help Andrew and the pokémon, or team R will realize their tricky plan! -----Input----- Each test contains multiple test cases. The first line contains one positive integer $t$ ($1 \le t \le 10^3$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $n$ and $q$ ($1 \le n \le 3 \cdot 10^5, q = 0$) denoting the number of pokémon and number of operations respectively. The second line contains $n$ distinct positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) denoting the strengths of the pokémon. $i$-th of the last $q$ lines contains two positive integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$) denoting the indices of pokémon that were swapped in the $i$-th operation. It is guaranteed that the sum of $n$ over all test cases does not exceed $3 \cdot 10^5$, and the sum of $q$ over all test cases does not exceed $3 \cdot 10^5$. -----Output----- For each test case, print $q+1$ integers: the maximal strength of army before the swaps and after each swap. -----Example----- Input 3 3 0 1 3 2 2 0 1 2 7 0 1 2 5 4 3 6 7 Output 3 2 9 -----Note----- In third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $5−3+7=9$. 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 from bisect import bisect_right bin_s = [1] while bin_s[-1] <= 10 ** 9: bin_s.append(bin_s[-1] * 2) def main(): n, q = map(int, input().split()) alst = list(map(int, input().split())) dp = [[-1, -1] for _ in range(n)] dp[0] = [alst[0], 0] for i, a in enumerate(alst[1:], start = 1): dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + a) dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - a) print(max(dp[-1])) for _ in range(int(input())): main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Karen is getting ready for a new school day! [Image] It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome? Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50. -----Input----- The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59). -----Output----- Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome. -----Examples----- Input 05:39 Output 11 Input 13:31 Output 0 Input 23:59 Output 1 -----Note----- In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome. In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome. In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s = input() h = int(s[:2]) m = int(s[3:]) def ispalin(h, m): s = "%02d:%02d"%(h,m) return s == s[::-1] for d in range(999999): if ispalin(h, m): print(d) break m+= 1 if m == 60: h = (h+1)%24 m = 0 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. -----Input----- The first line contains two integers, n and k (1 ≤ n ≤ 10^5; 1 ≤ k ≤ 10^9). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 10^5. Each string of the group consists only of lowercase English letters. -----Output----- If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). -----Examples----- Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ Codeforces Contest 260 Div 1 Problem B Author : chaotic_iak Language: Python 3.3.4 """ def main(): n,k = read() s = set() for i in range(n): s.add(read(0)) s = list(s) s.sort() s = treeify(s) res = solve(s) if res == 0: # neither: second player win print("Second") if res == 1: # odd: first player win if k is odd print("First" if k % 2 else "Second") if res == 2: # even: second player win print("Second") if res == 3: # both: first player win print("First") def treeify(s): res = [[] for _ in range(26)] for i in s: if i: res[ord(i[0]) - 97].append(i[1:]) fin = [] for i in range(26): if res[i]: fin.append(treeify(res[i])) return fin def solve(s, parity=2): for i in range(len(s)): if isinstance(s[i], list): s[i] = solve(s[i], 3-parity) if not s: return parity # no possible move: current parity if 0 in s: return 3 # any neither: both if 1 in s and 2 in s: return 3 # any odd and any even: both if 1 in s: return 1 # any odd: odd if 2 in s: return 2 # any even: even return 0 # all both: neither ################################### NON-SOLUTION STUFF BELOW def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return map(int, inputs.split()) def write(s="\n"): if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a sequence a_1, a_2, ..., a_{n} of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment a_{i} lies within segment a_{j}. Segment [l_1, r_1] lies within segment [l_2, r_2] iff l_1 ≥ l_2 and r_1 ≤ r_2. Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1. -----Input----- The first line contains one integer n (1 ≤ n ≤ 3·10^5) — the number of segments. Each of the next n lines contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^9) — the i-th segment. -----Output----- Print two distinct indices i and j such that segment a_{i} lies within segment a_{j}. If there are multiple answers, print any of them. If no answer exists, print -1 -1. -----Examples----- Input 5 1 10 2 9 3 9 2 3 2 9 Output 2 1 Input 3 1 5 2 6 6 20 Output -1 -1 -----Note----- In the first example the following pairs are considered correct: (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders; (3, 2), (4, 2), (3, 5), (4, 5) — touch one border; (5, 2), (2, 5) — match exactly. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) a = [] for i in range(1, n + 1): l, r = list(map(int, input().split())) a.append([l, -r, i]) a.sort() hh = a[0][1] wahh = max(-1, a[0][2]) for i in range(1, n): if a[i][1] >= hh: print(a[i][2], wahh) return else: hh = a[i][1] wahh = a[i][2] print(-1, -1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: - Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq Q \leq 10^5 - 1 \leq a_i, b_i \leq N - 1 \leq c_i \leq N-1 - 1 \leq d_i \leq 10^4 - 1 \leq x_j \leq N-1 - 1 \leq y_j \leq 10^4 - 1 \leq u_j < v_j \leq N - The given graph is a tree. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q -----Output----- Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. -----Sample Input----- 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 -----Sample Output----- 130 200 60 The graph in this input is as follows: Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line. - Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130. - Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200. - Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have their original lengths. 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 sys.setrecursionlimit(10**5) N, Q = map(int, input().split()) path = [[] for _ in range(N)] for _ in range(N-1) : a, b, c, d = (int(i) for i in input().split()) path[a-1].append((b-1, c-1, d)) path[b-1].append((a-1, c-1, d)) # doublingに必要なKを求める for K in range(18) : if 2 ** K >= N : break # dfs parent = [[-1] * N for _ in range(K)] rank = [-1 for _ in range(N)] rank[0] = 0 queue = [0] while queue : cur = queue.pop() for nex, _, _ in path[cur] : if rank[nex] < 0 : queue.append(nex) parent[0][nex] = cur rank[nex] = rank[cur] + 1 # doubling for i in range(1, K) : for j in range(N) : if parent[i-1][j] > 0 : parent[i][j] = parent[i-1][parent[i-1][j]] # lca def lca(a, b) : if rank[a] > rank[b] : a, b = b, a diff = rank[b] - rank[a] i = 0 while diff > 0 : if diff & 1 : b = parent[i][b] diff >>= 1 i += 1 if a == b : return a for i in range(K-1, -1, -1) : if parent[i][a] != parent[i][b] : a = parent[i][a] b = parent[i][b] return parent[0][a] # Queryの先読み schedule = [[] for _ in range(N)] for i in range(Q) : x, y, u, v = map(int, input().split()) x, u, v = x-1, u-1, v-1 l = lca(u, v) schedule[u].append((i, 1, x, y)) schedule[v].append((i, 1, x, y)) schedule[l].append((i, -2, x, y)) ret = [0] * Q C = [0] * (N-1) D = [0] * (N-1) def dfs(cur, pre, tot) : for i, t, c, d in schedule[cur] : ret[i] += t * (tot - D[c] + C[c] * d) for nex, c, d in path[cur] : if nex == pre : continue C[c] += 1 D[c] += d dfs(nex, cur, tot + d) C[c] -= 1 D[c] -= d dfs(0, -1, 0) for i in range(Q) : print(ret[i]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Your are given a string $S$ containing only lowercase letter and a array of character $arr$. Find whether the given string only contains characters from the given character array. Print $1$ if the string contains characters from the given array only else print $0$. Note: string contains characters in lower case only. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains- a string $S$ of lowercase letter a integer $n$ denoting length of character array $arr$ next line contains $n$ space separated characters. -----Output:----- For each testcase, Print $1$ if the string contains characters from the given array only else print $0$. -----Constraints----- - $1 \leq T \leq 1000$ - $0 \leq n \leq 10^5$ -----Sample Input:----- 3 abcd 4 a b c d aabbbcccdddd 4 a b c d acd 3 a b d -----Sample Output:----- 1 1 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for _ in range(t): S=set(input().strip()) n=int(input().strip()) a=set(input().strip().split(" ")) g=True for i in S: if(i not in a): g=False if(g): print(1) else: print(0) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. You are also given a positive integer $k$. In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa). The garland is called $k$-periodic if the distance between each pair of adjacent turned on lamps is exactly $k$. Consider the case $k=3$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa. Your task is to find the minimum number of moves you need to make to obtain $k$-periodic garland from the given one. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 25~ 000$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains two integers $n$ and $k$ ($1 \le n \le 10^6; 1 \le k \le n$) — the length of $s$ and the required period. The second line of the test case contains the string $s$ consisting of $n$ characters '0' and '1'. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^6$ ($\sum n \le 10^6$). -----Output----- For each test case, print the answer — the minimum number of moves you need to make to obtain $k$-periodic garland from the given one. -----Example----- Input 6 9 2 010001010 9 3 111100000 7 4 1111111 10 3 1001110101 1 1 1 1 1 0 Output 1 2 5 4 0 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 input = sys.stdin.readline rInt = lambda: int(input()) mInt = lambda: map(int, input().split()) rLis = lambda: list(map(int, input().split())) outs = [] t = rInt() for _ in range(t): n, k = mInt() s = input() pref = [0] for c in s: if c == '1': pref.append(pref[-1] + 1) else: pref.append(pref[-1]) best = pref[-1] dp = [] for i in range(n): cost = pref[i] if i >= k: case2 = dp[i - k] + pref[i] - pref[i - k + 1] if case2 < cost: cost = case2 if s[i] == '0': cost += 1 dp.append(cost) actual = cost + pref[-1] - pref[i + 1] if actual < best: best = actual outs.append(best) print(*outs, sep = '\n') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Problem description. Winston and Royce love sharing memes with each other. They express the amount of seconds they laughed ar a meme as the number of ‘XD’ subsequences in their messages. Being optimization freaks, they wanted to find the string with minimum possible length and having exactly the given number of ‘XD’ subsequences. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. - Next T lines contains a single integer N, the no of seconds laughed. -----Output----- - For each input, print the corresponding string having minimum length. If there are multiple possible answers, print any. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ N ≤ 109 - 1 ≤ Sum of length of output over all testcases ≤ 5*105 -----Example----- Input: 1 9 Output: XXXDDD -----Explanation----- Some of the possible strings are - XXDDDXD,XXXDDD,XDXXXDD,XDXDXDD etc. Of these, XXXDDD is the smallest. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for i in range(t): n=int(input()) r=int(n**(.5)) d=n-r*r m=d%r print('X'*m+'D'*(m>0)+'X'*(r-m)+'D'*(r+d//r)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even. Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written. Recently, they learned the operation called xor (exclusive OR).What is xor? For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows: - When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even. For example, 3~\textrm{xor}~5 = 6. They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf. We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i. Using this information, restore the integer written on the scarf of each Snuke Cat. -----Constraints----- - All values in input are integers. - 2 \leq N \leq 200000 - N is even. - 0 \leq a_i \leq 10^9 - There exists a combination of integers on the scarfs that is consistent with the given information. -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 \ldots a_N -----Output----- Print a line containing N integers separated with space. The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i. If there are multiple possible solutions, you may print any of them. -----Sample Input----- 4 20 11 9 24 -----Sample Output----- 26 5 7 22 - 5~\textrm{xor}~7~\textrm{xor}~22 = 20 - 26~\textrm{xor}~7~\textrm{xor}~22 = 11 - 26~\textrm{xor}~5~\textrm{xor}~22 = 9 - 26~\textrm{xor}~5~\textrm{xor}~7 = 24 Thus, this output is consistent with the given information. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n=int(input()) a=list(map(int,input().split())) X=[] b=a[0] for i in range(1,n) : b^=a[i] for i in range(n) : x=b^a[i] X.append(x) for i in X : print(i,end=" ") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: "How did you get the deal,how did he agree?" "Its's simple Tom I just made him an offer he couldn't refuse" Ayush is the owner of a big construction company and a close aide of Don Vito The Godfather, recently with the help of the Godfather his company has been assigned a big contract according to the contract he has to make n number of V shaped infinitely long roads(two V shaped roads may or not intersect) on an infinitely large field. Now the company assigning the contract needs to know the maximum number of regions they can get after making n such roads. Help Ayush by answering the above question. -----Input:----- - The first line consists of the number of test cases $T$. - Next T lines consists of the number of V shaped roads $n$. -----Output:----- For each test case print a single line consisting of the maximum regions obtained. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq n \leq 10^9$ -----Sample Input:----- 2 1 2 -----Sample Output:----- 2 7 -----EXPLANATION:----- Test case 1: For one V shaped road there will be 2 regions Test case 2: For n=2 the following figure depicts the case of maximum regions: 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()) print((2*(pow(n,2)))-n+1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Edo has got a collection of n refrigerator magnets! He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers. Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes. Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of ​​the door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan. Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x_1, y_1) and the upper right corner (x_2, y_2), then its center is located at ($\frac{x_{1} + x_{2}}{2}$, $\frac{y_{1} + y_{2}}{2}$) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator. The sides of the refrigerator door must also be parallel to coordinate axes. -----Input----- The first line contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ min(10, n - 1)) — the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator. Next n lines describe the initial plan of placing magnets. Each line contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1 < x_2 ≤ 10^9, 1 ≤ y_1 < y_2 ≤ 10^9) — the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide. -----Output----- Print a single integer — the minimum area of the door of refrigerator, which can be used to place at least n - k magnets, preserving the relative positions. -----Examples----- Input 3 1 1 1 2 2 2 2 3 3 3 3 4 4 Output 1 Input 4 1 1 1 2 2 1 9 2 10 9 9 10 10 9 1 10 2 Output 64 Input 3 0 1 1 2 2 1 1 1000000000 1000000000 1 3 8 12 Output 249999999000000001 -----Note----- In the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly. In the second test sample it doesn't matter which magnet to remove, the answer will not change — we need a fridge with door width 8 and door height 8. In the third sample you cannot remove anything as k = 0. 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* # def check(u, d, l, r): used = [pointsx[i][1] for i in range(l)] used += [pointsx[-1 - i][1] for i in range(r)] used += [pointsy[i][1] for i in range(u)] used += [pointsy[-1 - i][1] for i in range(d)] if len(set(used)) > k: return DOHERA dx = pointsx[-1 - r][0] - pointsx[l][0] dy = pointsy[-1 - d][0] - pointsy[u][0] dx += dx & 1 dy += dy & 1 dx = max(2, dx) dy = max(2, dy) return dx * dy # (n, k) = list(map(int, input().split())) pointsx = [] pointsy = [] DOHERA = 10 ** 228 for i in range(n): a = list(map(int, input().split())) pointsx += [(a[0] + a[2], i)] pointsy += [(a[1] + a[3], i)] (pointsx, pointsy) = (sorted(pointsx), sorted(pointsy)) ans = DOHERA for u in range(0, k + 1): for d in range(0, k + 1): for l in range(0, k + 1): for r in range(0, k + 1): if l + r <= k and u + d <= k: ans = min(ans, check(u, d, l, r)) print(ans // 4) # Made By Mostafa_Khaled ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a girl named ''Akansha''. She is very fond of eating chocolates but she has a weak immune system due to which she gets cold after eating chocolate during morning, evening and night and can only eat at most $x$ number of chocolate each afternoon. A friend of hers gifted her some $n$ number of chocolates that she doesn't want to share with anyone. Those chocolate have to be finished before they expire. (no. of days in which they are going to expire from the day she has been gifted the chocolate is given for each chocolate) $Note:$ Chocolate cannot be consumed on the day it expires. Help Akansha to know if it is possible for her to finish all the chocolates before they expire or not. -----Input:----- - First line will contain $T$, number of test cases. Then the test cases follow. - First line contains $n$,the number of chocolates gifted to her - Second line contains $x$,the number of chocolates she can eat each afternoon - Third line contains $n$ space separated integers $A1,A2...An$,denoting the expiry of each of the $n$ chocolates -----Output:----- For each testcase, print $Possible$, if she can complete all the chocolates gifted to her. Otherwise, print $Impossible$, if she can not finish all the chocolates. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq n \leq 1500$ - $1 \leq x \leq 1500$ - $1 \leq Ai \leq 1500$ -----Subtasks----- - 100 points : $Original Constraints$ -----Sample Input:----- 3 3 5 4 1 2 5 2 4 4 3 2 2 5 1 4 2 3 1 1 -----Sample Output:----- Impossible Possible Impossible -----EXPLANATION:----- - Example case 1 1st and 3rd chocolate on the 1st afternoon as she can consume at most 5. one chocolate will be wasted. $Note:$ she cannot eat the 2nd chocolate because chocolates cannot be consumed on the day of expiry. - Example case 2 4th and 5th chocolate on 1st afternoon, 3rd and 1st chocolate on 2nd afternoon. And 2nd chocolate on the 3rd afternoon. It will take a total of 3 days to finish the chocolate. - Example case 3 She cannot eat 4th and 5th chocolate as they will expire on the very 1st day, she can eat 2nd chocolate on 1st afternoon, then 3rd chocolate on 2nd afternoon, then 1st chocolate on 3rd afternoon, and 2 chocolates 4th and 5th will expire. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for t in range(int(input().strip())): n = int(input().strip()) x = int(input().strip()) arr = list(map(int, input().strip().split())) arr.sort() day = 1 acc = 0 isPossible = True for a in arr: acc += 1 if acc > x: day += 1 acc = 1 if day >= a: isPossible = False break print("Possible" if isPossible else "Impossible") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Shivam owns a gambling house, which has a special wheel called The Wheel of Fortune. This wheel is meant for giving free coins to people coming in the house. The wheel of fortune is a game of chance. It uses a spinning wheel with exactly N numbered pockets and a coin is placed in between every consecutive pocket. The wheel is spun in either of the two ways. Before the wheel is turned, all the coins are restored and players bet on a number K. Then a needle is made to point to any one of the pocket which has number K written on it. Wheel is then spun till the needle encounters number K again and the player gets all the coins the needle has encountered. Shivam being the owner of the gambling house, has the authority to place the needle on any of the K numbered pockets and also he could rotate the wheel in either of the two ways. Shivam has to figure out a way to minimize number of coins that he has to spend on every given bet. You are given a wheel having N elements and Q players. Each player bets on a number K from the wheel. For each player you have to print minimum number of coins Shivam has to spend. -----Input----- - The first line of the input contains an integer T denoting the number of test cases . The description of T testcases follow. - The first line of each test case contains single integer N . - The second line of each test case contains N space seperated integers denoting the numbers on the wheel. - The third line of each test case contains a single integer Q denoting the number of players. - Then, Q lines follow a single integer K from the N numbers of the wheel -----Output----- For each player, output the minimum number of coins Shivam has to spend. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 100000 - 1 ≤ Number written on the Wheel ≤ 1000 - 1 ≤ Q ≤ 10000 - 1 ≤ K ≤ 1000 - It is guaranteed that K belongs to the N numbers written on the wheel. -----Example----- Input: 2 3 1 2 3 3 1 2 3 6 2 1 5 3 2 1 4 1 2 3 5 Output: 3 3 3 2 2 6 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): n=int(input()) arr=list(map(int,input().split())) d={} for i in range(n): if arr[i] in d: d[arr[i]].append(i) else: d[arr[i]]=[i] q=int(input()) for i in range(q): m=int(input()) if len(d[m])==1: print(n) elif len(d[m])==2: print(min((d[m][1]-d[m][0]),((n-d[m][1])+d[m][0]))) else: k=100000 for j in range(len(d[m])-1): if (d[m][j+1]-d[m][j])<k: k=d[m][j+1]-d[m][j] else: pass print(min(k,((n-d[m][len(d[m])-1])+d[m][0]))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p_1, p_2, ..., p_{n}. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality p_{i} > p_{i} + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality p_{i} < p_{i} + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. -----Input----- The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the permutation p. The numbers are separated by spaces. -----Output----- In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10^{ - 6}. -----Examples----- Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 -----Note----- In the first test the sequence is already sorted, so the answer is 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python 3 import sys class CumTree: def __init__(self, a, b): self.a = a self.b = b self.count = 0 if a == b: return mid = (a + b) // 2 self.levo = CumTree(a, mid) self.desno = CumTree(mid+1, b) def manjsi(self, t): if self.a >= t: return 0 if self.b < t: return self.count return self.levo.manjsi(t) + self.desno.manjsi(t) def vstavi(self, t): if self.a <= t <= self.b: self.count += 1 if self.a == self.b: return self.levo.vstavi(t) self.desno.vstavi(t) n = int(sys.stdin.readline()) p = [int(x) for x in sys.stdin.readline().strip().split()] ct = CumTree(1, 4096) vsota = 0 while len(p) > 0: x = p.pop() vsota += ct.manjsi(x) ct.vstavi(x) k, d = vsota // 2, vsota % 2 print("%f" % (4*k + d)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Little X has n distinct integers: p_1, p_2, ..., p_{n}. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: If number x belongs to set A, then number a - x must also belong to set A. If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. -----Input----- The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 10^5; 1 ≤ a, b ≤ 10^9). The next line contains n space-separated distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 10^9). -----Output----- If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b_1, b_2, ..., b_{n} (b_{i} equals either 0, or 1), describing the division. If b_{i} equals to 0, then p_{i} belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). -----Examples----- Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO -----Note----- It's OK if all the numbers are in the same set, and the other one is empty. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import defaultdict def solve(n, a, b, xs): group = [None] * n id_ = {x: i for i, x in enumerate(xs)} if a == b: for x in xs: if a - x not in id_: return False group = [0] * n else: for i, x in enumerate(xs): if group[i] is not None: continue y = a - x z = b - x f1 = y in id_ and group[id_[y]] is None f2 = z in id_ and group[id_[z]] is None if f1 + f2 == 0: return False elif f1 + f2 == 1: g = int(f2) # End of link link = [] t = a if f1 else b while x in id_: link.append(x) x = t - x if x + x == t: break t = a + b - t # print(link) if len(link) % 2 == 0: for i, x in enumerate(link): group[id_[x]] = g elif link[0] * 2 == (b, a)[g]: for i, x in enumerate(link): group[id_[x]] = 1 - g elif link[-1] * 2 == (a, b)[g]: for i, x in enumerate(link): group[id_[x]] = g else: # Found invalid link, answer is "NO" return False return group n, a, b = list(map(int, input().split())) xs = list(map(int, input().split())) group = solve(n, a, b, xs) if isinstance(group, list): print('YES') print(' '.join(map(str, group))) else: print('NO') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: “Jesse, you asked me if I was in the meth business, or the money business… Neither. I’m in the empire business.” Walter’s sold his stack in Gray Matter Technologies, a company which he deserved half a credit, for peanuts. Now this company is worth a billion dollar company. Walter wants to get it's shares to have his Empire Business back and he founds an opportunity. There are $N$ persons having shares $A_1, A_2, A_3, … A_N$ in this company. Walter can buy these shares with their minimum Sold Values. Sold Values of a person's share $ i $ $(1 \leq i \leq N) $ with another person's share $ j $ $ (1 \leq j \leq N) $ is equal to $ A_j+|i-j| $. So, a person's share can have $ N $ possible sold values and Walter has to find minimum sold value among them for each person. Since Walter has to run his meth business also he asks you to find minimum sold value for each person. -----Input:----- - First line will contain $T$, number of test cases. Then the testcases follow. - The First line of each test case contains a integer $N$. - The Second line of each test case contains $N$ space integers namely $A_1,A_2,…A_N$. -----Output:----- For each test case, output in single line $N$ space integers denoting minimum sold value for each person. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 2*10^6 $ - $1 \leq A_i \leq 10^9 $ Sum of $N$ over all test cases will not exceed $2*10^6$. -----Sample Input:----- 2 5 6 5 5 5 2 5 1 2 3 4 5 -----Sample Output:----- 6 5 4 3 2 1 2 3 4 5 -----Explanation----- For first case: - Sold value for index $1$: $6,6,7,8,6$ - Sold value for index $2$: $7,5,6,7,5$ - Sold value for index $3$: $8,6,5,6,4$ - Sold value for index $4$: $9,7,6,5,3$ - Sold value for index $5$: $10,8,7,6,2$ Minimum sold value for each index will be $6,5,4,3,2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here T=int(input()) for _ in range(T): n=int(input()) arr=list(map(int,input().split())) left=[-1 for i in range(n)] right=[-1 for i in range(n)] min1=float("inf") for i in range(n): min1=min(arr[i],min1+1) left[i]=min1 min1=float("inf") for i in range(n-1,-1,-1): min1=min(arr[i],min1+1) right[i]=min1 for i in range(n): print(min(left[i],right[i]),end=" ") print("",end="\n") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an integer $D$. Find an integer sequence $A_1, A_2, \ldots, A_N$ such that the following conditions are satisfied: - $1 \le N \le 10^5$ - $1 \le A_i \le 10^5$ for each valid $i$ - $\sum_{i=1}^N \sum_{j=i}^N \left( \mathrm{min}(A_i, A_{i+1}, \ldots, A_j) - \mathrm{GCD}(A_i, A_{i+1}, \ldots, A_j) \right) = D$ It can be proved that a solution always exists under the given constraints. Note: $\mathrm{GCD}(B_1, B_2, \ldots, B_M)$ is the greatest integer which divides all the integers $B_1, B_2, \ldots, B_M$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains a single integer $D$. -----Output----- For each test case, print two lines. The first of these lines should contain a single integer $N$. The second line should contain $N$ space-separated integers $A_1, A_2, \ldots, A_N$. If there are multiple solutions, you may find any one of them. -----Constraints----- - $1 \le T \le 10$ - $0 \le D \le 10^9$ -----Example Input----- 4 2 5 200 13 -----Example Output----- 3 3 3 2 5 2 8 5 1 10 7 12 10 15 11 19 13 15 4 5 4 4 10 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t=int(input()) for i in range(t): D=int(input()) P=10**5-2 ans=[] if(D==0): ans.append(1) while(D>0): P=min(P,D) ans.append(P+2); ans.append(P+1); ans.append(1); D=D-P; print(len(ans)) print(*ans,sep=" ",end="\n") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets: the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are pairwise distinct (i.e. all $a_i$ are different), the $i$-th bracelet has a brightness $b_i$, where all the $b_i$ are pairwise distinct (i.e. all $b_i$ are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $i$-th daughter receives a necklace with brightness $x_i$ and a bracelet with brightness $y_i$, then the sums $x_i + y_i$ should be pairwise distinct. Help Kuroni to distribute the gifts. For example, if the brightnesses are $a = [1, 7, 5]$ and $b = [6, 1, 2]$, then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of $a_3 + b_1 = 11$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $a_1 + b_3 = 3$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $a_2 + b_2 = 8$. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of $a_1 + b_1 = 7$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $a_2 + b_2 = 8$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $a_3 + b_3 = 7$. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset! -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 100$)  — the number of daughters, necklaces and bracelets. The second line of each test case contains $n$ distinct integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$)  — the brightnesses of the necklaces. The third line of each test case contains $n$ distinct integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 1000$)  — the brightnesses of the bracelets. -----Output----- For each test case, print a line containing $n$ integers $x_1, x_2, \dots, x_n$, representing that the $i$-th daughter receives a necklace with brightness $x_i$. In the next line print $n$ integers $y_1, y_2, \dots, y_n$, representing that the $i$-th daughter receives a bracelet with brightness $y_i$. The sums $x_1 + y_1, x_2 + y_2, \dots, x_n + y_n$ should all be distinct. The numbers $x_1, \dots, x_n$ should be equal to the numbers $a_1, \dots, a_n$ in some order, and the numbers $y_1, \dots, y_n$ should be equal to the numbers $b_1, \dots, b_n$ in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them. -----Example----- Input 2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 Output 1 8 5 8 4 5 5 1 7 6 2 1 -----Note----- In the first test case, it is enough to give the $i$-th necklace and the $i$-th bracelet to the $i$-th daughter. The corresponding sums are $1 + 8 = 9$, $8 + 4 = 12$, and $5 + 5 = 10$. The second test case is described in the statement. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #list(map(int,input().split())) t=int(input()) for _ in range(t): n=int(input()) aa=list(map(int,input().split())) bb=list(map(int,input().split())) aa.sort() bb.sort() print(*aa) print(*bb) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Golomb sequence $G_1, G_2, \ldots$ is a non-decreasing integer sequence such that for each positive integer $n$, $G_n$ is the number of occurrences of $n$ in this sequence. The first few elements of $G$ are $[1, 2, 2, 3, 3, 4, 4, 4, 5, \ldots]$. Do you know the recurrence relation for the Golomb sequence? It is $G_1 = 1$ and $G_{n+1} = 1+G_{n+1-G_{G_n}}$ for each $n \ge 1$. A self-describing sequence, isn't it? Mr. Strange wants to learn CP, so he asked Chef, who is one of the best competitive programmers in the world, to teach him. Chef decided to test his ability by giving him the following task. Find the sum of squares of the $L$-th through $R$-th term of the Golomb sequence, i.e. $S = \sum_{i=L}^R G_i^2$. Since the sum can be quite large, compute it modulo $10^9+7$. Can you help Mr. Strange carry out this task given to him by his teacher? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $L$ and $R$. -----Output----- For each test case, print a single line containing one integer $S$ modulo $10^9+7$. -----Constraints----- - $1 \le T \le 10^5$ - $1 \le L \le R \le 10^{10}$ -----Subtasks----- Subtask #1 (50 points): - $T \le 10^2$ - $R \le 10^9$ Subtask #2 (50 points): original constraints -----Example Input----- 3 1 5 2 4 100 100 -----Example Output----- 27 17 441 -----Explanation----- Example case 1: $1^2 + 2^2 + 2^2 + 3^2 + 3^2 = 27$ Example case 2: $2^2 + 2^2 + 3^2 = 17$ Example case 3: $21^2 = 441$ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def find_upper_bound(arr,key): low,high = 0,len(arr)-1 while low<=high: mid = (low+high)//2 if arr[mid]==key:return mid elif arr[mid]>key and mid-1>=0 and arr[mid-1]<key:return mid elif arr[mid]>key:high = mid - 1 else:low = mid + 1 return mid def get_query(l): nonlocal prefix_storer,bin_storer ind = find_upper_bound(bin_storer,l) surplus = (abs(bin_storer[ind]-l)*ind*ind)%limit return (prefix_storer[ind]-surplus+limit)%limit def fire_query(l,r): return (get_query(r)-get_query(l-1)+limit)%limit golomb,dp,prefix_storer,bin_storer = [],[0,1],[0,1],[0,1] limit = 10**9+7 for i in range(2,10**6+100): dp.append(1 + dp[i-dp[dp[i-1]]]) bin_storer.append(dp[-1]+bin_storer[-1]) prefix_storer.append(((prefix_storer[-1] + (dp[-1]*i*i)%limit))%limit) # print(dp[1:20]) # print(bin_storer[1:20]) # print(prefix_storer[1:20]) # print(get_query(2),get_query(4)) for _ in range(int(input())): l,r = map(int,input().split()) print(fire_query(l,r)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an array of N integers a1, a2, ..., aN and an integer K. Find the number of such unordered pairs {i, j} that - i ≠ j - |ai + aj - K| is minimal possible Output the minimal possible value of |ai + aj - K| (where i ≠ j) and the number of such pairs for the given array and the integer K. -----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 consists of two space separated integers - N and K respectively. The second line contains N single space separated integers - a1, a2, ..., aN respectively. -----Output----- For each test case, output a single line containing two single space separated integers - the minimal possible value of |ai + aj - K| and the number of unordered pairs {i, j} for which this minimal difference is reached. -----Constraints----- - 1 ≤ T ≤ 50 - 1 ≤ ai, K ≤ 109 - N = 2 - 31 point. - 2 ≤ N ≤ 1000 - 69 points. -----Example----- Input: 1 4 9 4 4 2 6 Output: 1 4 -----Explanation:----- The minimal possible absolute difference of 1 can be obtained by taking the pairs of a1 and a2, a1 and a4, a2 and a4, a3 and a4. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): n,k=list(map(int, input().split())) l=list(map(int, input().split())) l.sort() c=0 mn=abs(l[0]+l[1]-k) for i in range(n-1): for j in range(i+1, n): temp=abs(l[i]+l[j]-k) if temp==mn: c+=1 elif temp<mn: mn=temp c=1 elif l[i]+l[j]-k>mn: break print(mn, c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $p$ of length $n$, and Skynyrd bought an array $a$ of length $m$, consisting of integers from $1$ to $n$. Lynyrd and Skynyrd became bored, so they asked you $q$ queries, each of which has the following form: "does the subsegment of $a$ from the $l$-th to the $r$-th positions, inclusive, have a subsequence that is a cyclic shift of $p$?" Please answer the queries. A permutation of length $n$ is a sequence of $n$ integers such that each integer from $1$ to $n$ appears exactly once in it. A cyclic shift of a permutation $(p_1, p_2, \ldots, p_n)$ is a permutation $(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$ for some $i$ from $1$ to $n$. For example, a permutation $(2, 1, 3)$ has three distinct cyclic shifts: $(2, 1, 3)$, $(1, 3, 2)$, $(3, 2, 1)$. A subsequence of a subsegment of array $a$ from the $l$-th to the $r$-th positions, inclusive, is a sequence $a_{i_1}, a_{i_2}, \ldots, a_{i_k}$ for some $i_1, i_2, \ldots, i_k$ such that $l \leq i_1 < i_2 < \ldots < i_k \leq r$. -----Input----- The first line contains three integers $n$, $m$, $q$ ($1 \le n, m, q \le 2 \cdot 10^5$) — the length of the permutation $p$, the length of the array $a$ and the number of queries. The next line contains $n$ integers from $1$ to $n$, where the $i$-th of them is the $i$-th element of the permutation. Each integer from $1$ to $n$ appears exactly once. The next line contains $m$ integers from $1$ to $n$, the $i$-th of them is the $i$-th element of the array $a$. The next $q$ lines describe queries. The $i$-th of these lines contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le m$), meaning that the $i$-th query is about the subsegment of the array from the $l_i$-th to the $r_i$-th positions, inclusive. -----Output----- Print a single string of length $q$, consisting of $0$ and $1$, the digit on the $i$-th positions should be $1$, if the subsegment of array $a$ from the $l_i$-th to the $r_i$-th positions, inclusive, contains a subsequence that is a cyclic shift of $p$, and $0$ otherwise. -----Examples----- Input 3 6 3 2 1 3 1 2 3 1 2 3 1 5 2 6 3 5 Output 110 Input 2 4 3 2 1 1 1 2 2 1 2 2 3 3 4 Output 010 -----Note----- In the first example the segment from the $1$-st to the $5$-th positions is $1, 2, 3, 1, 2$. There is a subsequence $1, 3, 2$ that is a cyclic shift of the permutation. The subsegment from the $2$-nd to the $6$-th positions also contains a subsequence $2, 1, 3$ that is equal to the permutation. The subsegment from the $3$-rd to the $5$-th positions is $3, 1, 2$, there is only one subsequence of length $3$ ($3, 1, 2$), but it is not a cyclic shift of the permutation. In the second example the possible cyclic shifts are $1, 2$ and $2, 1$. The subsegment from the $1$-st to the $2$-nd positions is $1, 1$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $2$-nd to the $3$-rd positions is $1, 2$, it coincides with the permutation. The subsegment from the $3$ to the $4$ positions is $2, 2$, its subsequences are not cyclic shifts of the permutation. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys inp = [int(x) for x in sys.stdin.read().split()] n, m, q = inp[0], inp[1], inp[2] p = [inp[idx] for idx in range(3, n + 3)] index_arr = [0] * (n + 1) for i in range(n): index_arr[p[i]] = i a = [inp[idx] for idx in range(n + 3, n + 3 + m)] leftmost_pos = [m] * (n + 1) next = [-1] * m for i in range(m - 1, -1, -1): index = index_arr[a[i]] right_index = 0 if index == n - 1 else index + 1 right = p[right_index] next[i] = leftmost_pos[right] leftmost_pos[a[i]] = i log = 0 while (1 << log) <= n: log += 1 log += 1 dp = [[m for _ in range(m + 1)] for _ in range(log)] for i in range(m): dp[0][i] = next[i] for j in range(1, log): for i in range(m): dp[j][i] = dp[j - 1][dp[j - 1][i]] last = [0] * m for i in range(m): p = i len = n - 1 for j in range(log - 1, -1, -1): if (1 << j) <= len: p = dp[j][p] len -= (1 << j) last[i] = p for i in range(m - 2, -1, -1): last[i] = min(last[i], last[i + 1]) inp_idx = n + m + 3 ans = [] for i in range(q): l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1 inp_idx += 2 if last[l] <= r: ans.append('1') else: ans.append('0') print(''.join(ans)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column. Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j]. There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout. If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs. -----Input----- The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 10^5). -----Output----- The output contains a single number — the maximum total gain possible. -----Examples----- Input 3 3 100 100 100 100 1 100 100 100 100 Output 800 -----Note----- Iahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3]. 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())) aa = [] for _ in range(n): row = list(map(int, input().split())) row.append(0) aa.append(row) aa.append([0] * (m + 1)) d1, d2, d3, d4 = ([[0] * (m + 1) for _ in range(n + 1)] for _ in (1, 2, 3, 4)) for i in range(n): for j in range(m): d1[i][j] = max(d1[i - 1][j], d1[i][j - 1]) + aa[i][j] for i in range(n): for j in range(m - 1, -1, -1): d2[i][j] = max(d2[i - 1][j], d2[i][j + 1]) + aa[i][j] for i in range(n - 1, -1, -1): for j in range(m): d3[i][j] = max(d3[i + 1][j], d3[i][j - 1]) + aa[i][j] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): d4[i][j] = max(d4[i + 1][j], d4[i][j + 1]) + aa[i][j] print((max( max(d1[i][j - 1] + d2[i - 1][j] + d3[i + 1][j] + d4[i][j + 1] for i in range(1, n - 1) for j in range(1, m - 1)), max(d1[i - 1][j] + d2[i][j + 1] + d3[i][j - 1] + d4[i + 1][j] for i in range(1, n - 1) for j in range(1, m - 1))))) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange. Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let $f(l,r)$ be the longest contiguous sequence of apples in the substring $s_{l}s_{l+1}\ldots s_{r}$. Help Zookeeper find $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$, or the sum of $f$ across all substrings. -----Input----- The first line contains a single integer $n$ $(1 \leq n \leq 5 \cdot 10^5)$. The next line contains a binary string $s$ of length $n$ $(s_i \in \{0,1\})$ -----Output----- Print a single integer: $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$. -----Examples----- Input 4 0110 Output 12 Input 7 1101001 Output 30 Input 12 011100011100 Output 156 -----Note----- In the first test, there are ten substrings. The list of them (we let $[l,r]$ be the substring $s_l s_{l+1} \ldots s_r$): $[1,1]$: 0 $[1,2]$: 01 $[1,3]$: 011 $[1,4]$: 0110 $[2,2]$: 1 $[2,3]$: 11 $[2,4]$: 110 $[3,3]$: 1 $[3,4]$: 10 $[4,4]$: 0 The lengths of the longest contiguous sequence of ones in each of these ten substrings are $0,1,2,2,1,2,2,1,1,0$ respectively. Hence, the answer is $0+1+2+2+1+2+2+1+1+0 = 12$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(list(range(_size))): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) n = int(input()) s = input() pref = [] curr = 0 for c in s: if c == '1': curr += 1 else: curr = 0 pref.append(curr) suff = [] curr = 0 for c in s[::-1]: if c == '1': curr += 1 else: curr = 0 suff.append(curr) suff.reverse() st = SegmentTree(suff) out = 0 add = 0 for i in range(n): if s[i] == '1': lo = -1 hi = i - pref[i] + 1 while hi - lo > 1: t = (lo + hi) // 2 if st.query(t, i - pref[i] + 1) >= pref[i]: lo = t else: hi = t add += (i - lo) #print(add) out += add print(out) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: As we all know, Chef is cooking string for long days, his new discovery on string is the longest common pattern length. The longest common pattern length between two strings is the maximum number of characters that both strings have in common. Characters are case sensitive, that is, lower case and upper case characters are considered as different. Note that characters can repeat in a string and a character might have one or more occurrence in common between two strings. For example, if Chef has two strings A = "Codechef" and B = "elfedcc", then the longest common pattern length of A and B is 5 (common characters are c, d, e, e, f). Chef wants to test you with the problem described above. He will give you two strings of Latin alphabets and digits, return him the longest common pattern length. -----Input----- The first line of the input contains an integer T, denoting the number of test cases. Then the description of T test cases follows. The first line of each test case contains a string A. The next line contains another character string B. -----Output----- For each test case, output a single line containing a single integer, the longest common pattern length between A and B. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ |A|, |B| ≤ 10000 (104), where |S| denotes the length of the string S - Both of A and B can contain only alphabet characters (both lower and upper case) and digits -----Example----- Input: 4 abcd xyz abcd bcda aabc acaa Codechef elfedcc Output: 0 4 3 5 -----Explanation----- Example case 1. There is no common character. Example case 2. All the characters are same. Example case 3. Three characters (a, a and c) are same. Example case 4. This sample is mentioned by the statement. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import Counter def solve(A,B): a = Counter(A) b = Counter(B) ans = 0 for i in a: if i in b: ans += min(a[i],b[i]) return ans t = int(input()) for _ in range(t): A = input() B = input() print(solve(A,B)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Codefortia is a small island country located somewhere in the West Pacific. It consists of $n$ settlements connected by $m$ bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to $a$ or $b$ seconds. It's guaranteed that one can go between any pair of settlements by following a sequence of roads. Codefortia was recently struck by the financial crisis. Therefore, the king decided to abandon some of the roads so that: it will be possible to travel between each pair of cities using the remaining roads only, the sum of times required to pass each remaining road will be minimum possible (in other words, remaining roads must form minimum spanning tree, using the time to pass the road as its weight), among all the plans minimizing the sum of times above, the time required to travel between the king's residence (in settlement $1$) and the parliament house (in settlement $p$) using the remaining roads only will be minimum possible. The king, however, forgot where the parliament house was. For each settlement $p = 1, 2, \dots, n$, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement $p$) after some roads are abandoned? -----Input----- The first line of the input contains four integers $n$, $m$, $a$ and $b$ ($2 \leq n \leq 70$, $n - 1 \leq m \leq 200$, $1 \leq a < b \leq 10^7$) — the number of settlements and gravel roads in Codefortia, and two possible travel times. Each of the following lines contains three integers $u, v, c$ ($1 \leq u, v \leq n$, $u \neq v$, $c \in \{a, b\}$) denoting a single gravel road between the settlements $u$ and $v$, which requires $c$ minutes to travel. You can assume that the road network is connected and has no loops or multiedges. -----Output----- Output a single line containing $n$ integers. The $p$-th of them should denote the minimum possible time required to travel from $1$ to $p$ after the selected roads are abandoned. Note that for each $p$ you can abandon a different set of roads. -----Examples----- Input 5 5 20 25 1 2 25 2 3 25 3 4 20 4 5 20 5 1 20 Output 0 25 60 40 20 Input 6 7 13 22 1 2 13 2 3 13 1 4 22 3 4 13 4 5 13 5 6 13 6 1 13 Output 0 13 26 39 26 13 -----Note----- The minimum possible sum of times required to pass each road in the first example is $85$ — exactly one of the roads with passing time $25$ must be abandoned. Note that after one of these roads is abandoned, it's now impossible to travel between settlements $1$ and $3$ in time $50$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import heapq n,m,a,b=map(int,input().split()) graph={i:[] for i in range(n)} for i in range(m): u,v,w=map(int,input().split()) graph[u-1].append((v-1,w)) graph[v-1].append((u-1,w)) components=[-1]*n comp=-1 for i in range(n): if components[i]==-1: comp+=1 components[i]=comp prev=[] layer=[i] while layer!=[]: newlayer=[] for guy in layer: for guy1 in graph[guy]: if guy1[1]==a and components[guy1[0]]==-1: newlayer.append(guy1[0]) components[guy1[0]]=comp prev=layer[:] layer=newlayer[:] useless=[] for guy in graph: for neigh in graph[guy]: if components[guy]==components[neigh[0]] and neigh[1]==b: useless.append((guy,neigh)) for guy in useless: graph[guy[0]].remove(guy[1]) counts=[0]*(comp+1) for i in range(n): counts[components[i]]+=1 bad=[] for i in range(comp+1): if counts[i]<=3: bad.append(i) for j in range(n): if components[j]==i: components[j]=-1 for guy in bad[::-1]: for i in range(n): if components[i]>guy: components[i]-=1 comp-=len(bad) comp+=1 dists=[[float("inf") for i in range(2**comp)] for j in range(n)] dists[0][0]=0 pq=[] heapq.heappush(pq,[0,0,0]) remaining=n visited=[0]*n while len(pq)>0 and remaining>0: dist,vert,mask=heapq.heappop(pq) if visited[vert]==0: visited[vert]=1 remaining-=1 for neigh in graph[vert]: if neigh[1]==b: if components[vert]==components[neigh[0]] and components[vert]!=-1: continue if components[neigh[0]]!=-1: if mask & (2**components[neigh[0]])>0: continue if components[vert]!=-1: maskn=mask+2**(components[vert]) else: maskn=mask else: maskn=mask if dist+neigh[1]<dists[neigh[0]][maskn]: dists[neigh[0]][maskn]=dist+neigh[1] heapq.heappush(pq,[dist+neigh[1],neigh[0],maskn]) optimal=[str(min(dists[i])) for i in range(n)] print(" ".join(optimal)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A repetition-free number is one in which each digit $\{1,2,3,…,9\}$ appears at most once and the digit $0$ does not appear. A repetition-free number can have at most nine digits, but may also have fewer than nine digits. Some examples of repetition-free numbers are $9, 32, 489, 98761$ and $983245$. You will be given an integer $N$ with at most nine digits. Your task is to print out the smallest repetition-free number bigger than $N$. For example, for $99$ the answer is $123$, for $881$ the answer is $891$, and for $133$ the answer is $134$. -----Input:----- A single line with a single integer with at most $9$ digits. -----Output:----- A single line containing the smallest repetition-free number bigger than the given number. If there is no repetition-free number bigger than the given number, print $0$. -----Constraints:----- - $N$ consists of atmost $9$ digits -----Sample input----- 99 -----Sample output----- 123 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()) i = N + 1 flag = 0 for i in range(N+1, 987654321): a = str(i) b = list(a) c = set(a) if '0' not in b: if len(b) == len(c): print(i) flag += 1 break if flag < 1: print(0) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Gray code (see wikipedia for more details) is a well-known concept. One of its important properties is that every two adjacent numbers have exactly one different digit in their binary representation. In this problem, we will give you n non-negative integers in a sequence A[1..n] (0<=A[i]<2^64), such that every two adjacent integers have exactly one different digit in their binary representation, similar to the Gray code. Your task is to check whether there exist 4 numbers A[i1], A[i2], A[i3], A[i4] (1 <= i1 < i2 < i3 < i4 <= n) out of the given n numbers such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Here xor is a bitwise operation which is same as ^ in C, C++, Java and xor in Pascal. -----Input----- First line contains one integer n (4<=n<=100000). Second line contains n space seperated non-negative integers denoting the sequence A. -----Output----- Output “Yes” (quotes exclusive) if there exist four distinct indices i1, i2, i3, i4 such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Otherwise, output "No" (quotes exclusive) please. -----Example----- Input: 5 1 0 2 3 7 Output: Yes The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python dic = {} #num = "1" #def tonum(num): # res=0 # for i in range(len(num)): # res = 2*res + int(num[i]) # return res #for i in range(64): # number = tonum(num) # dic[num] = [] # num = num+"0" n = int(input()) flag=0 if n >= 68: inp = input() print("Yes") else: inp = [int(x) for x in input().split()] for i in range(len(inp)-1): for j in range(i+1,len(inp)): xor = inp[i]^inp[j] if xor in list(dic.keys()): for pair in dic[xor]: (x,y) = pair if x != i and y!=j and x!=j and y!=i: flag = 1 break dic[xor].append((i,j)) else: dic[xor] = [] dic[xor].append((i,j)) if flag is 1: break if flag is 1: break if flag is 1: print("Yes") else: print("No") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is very expert in coding, so to keep his password safe from the hackers. He always enters a decoded code of his password. You are a hacker and your work is to find the maximum number of possible ways to unlock his password in encoded form. The encoded message containing only letters from A-Z is being encoded with numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 You have given a non-empty string containing only digits, determine the total number of ways to encode it. If the total number of ways are even then you are able to unlock the password. Input: The first line has a single integer T, denoting the number of test cases. The first line of each test case contains string “S” decoded number. Output: For each test case, in a new line, print 'YES' if number of maximum ways are even, otherwise 'NO'. (without quotes) Constraints: 1 ≤ T ≤ 50 1 ≤ S ≤ 30 Sample Input: 2 12 223 Sample Output: YES NO Explanation: For first test case, It could be encoded as "AB" (1 2) or "L" (12), hence the number of maximum possible ways are 2 so output is “YES”. 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: s = input().strip() if not s: print('NO') dp = [0 for x in range(len(s) + 1)] dp[0] = 1 dp[1] = 1 if 0 < int(s[0]) <= 9 else 0 for i in range(2, len(s) + 1): if 0 < int(s[i-1:i]) <= 9: dp[i] += dp[i - 1] if s[i-2:i][0] != '0' and int(s[i-2:i]) <= 26: dp[i] += dp[i - 2] if dp[len(s)]%2 == 0: print('YES') else: print('NO') t -= 1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Indian National Olympiad in Informatics 2016 Boing Inc, has N employees, numbered 1 ... N. Every employee other than Mr. Hojo (the head of the company) has a manager (P[i] denotes the manager of employee i). Thus an employee may manage any number of other employees but he reports only to one manager, so that the organization forms a tree with Mr. Hojo at the root. We say that employee B is a subordinate of employee A if B appears in the subtree rooted at A. Mr. Hojo, has hired Nikhil to analyze data about the employees to suggest how to identify faults in Boing Inc. Nikhil, who is just a clueless consultant, has decided to examine wealth disparity in the company. He has with him the net wealth of every employee (denoted A[i] for employee i). Note that this can be negative if the employee is in debt. He has already decided that he will present evidence that wealth falls rapidly as one goes down the organizational tree. He plans to identify a pair of employees i and j, j a subordinate of i, such A[i] - A[j] is maximum. Your task is to help him do this. Suppose, Boing Inc has 4 employees and the parent (P[i]) and wealth information (A[i]) for each employee are as follows: i 1 2 3 4 A[i] 5 10 6 12 P[i] 2 -1 4 2 P[2] = -1 indicates that employee 2 has no manager, so employee 2 is Mr. Hojo. In this case, the possible choices to consider are (2,1) with a difference in wealth of 5, (2,3) with 4, (2,4) with -2 and (4,3) with 6. So the answer is 6. -----Input format----- There will be one line which contains (2*N + 1) space-separate integers. The first integer is N, giving the number of employees in the company. The next N integers A[1], .., A[N] give the wealth of the N employees. The last N integers are P[1], P[2], .., P[N], where P[i] identifies the manager of employee i. If Mr. Hojo is employee i then, P[i] = -1, indicating that he has no manager. -----Output format----- One integer, which is the needed answer. -----Test data----- -108 ≤ A[i] ≤ 108, for all i. Subtask 1 (30 Marks) 1 ≤ N ≤ 500. Subtask 2 (70 Marks) 1 ≤ N ≤ 105. -----Sample Input----- 4 5 10 6 12 2 -1 4 2 -----Sample Output----- 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 from collections import defaultdict input = sys.stdin.readline sys.setrecursionlimit(1000000) arr=[int(x) for x in input().split()] if arr[0]==1: print(0) return p=[None] for i in range(1,arr[0]+1): p.append(arr[i]) a=[None] for i in range(arr[0]+1,2*arr[0]+1): a.append(arr[i]) graph=defaultdict(list) n=len(a)-1 for i in range(1,n+1): if a[i]==-1: source=i continue graph[a[i]].append((i,(p[a[i]]-p[i]))) def func(node): nonlocal res if len(graph[node])==0: return -10**9 curr=-10**9 for child in graph[node]: x=max(child[1],(func(child[0])+child[1])) curr=max(curr,x) res=max(curr,res) return curr res=-10**9 curr=func(source) print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Problem description. Dominic Toretto has taken his crew to compete in this years' Race Wars, a crew-on-crew tournament in which each member of one crew competes with a member of the other crew in a quarter mile drag race. Each win counts as one point for the winning crew. Draws and loses are awarded zero points. In the end the crew with more points is declared the winner of that round and can advance while the losing crew is knocked out. One member can compete in only one race per round and all crews have the same number of members. Dom and his crew have a reputation of being the best and naturally everyone expects them to win this year as well. However, during the tournament he spots a new crew of racers who are participating for the first time in this event. People expect them to be a dark horse so naturally Dom wants to keep an eye on their performance. Being the experienced racer that he is, Dom has figured out the time in which each racer of the opposing crew completes his quarter mile race. He also knows his own crew inside out and can estimate with absolute certainty, the time it would take each of his members to complete the race. Dominic is the reigning champion and thus has an advantage that he can select the order of the matches i.e.: he can select which member of his crew will go up against which member of the opposition. Given this data he wants to figure out the number of races he will win should his crew come face to face with their newest rivals. Unfortunately he is a racer and not a problem solver so he comes to you for help. Given the time each member of the two crews take to complete the race you have to figure out a way to arrange the matches so that Dominic can win maximum points possible for him. -----Input----- The first line of input is the T, the number of test cases. Each test case starts with a single number N, the number of racers on each crew. This is followed by two lines, each having N space separated integers containing the time taken by each member of Dominic's crew and the rival crew respectively. -----Output----- Output a single integer. The maximum number of points that Dominic can get. -----Constraints----- 1<=T<=100 1<=N<=100 Time taken by each member will be between 1 and 500 -----Example----- Input: 1 3 5 4 1 5 4 1 Output: 2 -----Explanation----- If Dom selects Racer 1 of his team to go against Racer 2 of the other team, Racer 2 of his team against Racer 3 of the other team and Racer 3 of his team against Racer 1 of the other team then he ends up with two wins and a loss which gives him 2 points. ... The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python testcases = int(input()) for i in range(testcases): n = int(input()) my = list(map(int,input().split())) opp = list(map(int,input().split())) my.sort(reverse = True) opp.sort(reverse = True) j = 0 k = 0 while(k < n): if(my[j] > opp[k]): j += 1 k += 1 print(j) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Andre has very specific tastes. Recently he started falling in love with arrays. Andre calls an nonempty array $b$ good, if sum of its elements is divisible by the length of this array. For example, array $[2, 3, 1]$ is good, as sum of its elements — $6$ — is divisible by $3$, but array $[1, 1, 2, 3]$ isn't good, as $7$ isn't divisible by $4$. Andre calls an array $a$ of length $n$ perfect if the following conditions hold: Every nonempty subarray of this array is good. For every $i$ ($1 \le i \le n$), $1 \leq a_i \leq 100$. Given a positive integer $n$, output any perfect array of length $n$. We can show that for the given constraints such an array always exists. An array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows. The first and only line of every test case contains a single integer $n$ ($1 \le n \le 100$). -----Output----- For every test, output any perfect array of length $n$ on a separate line. -----Example----- Input 3 1 2 4 Output 24 19 33 7 37 79 49 -----Note----- Array $[19, 33]$ is perfect as all $3$ its subarrays: $[19]$, $[33]$, $[19, 33]$, have sums divisible by their lengths, and therefore are good. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if True else 1): n = int(input()) #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) #s = input() print(*[1]*n) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let X be the set of all integers between 0 and n-1. Suppose we have a collection S1, S2, ..., Sm of subsets of X. Say an atom A is a subset of X such that for each Si we have either A is a subset of Si or A and Si do not have any common elements. Your task is to find a collection A1, ..., Ak of atoms such that every item in X is in some Ai and no two Ai, Aj with i ≠ j share a common item. Surely such a collection exists as we could create a single set {x} for each x in X. A more interesting question is to minimize k, the number of atoms. -----Input----- The first line contains a single positive integer t ≤ 30 indicating the number of test cases. Each test case begins with two integers n,m where n is the size of X and m is the number of sets Si. Then m lines follow where the i'th such line begins with an integer vi between 1 and n (inclusive) indicating the size of Si. Following this are vi distinct integers between 0 and n-1 that describe the contents of Si. You are guaranteed that 1 ≤ n ≤ 100 and 1 ≤ m ≤ 30. Furthermore, each number between 0 and n-1 will appear in at least one set Si. -----Output----- For each test case you are to output a single integer indicating the minimum number of atoms that X can be partitioned into to satisfy the constraints. -----Example----- Input: 2 5 2 3 0 1 2 3 2 3 4 4 3 2 0 1 2 1 2 2 2 3 Output: 3 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 # cook your dish here for _ in range(int(input())): n,m=list(map(int,input().split())) atomlist = ['']*n for k in range(m): s=[] s.extend(input().split()[1:]) #print(s) for w in range(n): if str(w) in s: atomlist[w]+="1" else: atomlist[w]+="0" #print(atomlist) print(len(set(atomlist))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today, Chef decided to cook some delicious meals from the ingredients in his kitchen. There are $N$ ingredients, represented by strings $S_1, S_2, \ldots, S_N$. Chef took all the ingredients, put them into a cauldron and mixed them up. In the cauldron, the letters of the strings representing the ingredients completely mixed, so each letter appears in the cauldron as many times as it appeared in all the strings in total; now, any number of times, Chef can take one letter out of the cauldron (if this letter appears in the cauldron multiple times, it can be taken out that many times) and use it in a meal. A complete meal is the string "codechef". Help Chef find the maximum number of complete meals he can make! -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains a single string $S_i$. -----Output----- For each test case, print a single line containing one integer — the maximum number of complete meals Chef can create. -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 100$ - $|S_1| + |S_2| + \ldots + |S_N| \le 1,000$ - each string contains only lowercase English letters -----Example Input----- 3 6 cplusplus oscar deck fee hat near 5 code hacker chef chaby dumbofe 5 codechef chefcode fehcedoc cceeohfd codechef -----Example Output----- 1 2 5 -----Explanation----- Example case 1: After mixing, the cauldron contains the letter 'c' 3 times, the letter 'e' 4 times, and each of the letters 'o', 'd', 'h' and 'f' once. Clearly, this is only enough for one "codechef" meal. Example case 2: After mixing, the cauldron contains the letter 'c' 4 times, 'o' 2 times, 'd' 2 times, 'e' 4 times, 'h' 3 times and 'f' 2 times, which is enough to make 2 meals. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t=int(input()) while t>0: n=int(input()) li=[] c,o,d,e,h,f=0,0,0,0,0,0 for i in range(0,n): s=input() for i in range(len(s)): if s[i]=='c': c=c+1 elif s[i]=='o': o=o+1 elif s[i]=='d': d=d+1 elif s[i]=='e': e=e+1 elif s[i]=='h': h=h+1 elif s[i]=='f': f=f+1 e=e//2 c=c//2 print(min(c,o,d,e,h,f)) t-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \dots r]$. The characters of each string are numbered from $1$. We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011. Binary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., every string is reachable from itself. You are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$. -----Input----- The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of string $t$. The second line contains one string $t$ ($|t| = n$). Each character of $t$ is either 0 or 1. The third line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries. Then $q$ lines follow, each line represents a query. The $i$-th line contains three integers $l_1$, $l_2$ and $len$ ($1 \le l_1, l_2 \le |t|$, $1 \le len \le |t| - \max(l_1, l_2) + 1$) for the $i$-th query. -----Output----- For each query, print either YES if $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$, or NO otherwise. You may print each letter in any register. -----Example----- Input 5 11011 3 1 3 3 1 4 2 1 2 3 Output Yes Yes No 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 MOD = 987654103 n = int(input()) t = input() place = [] f1 = [] e1 = [] s = [] curr = 0 count1 = 0 for i in range(n): c = t[i] if c == '0': if count1: e1.append(i - 1) if count1 & 1: s.append(1) curr += 1 e1.append(-1) f1.append(-1) count1 = 0 else: f1.append(-1) e1.append(-1) place.append(curr) curr += 1 s.append(0) else: if count1 == 0: f1.append(i) count1 += 1 place.append(curr) if count1: if count1 & 1: s.append(1) else: s.append(0) curr += 1 e1.append(n - 1) e1.append(-1) f1.append(-1) place.append(curr) pref = [0] val = 0 for i in s: val *= 3 val += i + 1 val %= MOD pref.append(val) q = int(input()) out = [] for _ in range(q): l1, l2, leng = list(map(int, input().split())) l1 -= 1 l2 -= 1 starts = (l1, l2) hashes = [] for start in starts: end = start + leng - 1 smap = place[start] emap = place[end] if t[end] == '1': emap -= 1 if s[smap] == 1: smap += 1 prep = False app = False if t[start] == '1': last = e1[place[start]] last = min(last, end) count = last - start + 1 if count % 2: prep = True if t[end] == '1': first = f1[place[end]] first = max(first, start) count = end - first + 1 if count % 2: app = True preHash = 0 length = 0 if smap <= emap: length = emap - smap + 1 preHash = pref[emap + 1] preHash -= pref[smap] * pow(3, emap - smap + 1, MOD) preHash %= MOD if length == 0 and prep and app: app = False #print(preHash, prep, app, length) if prep: preHash += pow(3, length, MOD) * 2 length += 1 if app: preHash *= 3 preHash += 2 #print(preHash) preHash %= MOD hashes.append(preHash) if hashes[0] == hashes[1]: out.append('Yes') else: out.append('No') print('\n'.join(out)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t). He can move in arbitrary directions with speed 1. Here, we will consider him as a point without size. There are N circular barriers deployed on the plane. The center and the radius of the i-th barrier are (x_i, y_i) and r_i, respectively. The barriers may overlap or contain each other. A point on the plane is exposed to cosmic rays if the point is not within any of the barriers. Snuke wants to avoid exposure to cosmic rays as much as possible during the travel. Find the minimum possible duration of time he is exposed to cosmic rays during the travel. -----Constraints----- - All input values are integers. - -10^9 ≤ x_s, y_s, x_t, y_t ≤ 10^9 - (x_s, y_s) ≠ (x_t, y_t) - 1≤N≤1,000 - -10^9 ≤ x_i, y_i ≤ 10^9 - 1 ≤ r_i ≤ 10^9 -----Input----- The input is given from Standard Input in the following format: x_s y_s x_t y_t N x_1 y_1 r_1 x_2 y_2 r_2 : x_N y_N r_N -----Output----- Print the minimum possible duration of time Snuke is exposed to cosmic rays during the travel. The output is considered correct if the absolute or relative error is at most 10^{-9}. -----Sample Input----- -2 -2 2 2 1 0 0 1 -----Sample Output----- 3.6568542495 An optimal route is as follows: The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): import sys input = sys.stdin.readline import heapq def dijkstra_heap(s,g,edge): #始点sから各頂点への最短距離 d = [10**20] * (n+2) used = [True] * (n+2) #True:未確定 d[s] = 0 used[s] = False edgelist = [] sx,sy,sr=edge[s][0],edge[s][1],edge[s][2] for i in range(n+2): x,y,r=edge[i][0],edge[i][1],edge[i][2] dist=((x-sx)**2+(y-sy)**2)**(1/2) heapq.heappush(edgelist,(max(dist-r-sr,0),i)) while len(edgelist): minedge = heapq.heappop(edgelist) #まだ使われてない頂点の中から最小の距離のものを探す v = minedge[1] if not used[v]: continue d[v] = minedge[0] used[v] = False bx,by,br=edge[v][0],edge[v][1],edge[v][2] for i in range(n+2): x,y,r=edge[i][0],edge[i][1],edge[i][2] dist=((x-bx)**2+(y-by)**2)**(1/2) if used[i]: heapq.heappush(edgelist,(max(dist-r-br,0)+d[v],i)) if not used[g]: break return d[g] sx,sy,gx,gy = map(int,input().split()) #n:頂点数 w:辺の数 n=int(input()) edge=[(sx,sy,0),(gx,gy,0)] for i in range(2,n+2): x,y,r=map(int,input().split()) edge.append((x,y,r)) print(dijkstra_heap(0,1,edge)) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Screen resolution of Polycarp's monitor is $a \times b$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $(x, y)$ ($0 \le x < a, 0 \le y < b$). You can consider columns of pixels to be numbered from $0$ to $a-1$, and rows — from $0$ to $b-1$. Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen. Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself. -----Input----- In the first line you are given an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the test. In the next lines you are given descriptions of $t$ test cases. Each test case contains a single line which consists of $4$ integers $a, b, x$ and $y$ ($1 \le a, b \le 10^4$; $0 \le x < a$; $0 \le y < b$) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $a+b>2$ (e.g. $a=b=1$ is impossible). -----Output----- Print $t$ integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel. -----Example----- Input 6 8 8 0 0 1 10 0 3 17 31 10 4 2 1 0 0 5 10 3 9 10 10 4 8 Output 56 6 442 1 45 80 -----Note----- In the first test case, the screen resolution is $8 \times 8$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. [Image] 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 * zzz = int(input()) for zz in range(zzz): a, b, x, y = list(map(int, input().split())) print(max(x*b, (a-x-1)*b, y*a, (b - y - 1)*a)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an array A with size N (indexed from 0) and an integer K. Let's define another array B with size N · K as the array that's formed by concatenating K copies of array A. For example, if A = {1, 2} and K = 3, then B = {1, 2, 1, 2, 1, 2}. You have to find the maximum subarray sum of the array B. Fomally, you should compute the maximum value of Bi + Bi+1 + Bi+2 + ... + Bj, where 0 ≤ i ≤ j < N · K. -----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 A0, A1, ..., AN-1. -----Output----- For each test case, print a single line containing the maximum subarray sum of B. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 105 - 1 ≤ K ≤ 105 - -106 ≤ Ai ≤ 106 for each valid i -----Subtasks----- Subtask #1 (18 points): N · K ≤ 105 Subtask #2 (82 points): original constraints -----Example----- Input: 2 2 3 1 2 3 2 1 -2 1 Output: 9 2 -----Explanation----- Example case 1: B = {1, 2, 1, 2, 1, 2} and the subarray with maximum sum is the whole {1, 2, 1, 2, 1, 2}. Hence, the answer is 9. Example case 2: B = {1, -2, 1, 1, -2, 1} and the subarray with maximum sum is {1, 1}. Hence, the answer is 2. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def max_sum(arr): # Finds the maximum sum of sub-arrays of arr max_till_now = -1000000 #minimum possible number current_sum = 0 for i in range(len(arr)): if current_sum < 0: # If sum of previous elements is negative, then ignore them. Start fresh # with `current_sum = 0` current_sum = 0 current_sum += arr[i] # Update max if max_till_now < current_sum: max_till_now = current_sum return max_till_now def solve(A, k): if k == 1: return max_sum(A) # Find sum of elements of A sum_A = 0 for i in range(len(A)): sum_A += A[i] Max_Suffix_Sum = -1000000 current = 0 for i in range(len(A)): current += A[-i-1] if current > Max_Suffix_Sum: Max_Suffix_Sum = current Max_Prefix_Sum = -1000000 current = 0 for i in range(len(A)): current += A[i] if current > Max_Prefix_Sum: Max_Prefix_Sum = current if sum_A <= 0: # Check two cases: # Case 1 : Check the max_sum of A case_1_max_sum = max_sum(A) # Case 2 : Check the max_sum of A + A case_2_max_sum = Max_Suffix_Sum + Max_Prefix_Sum # Return the maximum of the two cases return max([case_1_max_sum, case_2_max_sum]) else: # if sum_A > 0 #Check two cases: # Case 1 : Check the max_sum of A case_1_max_sum = max_sum(A) # Case 2 # Max sum = Max_Suffix_Sum + (k - 2)*sum_A + Max_Prefix_Sum case_2_max_sum = Max_Suffix_Sum + (k - 2)*sum_A + Max_Prefix_Sum # Return the maximum of the two cases return max([case_1_max_sum, case_2_max_sum]) # Main T = int(input()) # No of test cases for i in range(T): [N, k] = list(map(int, input().split(" "))) A = list(map(int, input().split(" "))) answer = solve(A,k) print(answer) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a field with plants — a grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$); out of its $NM$ cells, $K$ cells contain plants, while the rest contain weeds. Two cells are adjacent if they have a common side. You want to build fences in the field in such a way that the following conditions hold for each cell that contains a plant: - it is possible to move from this cell to each adjacent cell containing a plant without crossing any fences - it is impossible to move from this cell to any cell containing weeds or to leave the grid without crossing any fences The fences can only be built between cells or on the boundary of the grid, i.e. on the sides of cells. The total length of the built fences is the number of pairs of side-adjacent cells such that there is a fence built on their common side plus the number of sides of cells on the boundary of the grid which have fences built on them. Find the minimum required total length of fences that need to be built. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains three space-separated integers $N$, $M$ and $K$. - $K$ lines follow. Each of these lines contains two space-separated integers $r$ and $c$ denoting that the cell in row $r$ and column $c$ contains a plant. -----Output----- For each test case, print a single line containing one integer — the minimum required length of fences. -----Constraints----- - $1 \le T \le 10$ - $1 \le N, M \le 10^9$ - $1 \le K \le 10^5$ - $1 \le r \le N$ - $1 \le c \le M$ - the cells containing plants are pairwise distinct -----Subtasks----- Subtask #1 (30 points): $1 \le N, M \le 1,000$ Subtask #2 (70 points): original constraints -----Example Input----- 2 4 4 9 1 4 2 1 2 2 2 3 3 1 3 3 4 1 4 2 4 3 4 4 1 1 1 -----Example Output----- 20 4 -----Explanation----- Example case 1: The field looks like this ('x' denotes a cell containing a plant, '.' denotes a cell containing weeds): ...x xxx. x.x. xxx. An optimal solution is to build fences around the topmost plant (with length $4$), around the remaining eight plants (with length $12$) and around the hole between them (with length $4$). The total length is $4+12+4 = 20$. 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-=1 d={} n,m,k=[int(x) for x in list(input().split())] sum=0 while(k): k-=1 x,y=[int(x) for x in list(input().split())] a=[-1,1,0,0] b=[0,0,-1,1] for i in range(4): if((x+a[i],y+b[i]) in d): sum-=1 else: sum+=1 d[(x,y)]=1 print(sum) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Scheme? - Too loudly said. Just a new idea. Now Chef is expanding his business. He wants to make some new restaurants in the big city of Lviv. To make his business competitive he should interest customers. Now he knows how. But don't tell anyone - it is a secret plan. Chef knows four national Ukrainian dishes - salo, borsch, varenyky and galushky. It is too few, of course, but enough for the beginning. Every day in his restaurant will be a dish of the day among these four ones. And dishes of the consecutive days must be different. To make the scheme more refined the dish of the first day and the dish of the last day must be different too. Now he wants his assistant to make schedule for some period. Chef suspects that there is more than one possible schedule. Hence he wants his assistant to prepare all possible plans so that he can choose the best one among them. He asks you for help. At first tell him how many such schedules exist. Since the answer can be large output it modulo 109 + 7, that is, you need to output the remainder of division of the actual answer by 109 + 7. -----Input----- The first line of the input contains an integer T, the number of test cases. Each of the following T lines contains a single integer N denoting the number of days for which the schedule should be made. -----Output----- For each test case output a single integer in a separate line, the answer for the corresponding test case. -----Constraints-----1 ≤ T ≤ 100 2 ≤ N ≤ 109 -----Example----- Input: 3 2 3 5 Output: 12 24 240 -----Explanation----- Case 1. For N = 2 days we have the following 12 schedules: First day Second day salo borsch salo varenyky salo galushky borsch salo borsch varenyky borsch galushky varenyky salo varenyky borsch varenyky galushky galushky salo galushky borsch galushky varenyky Case 2. For N = 3 we have the following 24 schedules: First daySecond dayThird day salo borsch varenyky salo borsch galushky salo varenyky borsch salo varenyky galushky salo galushky borsch salo galushky varenyky borsch salo varenyky borsch salo galushky borsch varenyky salo borsch varenyky galushky borsch galushky salo borsch galushky varenyky varenyky salo borsch varenyky salo galushky varenyky borsch salo varenyky borsch galushky varenyky galushky salo varenyky galushky borsch galushky salo borsch galushky salo varenyky galushky borsch salo galushky borsch varenyky galushky varenyky salo galushky varenyky borsch Case 3. Don't be afraid. This time we will not provide you with a table of 240 schedules. The only thing we want to mention here is that apart from the previous two cases schedules for other values of N can have equal dishes (and even must have for N > 4). For example the schedule (salo, borsch, salo, borsch) is a correct schedule for N = 4 while the schedule (varenyky, salo, galushky, verynky, salo) is a correct schedule for N = 5. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python r = 1000000007 t = int(input()) for i in range(t): n = int(input()) print(pow(3,n,r) + pow(-1,n)*3) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Three numbers A, B and C are the inputs. Write a program to find second largest among them. -----Input----- The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains three integers A, B and C. -----Output----- For each test case, display the second largest among A, B and C, in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A,B,C ≤ 1000000 -----Example----- Input 3 120 11 400 10213 312 10 10 3 450 Output 120 312 10 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here x=int(input()) for i in range(x): s=list(map(int,input().split())) s.sort() print(s[1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vanja and Miksi really like games. After playing one game for a long time, they decided to invent another game! In this game, they have a sequence $A_1, A_2, \dots, A_N$ and two numbers $Z_1$ and $Z_2$. The rules of the game are as follows: - The players take turns alternately, starting with Vanja. - There is an integer $S$; at the beginning, $S = 0$. - In each turn, the current player must choose an arbitrary element of $A$ and either add that number to $S$ or subtract it from $S$. Each element can be selected multiple times. - Afterwards, if $S = Z_1$ or $S = Z_2$, the current player (the player who made $S$ equal to $Z_1$ or $Z_2$) is the winner of the game. - If the game lasts for $10^{10}$ turns, Vanja and Miksi decide to declare it a tie. Can you help the boys determine the winner of the game? Please note that the game can end in a tie (if nobody can make $S = Z_1$ or $S = Z_2$ in the first $10^{10}$ moves). Both players play optimally, i.e. if there is a move which guarantees the current player's victory regardless of the other player's moves, the current player will make such a move. If the current player cannot win and there is a move which guarantees that the game will end in a tie, the current player will make such a move. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains three space-separated integers $N$, $Z_1$ and $Z_2$. - The second line contains $N$ space-separated integers $A_1, A_2, \dots, A_N$. -----Output----- - For each test case, print a single line containing one integer — the final result of the game: - $1$ if Vanja (the first player) has a winning strategy - $2$ if Miksi (the second player) has a winning strategy - $0$ if the game ends in a tie -----Constraints----- - $1 \le T \le 50$ - $1 \le N \le 50$ - $|Z_1|, |Z_2| \le 10^9$ - $|A_i| \le 10^9$ for each valid $i$ -----Subtasks----- Subtask #1 (25 points): $N = 2$ Subtask #2 (75 points): original constraints -----Example Input----- 3 2 6 4 -4 10 1 1 -1 2 2 0 7 3 4 -----Example Output----- 1 0 2 -----Explanation----- Example case 1: The first player can choose the value $A_1 = -4$, subtract it from $S = 0$ and obtain $S = - (-4) = 4 = Z_2$. The winner is the first player. Example case 2: It can be proven that neither player is able to reach $S = Z_1$ or $S = Z_2$. The result is a tie. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys from collections import defaultdict as dd from collections import deque from fractions import Fraction as f from copy import * from bisect import * from heapq import * from math import * from itertools import permutations def eprint(*args): print(*args, file=sys.stderr) zz=1 #sys.setrecursionlimit(10**6) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') def li(): return [int(xx) for xx in input().split()] def fli(): return [float(x) for x in input().split()] def comp(a,b): if(a>b): return 2 return 2 if a==b else 0 def gi(): return [xx for x in input().split()] def fi(): return int(input()) def swap(a,i,j): a[i],a[j]=a[j],a[i] def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) def gh(): sys.stdout.flush() def graph(n,m): for i in range(m): x,y=mi() a[x].append(y) a[y].append(x) def bo(i): return ord(i)-ord('a') t=fi() while t>0: t-=1 n,z1,z2=mi() d={} a=li() flag=0 for i in a: d[i]=1 d[-i]=1 if i==z1 or i==z2 or i==-z1 or i==-z2: flag=1 break if flag: print(1) continue for i in d: p=[i-z1,i-z2] c=1 for j in p: if j in d: c*=0 flag|=c print(0 if flag else 2) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (x_{i}, y_{i}). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes. At the moment 0, from the point (0, 0) the laser ray is released in the direction of point (1, 1). The ray travels with a speed of $\sqrt{2}$ meters per second. Thus, the ray will reach the point (1, 1) in exactly one second after the start. When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops. For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print - 1 for such sensors. -----Input----- The first line of the input contains three integers n, m and k (2 ≤ n, m ≤ 100 000, 1 ≤ k ≤ 100 000) — lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers x_{i} and y_{i} (1 ≤ x_{i} ≤ n - 1, 1 ≤ y_{i} ≤ m - 1) — coordinates of the sensors. It's guaranteed that no two sensors are located at the same point. -----Output----- Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or - 1 if this will never happen. -----Examples----- Input 3 3 4 1 1 1 2 2 1 2 2 Output 1 -1 -1 2 Input 3 4 6 1 1 2 1 1 2 2 2 1 3 2 3 Output 1 -1 -1 2 5 -1 Input 7 4 5 1 3 2 2 5 1 5 3 4 3 Output 13 2 9 5 -1 -----Note----- In the first sample, the ray will consequently pass through the points (0, 0), (1, 1), (2, 2), (3, 3). Thus, it will stop at the point (3, 3) after 3 seconds. [Image] In the second sample, the ray will consequently pass through the following points: (0, 0), (1, 1), (2, 2), (3, 3), (2, 4), (1, 3), (0, 2), (1, 1), (2, 0), (3, 1), (2, 2), (1, 3), (0, 4). The ray will stop at the point (0, 4) after 12 seconds. It will reflect at the points (3, 3), (2, 4), (0, 2), (2, 0) and (3, 1). [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m, k = list(map(int,input().split())) dm, dp = {}, {} vis = {} sensors = [] border = set() for el in [(0, m), (n, 0), (0, 0), (n, m)]: border.add(el) for _ in range(k): x, y = list(map(int, input().split())) if not (x - y) in dm: dm[x - y] = [] dm[x - y].append((x, y)) if not (x + y) in dp: dp[x + y] = [] dp[x + y].append((x, y)) vis[(x, y)] = -1 sensors.append((x,y)) x, y = 0, 0 time = 0 move = (1,1) while True: if move == (1,1): v = min(n - x, m - y) nxt = (x + v, y + v) if nxt[0] == n: move = (-1, 1) else: move = (1, -1) if (x - y) in dm: for sensor in dm[x - y]: if vis[sensor] == -1: #print('doing', sensor) vis[sensor] = time + sensor[0] - x time += v elif move == (-1,-1): v = min(x, y) nxt = (x - v, y - v) if nxt[0] == 0: move = (1, -1) else: move = (-1, 1) if (x - y) in dm: for sensor in dm[x - y]: if vis[sensor] == -1: #print('doing', sensor) vis[sensor] = time + x - sensor[0] time += v elif move == (-1,1): v = min(x, m - y) nxt = (x - v, y + v) if nxt[0] == 0: move = (1, 1) else: move = (-1, -1) if (x + y) in dp: for sensor in dp[x + y]: if vis[sensor] == -1: #print('doing', sensor) vis[sensor] = time + x - sensor[0] time += v else: v = min(n - x, y) nxt = (x + v, y - v) if nxt[0] == n: move = (-1, -1) else: move = (1, 1) if (x + y) in dp: for sensor in dp[x + y]: if vis[sensor] == -1: #print('doing', sensor) vis[sensor] = time + sensor[0] - x time += v if nxt in border: break else: border.add(nxt) x, y = nxt #print('bum', x, y) for i in range(k): #print(sensors[i]) print(vis[sensors[i]]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Write a program, which takes an integer N and if the number is less than 10 then display "Thanks for helping Chef!" otherwise print "-1". -----Input----- The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N. -----Output----- For each test case, output the given string or -1 depending on conditions, in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - -20 ≤ N ≤ 20 -----Example----- Input 3 1 12 -5 Output Thanks for helping Chef! -1 Thanks for helping Chef! The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for i in range(int(input())): x=int(input()) if x<10: print("Thanks for helping Chef!") else: print("-1") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $n$ carrots with lengths $a_1, a_2, a_3, \ldots, a_n$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $k$ rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into $k$ pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size $x$ is $x^2$. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. -----Input----- The first line contains two integers $n$ and $k$ $(1 \leq n \leq k \leq 10^5)$: the initial number of carrots and the number of rabbits. The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(1 \leq a_i \leq 10^6)$: lengths of carrots. It is guaranteed that the sum of $a_i$ is at least $k$. -----Output----- Output one integer: the minimum sum of time taken for rabbits to eat carrots. -----Examples----- Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 -----Note----- For the first test, the optimal sizes of carrots are $\{1,1,1,2,2,2\}$. The time taken is $1^2+1^2+1^2+2^2+2^2+2^2=15$ For the second test, the optimal sizes of carrots are $\{4,5,5,5\}$. The time taken is $4^2+5^2+5^2+5^2=91$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import heapq def sum_sqaure(a, k): q, r = divmod(a, k) return q**2 * (k-r) + (q+1)**2 * r def diff(a, k): return sum_sqaure(a, k+1) - sum_sqaure(a, k) n, k = map(int, input().split()) nums = list(map(int, input().split())) curr = sum(sum_sqaure(a, 1) for a in nums) Q = [(diff(a, 1), a, 1) for a in nums] heapq.heapify(Q) for __ in range(k - n): d, a, i = heapq.heappop(Q) curr += d heapq.heappush(Q, (diff(a, i+1), a, i+1)) print(curr) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Fennec and Snuke are playing a board game. On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree. Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored. Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell. More specifically, each player performs the following action in her/his turn: - Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black. - Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white. A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally. -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq a_i, b_i \leq N - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} -----Output----- If Fennec wins, print Fennec; if Snuke wins, print Snuke. -----Sample Input----- 7 3 6 1 2 3 1 7 4 5 7 1 4 -----Sample Output----- Fennec For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #!/usr/bin/env python3 import sys sys.setrecursionlimit(10 ** 6) def main(): n = int(input()) adj_list = [[] for i in range(n)] for i in range(n - 1): a1, b1 = list(map(int, sys.stdin.readline().split())) adj_list[a1 - 1].append(b1 - 1) adj_list[b1 - 1].append(a1 - 1) path = list(reversed(dfs(0, -1, adj_list, n))) assert len(path) >= 2 fpath = len(path) - len(path) // 2 cut = set(path[fpath - 1:fpath + 1]) f = dfs2(0, -1, adj_list, n, cut) s = dfs2(n - 1, -1, adj_list, n, cut) assert f + s == n print(("Fennec" if f > s else "Snuke")) def dfs(now, prev, adj_list, n): if now == n - 1: return [now] for next in adj_list[now]: if next == prev: continue p = dfs(next, now, adj_list, n) if p is not None: p.append(now) return p def dfs2(now, prev, adj_list, n, cut): size = 1 for next in adj_list[now]: if next == prev: continue if {now, next} == cut: continue s = dfs2(next, now, adj_list, n, cut) size += s return size def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: We have a board with an H \times W grid. Each square in the grid is painted in black or white. The square at the i-th row from the top and j-th column from the left is black if the j-th character in S_i is #, and white if that character is .. Snuke can perform the following operation on the grid any number of times: - Select a row or column in the grid, and invert the color of all the squares in that row or column (that is, black squares become white and vice versa). Then, Snuke draws a rectangle along grid lines. Here, all the squares contained in the rectangle must be painted in black. Find the maximum possible area of Snuke's rectangle when the operation is performed optimally. -----Constraints----- - 2 \leq H \leq 2000 - 2 \leq W \leq 2000 - |S_i| = W - S_i consists of # and .. -----Input----- Input is given from Standard Input in the following format: H W S_1 S_2 : S_H -----Output----- Print the maximum possible area of Snuke's rectangle. -----Sample Input----- 3 3 ..# ##. .#. -----Sample Output----- 6 If the first row from the top and the third column from the left are inverted, a 2 \times 3 rectangle can be drawn, as shown below: 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()[:-1] H, W = map(int, input().split()) s = [input() for _ in range(H)] ans = max(H, W) def max_rect(a): res = 0 stack = [a[0]] for i in range(1, W-1): new_pos = i while stack and stack[-1] % 10000 >= a[i]: pos, hght = stack[-1] // 10000, stack[-1] % 10000 res = max(res, (i - pos + 1) * (hght + 1)) new_pos = pos stack.pop() stack.append(new_pos * 10000 + a[i]) while stack: pos, hght = stack[-1] // 10000, stack[-1] % 10000 res = max(res, (W - pos) * (hght + 1)) stack.pop() return res dp = [[0 for _ in range(W-1)] for _ in range(H-1)] for j in range(W-1): if not ((s[0][j] == s[1][j]) ^ (s[0][j+1] == s[1][j+1])): dp[0][j] = 1 ans = max(ans, max_rect(dp[0])) for i in range(1, H-1): for j in range(W-1): if not ((s[i][j] == s[i+1][j]) ^ (s[i][j+1] == s[i+1][j+1])): dp[i][j] = dp[i-1][j] + 1 ans = max(ans, max_rect(dp[i])) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have a fence consisting of $n$ vertical boards. The width of each board is $1$. The height of the $i$-th board is $a_i$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $2$ to $n$, the condition $a_{i-1} \neq a_i$ holds. Unfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the $i$-th board by $1$, but you have to pay $b_i$ rubles for it. The length of each board can be increased any number of times (possibly, zero). Calculate the minimum number of rubles you have to spend to make the fence great again! You have to answer $q$ independent queries. -----Input----- The first line contains one integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of queries. The first line of each query contains one integers $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of boards in the fence. The following $n$ lines of each query contain the descriptions of the boards. The $i$-th line contains two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le 10^9$) — the length of the $i$-th board and the price for increasing it by $1$, respectively. It is guaranteed that sum of all $n$ over all queries not exceed $3 \cdot 10^5$. It is guaranteed that answer to each query will not exceed $10^{18}$. -----Output----- For each query print one integer — the minimum number of rubles you have to spend to make the fence great. -----Example----- Input 3 3 2 4 2 1 3 5 3 2 3 2 10 2 6 4 1 7 3 3 2 6 1000000000 2 Output 2 9 0 -----Note----- In the first query you have to increase the length of second board by $2$. So your total costs if $2 \cdot b_2 = 2$. In the second query you have to increase the length of first board by $1$ and the length of third board by $1$. So your total costs if $1 \cdot b_1 + 1 \cdot b_3 = 9$. In the third query the fence is great initially, so you don't need to spend rubles. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python 3 import math import os import sys DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) INF = 10 ** 20 def solve(N, A, B): dp = {A[0]: 0, A[0] + 1: B[0], A[0] + 2: B[0] * 2} for i in range(1, N): ndp = {} h = A[i] for ph, c in dp.items(): for inc in range(3): nh = h + inc if ph == nh: continue if nh not in ndp: ndp[nh] = INF ndp[nh] = min(ndp[nh], c + B[i] * inc) dp = ndp return min(dp.values()) def main(): Q = int(inp()) for _ in range(Q): N = int(inp()) A = [] B = [] for _ in range(N): a, b = [int(e) for e in inp().split()] A.append(a) B.append(b) print(solve(N, A, B)) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today a plane was hijacked by a maniac. All the passengers of the flight are taken as hostage. Chef is also one of them. He invited one of the passengers to play a game with him. If he loses the game, he will release all the passengers, otherwise he will kill all of them. A high risk affair it is. Chef volunteered for this tough task. He was blindfolded by Hijacker. Hijacker brought a big black bag from his pockets. The contents of the bag is not visible. He tells Chef that the bag contains R red, G green and B blue colored balloons. Hijacker now asked Chef to take out some balloons from the box such that there are at least K balloons of the same color and hand him over. If the taken out balloons does not contain at least K balloons of the same color, then the hijacker will shoot everybody. Chef is very scared and wants to leave this game as soon as possible, so he will draw the minimum number of balloons so as to save the passengers. Can you please help scared Chef to find out the minimum number of balloons he should take out. -----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 three space-separated integers R, G and B. The second line contains only one integer K. -----Output----- For each test case, output a single line containing one integer - the minimum number of balloons Chef need to take out from the bag. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ R, G, B ≤ 109 - 1 ≤ K ≤ max{R, G, B} -----Subtasks----- - Subtask 1 (44 points): 1 ≤ R, G, B ≤ 10 - Subtask 2 (56 points): No additional constraints -----Example----- Input: 2 3 3 3 1 3 3 3 2 Output: 1 4 -----Explanation----- Example case 2. In the worst-case scenario first three balloons will be of the three different colors and only after fourth balloon Chef will have two balloons of the same color. So, Chef might need to fetch 4 balloons The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys test_cases = int(input()) for i in range(0,test_cases): count = input().split() #print count count_r = int(count[0]) count_g = int(count[1]) count_b = int(count[2]) k = int(input()) if k is 1: total = 1 else: total = 1 if count_r < k: total = total + count_r else: total = total + (k-1) if count_g < k: total = total + count_g else: total = total + (k-1) if count_b < k: total = total + count_b else: total = total + (k-1) print(total) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Due to the COVID pandemic, there has been an increase in the number of cases if a hospital. The management has decided to clear a large square area for the patients and arrange for beds. But the beds can't be too near to each other. The area is of dimension $N$ x $N$ The whole area is already divided into blocks. $1$ means there's a bed in the block, $0$ denotes there isn't. Note, beds placed on consecutive diagonal blocks are safe. This is a SAFE example: 1 0 0 1 This is an UNSAFE example: 0 1 1 0 0 0 1 0 0 To avoid spreading the virus even further, you have to make sure no two adjacent blocks have beds in them. This is done to maintain distance between beds. Return an output of "SAFE" if you find the workers have arranged the beds with due consideration to the distance needed. Return "UNSAFE" otherwise. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Next line contains $N$. - Next $N$ lines will contain $N$ number of space-separated integers $Ai$ which make denote the beds in the area. -----Output:----- For each test case, output in a single line whether the total arrangement is "SAFE" or "UNSAFE". Even if there's a single unsafe bed in the whole area, report the whole area as "UNSAFE". -----Constraints----- - $1 \leq T \leq 100$ - $0 \leq Ai \leq 1$ - $2 \leq N \leq 100$ -----Subtasks----- - 30 points : $1 \leq N \leq 7$ - 70 points : Original constraints -----Sample Input:----- 2 4 1 0 1 0 0 0 0 1 0 1 0 0 1 0 0 1 4 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0 0 -----Sample Output:----- SAFE UNSAFE -----EXPLANATION:----- Beds placed on blocks diagonally are not a problem. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python res = [] for _ in range(int(input())): lst = [] flag = 0 n = int(input()) for i in range(n): lst.append(list(map(int, input().split()))) for i in lst: for j in range(n-1): if i[j] == i[j+1] == 1: res.append("UNSAFE") flag = 1 break if flag != 0: break for i in range(n-1): for j in range(n): if lst[i][j] == lst[i+1] == 1: res.append("UNSAFE") flag = 1 break if flag != 0: break if flag == 0: res.append("SAFE") for i in res: print(i) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef had an array A with length N, but some of its elements got lost. Now, each element of this array is either unknown (denoted by -1) or a positive integer not exceeding K. Chef decided to restore the array A by replacing each unknown element by a positive integer not exceeding K. However, Chef has M restrictions that must hold for the restored array. There are two types of restrictions: - I L R, meaning that for each i such that L < i ≤ R, the condition Ai - Ai-1 = 1 should be satisfied. - D L R, meaning that for each i such that L < i ≤ R, the condition Ai - Ai-1 = -1 should be satisfied. Chef would like to know the number of ways to restore the array while satisfying all restrictions, modulo 109+7. -----Input----- - The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains three space-separated integers N, M and K. - The second line contains N integers A1, A2, ..., AN. - Each of the following M lines contains one restriction in the form I L R or D L R. -----Output----- For each test case, print a single line containing one integer - the number of ways to restore the array modulo 109+7. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N, M ≤ 100,000 - 1 ≤ K ≤ 1,000,000,000 - 1 ≤ L < R ≤ N - 1 ≤ Ai ≤ K or Ai = -1 for each valid i - 1 ≤ sum of N over all test cases ≤ 500,000 - 1 ≤ sum of M over all test cases ≤ 500,000 -----Example----- Input: 3 4 2 10 2 3 5 4 I 1 2 D 3 4 5 2 10 -1 -1 -1 -1 -1 I 1 3 D 3 5 6 2 2 -1 -1 -1 -1 -1 -1 I 1 4 D 4 6 Output: 1 8 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here MOD = 10 ** 9 + 7 for t in range(int(input())): N, M, K = map(int, input().split()) A = list(map(int, input().split())) I, D = [0] * (N + 2), [0] * (N + 2) for i in range(M): x, L, R = input().split() L, R = int(L), int(R) if x == 'I': I[L] += 1 I[R] -= 1 else: D[L] += 1 D[R] -= 1 impossibru = mx = mn = 0 ans = 1 for i in range(N): I[i] += I[i - 1] D[i] += D[i - 1] if I[i] and D[i]: impossibru = 1 break if not I[i] and not D[i]: ans = ans * (mx - mn + 1) % MOD mn, mx = 1, K elif I[i]: mx = min(mx + 1, K) mn += 1 elif D[i]: mn = max(1, mn - 1) mx -= 1 if mn > mx: impossibru = 1 break if A[i] != -1: if not mn <= A[i] <= mx: impossibru = 1 break mn = mx = A[i] ans = ans * (mx - mn + 1) % MOD print(0 if impossibru else ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has a binary array in an unsorted manner. Cheffina challenges chef to find the transition point in the sorted (ascending) binary array. Here indexing is starting from 0. Note: Transition point always exists. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains two lines of input, $N$. - N space-separated binary numbers. -----Output:----- For each test case, output in a single line answer. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 10^5$ -----Sample Input:----- 1 5 0 1 0 0 1 -----Sample Output:----- 3 -----EXPLANATION:----- binary array in sorted form will look like = [0, 0, 0, 1, 1] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n=int(input()) A=list(map(int,input().split())) A.sort() for i in range(len(A)): if A[i]==1: print(i) break ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You have an array A of size N containing only positive numbers. You have to output the maximum possible value of A[i]%A[j] where 1<=i,j<=N. -----Input----- The first line of each test case contains a single integer N denoting the size of the array. The next N lines contains integers A1, A2, ..., AN denoting the numbers -----Output----- Output a single integer answering what is asked in the problem. -----Subtask 1 (20 points)----- - 1 ≤ N ≤ 5000 - 1 ≤ A[i] ≤ 2*(10^9) -----Subtask 2 (80 points)----- - 1 ≤ N ≤ 1000000 - 1 ≤ A[i] ≤ 2*(10^9) -----Example----- Input: 2 1 2 Output: 1 -----Explanation----- There will be four values, A[0]%A[0] = 0, A[0]%A[1]=1, A[1]%A[0]=0, A[1]%A[1]=0, and hence the output will be the maximum among them all, that 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 = int(input()) a = [] for i in range(n): a.append(int(input())) m1 = 0 m2 = 0 for e in a: if (e > m1): m2 = m1 m1 = e elif (e > m2 and e != m1): m2 = e ans = 0 for e in a: temp = m1%e if (temp>ans): ans = temp print(max(m2%m1,ans)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef received a permutation $P_1, P_2, \ldots, P_N$ and also an integer $D$ from his good friend Grux, because Grux was afraid he would forget them somewhere. However, since Grux was just playing with the permutation, it was all shuffled, and Chef only likes sorted permutations, so he decided to sort it by performing some swaps. Chef wants to use the integer $D$ he just received, so he is only willing to swap two elements of the permutation whenever their absolute difference is exactly $D$. He has limited time, so you should determine the minimum number of swaps he needs to perform to sort the permutation, or tell him that it is impossible to sort it his way. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $D$. - The second line contains $N$ space-separated integers $P_1, P_2, \ldots, P_N$. -----Output----- For each test case, print a single line containing one integer ― the minimum number of swaps, or $-1$ if it is impossible to sort the permutation. -----Constraints----- - $1 \le T \le 20$ - $1 \le N \le 200,000$ - $1 \le D \le N$ - $1 \le P_i \le N$ for each valid $i$ - $P_1, P_2, \ldots, P_N$ are pairwise distinct - the sum of $N$ over all test cases does not exceed $10^6$ -----Subtasks----- Subtask #1 (20 points): $D = 1$ Subtask #2 (30 points): - $N \le 1,000$ - the sum of $N$ over all test cases does not exceed $10,000$ Subtask #3 (50 points): original constraints -----Example Input----- 2 5 2 3 4 5 2 1 5 2 4 3 2 1 5 -----Example Output----- 3 -1 -----Explanation----- Example case 1: Chef can perform the following swaps in this order: - swap the first and fifth element - swap the third and fifth element - swap the second and fourth element 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(10000000) def mergeSortInversions(arr): if len(arr) == 1: return arr, 0 larr=len(arr) a = arr[:larr//2] b = arr[larr//2:] a, ai = mergeSortInversions(a) b, bi = mergeSortInversions(b) c = [] i = 0 j = 0 inversions = 0 + ai + bi la=len(a) while i < la and j < len(b): if a[i] <= b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 inversions += (la-i) c += a[i:] c += b[j:] return c, inversions for _ in range(int(input())): n,d=list(map(int,input().split())) p=[int(o) for o in input().split()] array=[[] for i in range(d)] flag=0 for i in range(n): array[i%d].append(p[i]) if p[i]%((i%d)+1)!=0: flag=1 ans=0 dumarr=[0]*n for i in range(d): array[i],v=mergeSortInversions(array[i]) for j in range(len(array[i])): dumarr[i+j*d]=array[i][j] ans+=v p=sorted(p) # print(dumarr) if dumarr==p: print(ans) else: print(-1) ```