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: There are $N$ cars (numbered $1$ through $N$) on a circular track with length $N$. For each $i$ ($2 \le i \le N$), the $i$-th of them is at a distance $i-1$ clockwise from car $1$, i.e. car $1$ needs to travel a distance $i-1$ clockwise to reach car $i$. Also, for each valid $i$, the $i$-th car has $f_i$ litres of gasoline in it initially. You are driving car $1$ in the clockwise direction. To move one unit of distance in this direction, you need to spend $1$ litre of gasoline. When you pass another car (even if you'd run out of gasoline exactly at that point), you steal all its gasoline. Once you do not have any gasoline left, you stop. What is the total clockwise distance travelled by your car? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $f_1, f_2, \ldots, f_N$. -----Output----- For each test case, print a single line containing one integer ― the total clockwise distance travelled. -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 100$ - $0 \le f_i \le 100$ for each valid $i$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 3 5 3 0 0 0 0 5 1 1 1 1 1 5 5 4 3 2 1 -----Example Output----- 3 5 15 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()) f=list(map(int,input().split())) sum1=f[0] d=0 i=1 while sum1!=0 and i<n: sum1=sum1-1+f[i] d+=1 i+=1 print(d+sum1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef belongs to a very rich family which owns many gold mines. Today, he brought N gold coins and decided to form a triangle using these coins. Isn't it strange? Chef has a unusual way of forming a triangle using gold coins, which is described as follows: - He puts 1 coin in the 1st row. - then puts 2 coins in the 2nd row. - then puts 3 coins in the 3rd row. - and so on as shown in the given figure. Chef is interested in forming a triangle with maximum possible height using at most N coins. Can you tell him the maximum possible height of the triangle? -----Input----- The first line of input contains a single integer T denoting the number of test cases. The first and the only line of each test case contains an integer N denoting the number of gold coins Chef has. -----Output----- For each test case, output a single line containing an integer corresponding to the maximum possible height of the triangle that Chef can get. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 109 -----Subtasks----- - Subtask 1 (48 points) : 1 ≤ N ≤ 105 - Subtask 2 (52 points) : 1 ≤ N ≤ 109 -----Example----- Input3 3 5 7 Output2 2 3 -----Explanation----- - Test 1: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins. - Test 2: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins. - Test 3: Chef can't form a triangle with height > 3 as it requires atleast 10 gold coins. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = eval(input()) def moneda(m): h = 1 triange = [] while m >= h: triange.append(h) m -= h h += 1 return len(triange) triangulo = [] for i in range(t): n = eval(input()) triangulo.append(n) for i in triangulo: print(moneda(i)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is Chef and Chef’s Crush who are playing a game of numbers. Chef’s crush has a number $A$ and Chef has a number $B$. Now, Chef wants Chef’s crush to win the game always, since she is his crush. The game ends when the greatest value of A^B is reached after performing some number of operations (possibly zero), Where ^ is Bitwise XOR. Before performing any operation you have to ensure that both $A$ and $B$ have the same number of bits without any change in the values. It is not guaranteed that $A$ and $B$ should have same number of bits in the input. For example, if $A$ is $2$ and $B$ is $15$, then the binary representation of both the numbers will have to be $0010$ and $1111$ respectively, before performing any operation. The operation is defined as : - Right circular shift of the bits of only $B$ from MSB$_B$ to LSB$_B$ i.e. if we consider $B_1 B_2 B_3 B_4$ as binary number, then after one circular right shift, it would be $B_4 B_1 B_2 B_3$ They both are busy with themselves, can you find the number of operations to end the game? -----Input :----- - The first line of input contains $T$, (number of test cases) - Then each of the next $T$ lines contain : two integers $A$ and $B$ respectively. -----Output :----- For each test case print two space-separated integers, The number of operations to end the game and value of A^B when the game ends. -----Constraints :----- - $1 \leq T \leq100$ - $1\leq A,B \leq 10^{18}$ -----Subtasks :----- - 30 Points: $1\leq A,B \leq 10^5$ - 70 Points: Original Constraints -----Sample Input :----- 1 4 5 -----Sample Output :----- 2 7 -----Explanation :----- Binary representation of $4$ is $100$ and binary representation $5$ is $101$. - After operation $1$ : $B$ $=$ $110$, so A^B $=$ $2$ - After operation $2$ : $B$ $=$ $011$, so A^B $=$ $7$ So, the value of A^B will be $7$. Which is the greatest possible value for A^B and the number of operations are $2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): t = int(input()) while (t): m, n = map(int, input().split()) a , b= bin(m)[2:],bin(n)[2:] #print(a,b) max = m^n if len(a)>len(b): diff =len(a)-len(b) b= ("0"*diff)+b #print(b) elif len(a)<len(b): diff =len(b)-len(a) a= ("0"*diff)+a #print(a) ll = len(b) count= 0 for i in range(ll-1): s= b[ll-1] + b s= s[:ll] tt= m^ int(s,2) #print(m,s,tt) if tt>max: max =tt count= i+1 b=s print(count,max) t-=1 def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mandarin chinese , Russian and Vietnamese as well. Chef is organising a contest with $P$ problems (numbered $1$ through $P$). Each problem has $S$ subtasks (numbered $1$ through $S$). The difficulty of a problem can be calculated as follows: - Let's denote the score of the $k$-th subtask of this problem by $SC_k$ and the number of contestants who solved it by $NS_k$. - Consider the subtasks sorted in the order of increasing score. - Calculate the number $n$ of valid indices $k$ such that $NS_k > NS_{k + 1}$. - For problem $i$, the difficulty is a pair of integers $(n, i)$. You should sort the problems in the increasing order of difficulty levels. Since difficulty level is a pair, problem $a$ is more difficult than problem $b$ if the number $n$ is greater for problem $a$ than for problem $b$, or if $a > b$ and $n$ is the same for problems $a$ and $b$. -----Input----- - The first line of the input contains two space-separated integers $P$ and $S$ denoting the number of problems and the number of subtasks in each problem. - $2P$ lines follow. For each valid $i$, the $2i-1$-th of these lines contains $S$ space-separated integers $SC_1, SC_2, \dots, SC_S$ denoting the scores of the $i$-th problem's subtasks, and the $2i$-th of these lines contains $S$ space-separated integers $NS_1, NS_2, \dots, NS_S$ denoting the number of contestants who solved the $i$-th problem's subtasks. -----Output----- Print $P$ lines containing one integer each — the indices of the problems in the increasing order of difficulty. -----Constraints----- - $1 \le P \le 100,000$ - $2 \le S \le 30$ - $1 \le SC_i \le 100$ for each valid $i$ - $1 \le NS_i \le 1,000$ for each valid $i$ - in each problem, the scores of all subtasks are unique -----Subtasks----- Subtask #1 (25 points): $S = 2$ Subtask #2 (75 points): original constraints -----Example Input----- 3 3 16 24 60 498 861 589 14 24 62 72 557 819 16 15 69 435 779 232 -----Example Output----- 2 1 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python p,s = [int(i) for i in input().split()] scores = {} for j in range(1, p + 1): sc = [int(i) for i in input().split()] ns = [int(i) for i in input().split()] nsc = dict(list(zip(sc,ns))) ssc = sorted(sc) score = 0 for a,b in zip(ssc[:-1], ssc[1:]): if nsc[a] > nsc[b]: score += 1 if score in list(scores.keys()) : scores[score].append(j) else : scores[score] = [j] total_scores = sorted(list(scores.keys())) final_list = [] for val in total_scores : final_list += sorted(scores[val]) for val in final_list : print(val) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices. Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 4) — the number of vertices that were not erased by Wilbur's friend. Each of the following n lines contains two integers x_{i} and y_{i} ( - 1000 ≤ x_{i}, y_{i} ≤ 1000) —the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order. It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes. -----Output----- Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print - 1. -----Examples----- Input 2 0 0 1 1 Output 1 Input 1 1 1 Output -1 -----Note----- In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square. In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area. 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()) points = [[int(x) for x in input().split()] for _ in range(n)] if n <= 1: print(-1) return dx = [1e9, -1e9] dy = [1e9, -1e9] for x, y in points: dx[0] = min(dx[0], x) dx[1] = max(dx[1], x) dy[0] = min(dy[0], y) dy[1] = max(dy[1], y) area = (dx[1] - dx[0]) * (dy[1] - dy[0]) if area: print(area) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Yesterday, Chef found $K$ empty boxes in the cooler and decided to fill them with apples. He ordered $N$ apples, where $N$ is a multiple of $K$. Now, he just needs to hire someone who will distribute the apples into the boxes with professional passion. Only two candidates passed all the interviews for the box filling job. In one minute, each candidate can put $K$ apples into boxes, but they do it in different ways: the first candidate puts exactly one apple in each box, while the second one chooses a random box with the smallest number of apples and puts $K$ apples in it. Chef is wondering if the final distribution of apples can even depend on which candidate he hires. Can you answer that question? Note: The boxes are distinguishable (labeled), while the apples are not. Therefore, two distributions of apples are different if there is a box such that the number of apples in it when the first candidate finishes working can be different from the number of apples in it when the second candidate finishes working. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $N$ and $K$. -----Output----- For each test case, print a single line containing the string "YES" if the final distributions of apples can be different or "NO" if they will be the same (without quotes). -----Constraints----- - $1 \le T \le 250$ - $1 \le N, K \le 10^{18}$ - $N$ is divisible by $K$ -----Subtasks----- Subtask #1 (30 points): $1 \le N, K \le 10^5$ Subtask #2 (70 points): original constraints -----Example Input----- 3 5 1 4 2 10 10 -----Example Output----- NO NO YES -----Explanation----- Example case 1: No matter who is hired, all apples will be in the only box at the end. Example case 2: At the end, there will be two apples in each box. Example case 3: If we hire the first candidate, there will be one apple in each box, but if we hire the second one, there will be $10$ apples in one box and none in all other boxes. 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,0,-1): x,y=map(int,input().split()) k=x//y if k%y==0: print("NO") else: print("YES") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Consider the following operations on a triple of integers. In one operation, you should: - Choose an integer $d$ and an arithmetic operation ― either addition or multiplication. - Choose a subset of elements of the triple. - Apply the arithmetic operation to each of the chosen elements, i.e. either add $d$ to each of them or multiply each of them by $d$. For example, if we have a triple $(3, 5, 7)$, we may choose to add $3$ to the first and third element, and we get $(6, 5, 10)$ using one operation. You are given an initial triple $(p, q, r)$ and a target triple $(a, b, c)$. Find the minimum number of operations needed to transform $(p, q, r)$ into $(a, b, c)$. -----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 $p$, $q$ and $r$. - The second line contains three space-separated integers $a$, $b$ and $c$. -----Output----- For each test case, print a single line containing one integer ― the minimum required number of operations. -----Constraints----- - $1 \le T \le 1,000$ - $|p|, |q|, |r|, |a|, |b|, |c| \le 10^9$ -----Subtasks----- Subtask #1 (10 points): $|p|, |q|, |r|, |a|, |b|, |c| \le 10$ Subtask #2 (90 points): original constraints -----Example Input----- 2 3 5 7 6 5 10 8 6 3 9 7 8 -----Example Output----- 1 2 -----Explanation----- Example case 1: We add $3$ to the first and third element of $(3, 5, 7)$ to form $(6, 5, 10)$. Example case 2: We can add $1$ to each element to form $(9, 7, 4)$ and then multiply the third element by $2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def eq_solve(v0, v1, u0, u1): den = u0 - v0 num = u1 - v1 if den != 0: return num / den return 1 def solve(p, q, r, a, b, c, rs): if p == a and q == b and r == c: return rs if rs >= 2: return 3 res = 3 adds = [a - p, b - q, c - r] muls = [] if p != 0: muls.append(a / p) if q != 0: muls.append(b / q) if r != 0: muls.append(c / r) muls.append(eq_solve(p, a, q, b)) muls.append(eq_solve(p, a, r, c)) muls.append(eq_solve(q, b, r, c)) msks = 2 ** 3 for msk in range(msks): for add in adds: np = p nq = q nr = r if (msk & 1) > 0: np += add if (msk & 2) > 0: nq += add if (msk & 4) > 0: nr += add res = min(res, solve(np, nq, nr, a, b, c, rs + 1)) for mul in muls: np = p nq = q nr = r if (msk & 1) > 0: np *= mul if (msk & 2) > 0: nq *= mul if (msk & 4) > 0: nr *= mul res = min(res, solve(np, nq, nr, a, b, c, rs + 1)) return res t = int(input()) while t > 0: p, q, r = map(int, input().split()) a, b, c = map(int, input().split()) z = solve(p, q, r, a, b, c, 0) print(z) t -= 1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has a sequence of $N$ integers, $A_1, A_2, ... , A_N$. He likes this sequence if it contains a subsequence of $M$ integers, $B_1, B_2, ... , B_M$ within it. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. You will be given a sequence of $N$ integers, $A_1, A_2, ..., A_N$ followed by another sequence of $M$ integers, $B_1, B_2, ..., B_M$. Given these, you have to tell whether Chef likes the sequence of $N$ integers($A_1, A_2, ..., A_N$) or not. Formally, output "Yes" if $\exists idx_1, idx_2, ..., idx_M | 1 \le idx_1 < idx_2 < ... < idx_M \le N$ and $A_{idx_i} = B_i \forall i, 1 \le i \le M$ Otherwise output "No". Note that the quotes are for clarity. -----Input----- The first line contains a single integer, $T$. $T$ test cases follow where each test case contains four lines: - The first line of a test case contains a single integer $N$ - The second line of the test case contains $N$ space separated integers, $A_1, A_2, ..., A_N$ - The third line of the test case contains a single integer $M$. - The fourth line contains $M$ space separated integers, $B_1, B_2, ..., B_M$ Symbols have usual meanings as described in the statement. -----Output----- For each test case, output a single line containing the output. Output is "Yes" if Chef likes the sequence $A$. Output is "No" if Chef dislikes the sequence $A$. -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 10^3$ - $1 \le M \le 10^3$ - $1 \le A_i, B_i \le 10^9$ -----Sample Input----- 3 6 1 2 3 4 5 6 3 2 3 4 6 22 5 6 33 1 4 2 4 15 4 1 3 4 2 2 1 2 -----Sample Output----- Yes No Yes -----Explanation:----- In sample test case $1$, the sequence $1,2,3,4,5,6$ contains the subsequence $2, 3, 4$. The subsequence is present at indices $1, 2, 3$ of the original sequence. Hence, $1,2,3,4,5,6$ is a sequence which Chef likes it. Therefore, we output "Yes". In sample test case $2$, the subsequence $4, 15$ is not present in sequence $22, 5, 6, 33, 1, 4$. Hence, we output "No". In sample test case $3$, the sequence $1, 3, 4, 2$ contains the subsequence $1, 2$. The subsequence is present at indices $0, 3$. Therefore, we output "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()) i=0 while i<t: n=int(input()) A=[] A=input().split() m=int(input()) B=[] B=input().split() j=0 a=-1 while j<m: c=1 if B[j] in A: b=A.index(B[j]) A.remove(B[j]) if b>=a: a=b c=1 else: c=0 break else: c=0 break j+=1 if c==1: print("Yes") else: print("No") i+=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a string s consisting of |s| small english letters. In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter. Your target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible. -----Input----- The only one line of the input consisting of the string s consisting of |s| (1 ≤ |s| ≤ 10^5) small english letters. -----Output----- If you can get a string that can be obtained from the given string and will contain english alphabet as a subsequence, print it. Otherwise print «-1» (without quotes). -----Examples----- Input aacceeggiikkmmooqqssuuwwyy Output abcdefghijklmnopqrstuvwxyz Input thereisnoanswer Output -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s = list(input()) target = 'abcdefghijklmnopqrstuvwxyz' ind_t = 0 ind_s = 0 while ind_s < len(s) and ind_t < 26: if ord(s[ind_s]) <= ord(target[ind_t]): s[ind_s] = target[ind_t] ind_t += 1 ind_s += 1 else: ind_s += 1 if ind_t == 26: print(''.join(s)) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: "Ring Ring!!" Sherlock's phone suddenly started ringing. And it was none other than Jim Moriarty.. "Long time no see ! You miss me right ? Anyway we'll talk about it later . Let me first tell you something. Dr.Watson is with me . And you've got only one chance to save him . Here's your challenge:. Given a number N and another number M, tell if the remainder of N%M is odd or even. If it's odd, then print "ODD" else print "EVEN" If Sherlock can answer the query correctly, then Watson will be set free. He has approached you for help since you being a programmer.Can you help him? -----Input----- The first line contains, T, the number of test cases.. Each test case contains an integer, N and M -----Output----- Output the minimum value for each test case -----Constraints----- 1 = T = 20 1 <= N <= 10^18 1 <= M<= 10^9 -----Subtasks----- Subtask #1 : (20 points) 1 = T = 20 1 <= N <= 100 1 <= M<= 100 Subtask 2 : (80 points) 1 = T = 20 1 <= N <= 10^18 1 <= M<= 10^9 -----Example----- Input: 2 4 4 6 5 Output: EVEN ODD The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys user_input = sys.stdin.readline().split() T = int(user_input[0]) for j in range(T) : var = sys.stdin.readline().split() N = int(var[0]) M = int(var[1]) if (N%M)%2 : print("ODD") else : print("EVEN") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Consider a tree $T$ (that is, a connected graph without cycles) with $n$ vertices labelled $1$ through $n$. We start the following process with $T$: while $T$ has more than one vertex, do the following: choose a random edge of $T$ equiprobably; shrink the chosen edge: if the edge was connecting vertices $v$ and $u$, erase both $v$ and $u$ and create a new vertex adjacent to all vertices previously adjacent to either $v$ or $u$. The new vertex is labelled either $v$ or $u$ equiprobably. At the end of the process, $T$ consists of a single vertex labelled with one of the numbers $1, \ldots, n$. For each of the numbers, what is the probability of this number becoming the label of the final vertex? -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 50$). The following $n - 1$ lines describe the tree edges. Each of these lines contains two integers $u_i, v_i$ — labels of vertices connected by the respective edge ($1 \leq u_i, v_i \leq n$, $u_i \neq v_i$). It is guaranteed that the given graph is a tree. -----Output----- Print $n$ floating numbers — the desired probabilities for labels $1, \ldots, n$ respectively. All numbers should be correct up to $10^{-6}$ relative or absolute precision. -----Examples----- Input 4 1 2 1 3 1 4 Output 0.1250000000 0.2916666667 0.2916666667 0.2916666667 Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output 0.0850694444 0.0664062500 0.0664062500 0.1955295139 0.1955295139 0.1955295139 0.1955295139 -----Note----- In the first sample, the resulting vertex has label 1 if and only if for all three edges the label 1 survives, hence the probability is $1/2^3 = 1/8$. All other labels have equal probability due to symmetry, hence each of them has probability $(1 - 1/8) / 3 = 7/24$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python maxn=50+10 g=[None]*maxn dp=[None]*maxn c=[None]*maxn size=[0]*maxn for i in range(0,maxn): c[i]=[0]*maxn c[i][0]=1 for j in range(1,i+1): c[i][j]=c[i-1][j-1]+c[i-1][j] n=int(input()) for i in range(1,n+1): g[i]=[] for i in range(1,n): u,v=input().split() u=int(u) v=int(v) g[u].append(v) g[v].append(u) def mul(a,b,x,y): tmp=[0]*(x+y+1) for i in range(0,x+1): for j in range(0,y+1): tmp[i+j]+=a[i]*b[j]*c[i+j][i]*c[x+y-i-j][x-i] return tmp def dfs(pos,fa): nonlocal dp nonlocal size dp[pos]=[1] size[pos]=0 for ch in g[pos]: if ch != fa: dfs(pos=ch,fa=pos) dp[pos]=mul(dp[pos],dp[ch],size[pos],size[ch]) size[pos]+=size[ch] if fa: size[pos]+=1 tmp=[0]*(size[pos]+1) for i in range(0,size[pos]+1): for j in range(0,size[pos]): if j<i: tmp[i]+=dp[pos][i-1] else: tmp[i]+=dp[pos][j]*0.5 dp[pos]=tmp for i in range(1,n+1): dfs(pos=i,fa=0) tmp=dp[i][0] for j in range(1,n): tmp/=j print(tmp) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given an array of size N$N$ and two integers K$K$ and S$S$, the special sum of a subarray is defined as follows: (Sum of all elements of the subarray) * (K$K$ - p$p$ * S$S$) Where p$p$ = number of distinct prime factors of “product of all elements of the subarray”. Find the maximum special sum by considering all non-empty subarrays of the given array. -----Input----- - First line contains 3 integers N$N$, K$K$ and S$S$. - Second line contains N$N$ integers, the elements of the array. -----Output----- Output a single integer. The maximum special sum considering all non-empty subarrays of the array. -----Constraints:----- - 1≤N,K,S≤105$ 1 \leq N, K, S \leq 10^5 $ - 0≤K/S≤20$ 0 \leq K / S \leq 20 $ - 1<$ 1 < $ Any element of array <105$ < 10^5 $ -----Sample Input----- 4 10 2 14 2 7 15 -----Sample Output----- 138 -----Sample Explanation----- Consider the subarray {14, 2, 7} Total number of distinct prime factors in it is 2 (2 and 7). Therefore, value of special sum is (14 + 2 + 7) * (10 - 2 * 2) = 138. This is the subarray with the maximum special sum. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from math import floor, sqrt try:long except NameError:long = int def fac(n): step,maxq,d = lambda x: 1 + (x<<2) - ((x>>1)<<1),long(floor(sqrt(n))),1 q = n % 2 == 0 and 2 or 3 while q <= maxq and n % q != 0: q = step(d) d += 1 return q <= maxq and [q] + fac(n//q) or [n] n,k,s = map(int,input().split()) a,di,l,m,ans,su =list(map(int,input().split())),{},[],0,0,0 for i in a: bb,su = list(set(fac(i))),su+i for j in bb: try:di[j]+=1 except KeyError:m,di[j] = m+1,1 l.append(su*(k-m*s)) if su*(k-m*s) <0:m,di,su = 0,{},0 print(max(l)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format. The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description). Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m. -----Input----- The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·10^6 (in particular, this means that the length of some line does not exceed 5·10^6 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty. -----Output----- If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m. -----Examples----- Input 60 3 2012-03-16 16:15:25: Disk size is 2012-03-16 16:15:25: Network failute 2012-03-16 16:16:29: Cant write varlog 2012-03-16 16:16:42: Unable to start process 2012-03-16 16:16:43: Disk size is too small 2012-03-16 16:16:53: Timeout detected Output 2012-03-16 16:16:43 Input 1 2 2012-03-16 23:59:59:Disk size 2012-03-17 00:00:00: Network 2012-03-17 00:00:01:Cant write varlog Output -1 Input 2 2 2012-03-16 23:59:59:Disk size is too sm 2012-03-17 00:00:00:Network failute dete 2012-03-17 00:00:01:Cant write varlogmysq Output 2012-03-17 00:00:00 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # import atexit # import io # import sys # # _INPUT_LINES = sys.stdin.read().splitlines() # input = iter(_INPUT_LINES).__next__ # _OUTPUT_BUFFER = io.StringIO() # sys.stdout = _OUTPUT_BUFFER # # # @atexit.register # def write(): # sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) import bisect from datetime import datetime def main(): n, m = list(map(int, input().split())) n -= 1 timestamps = [] raw = [] while True: s = "" try: s = input() except: print(-1) return d = datetime.strptime(s[0:19], "%Y-%m-%d %H:%M:%S") timestamps.append(int(d.timestamp())) raw.append(s[0:19]) idx = bisect.bisect_left(timestamps, timestamps[-1] - n) if len(timestamps) - idx == m: print(raw[-1]) return def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number y?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of. Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers y_{i}, he should ask the questions about. -----Input----- A single line contains number n (1 ≤ n ≤ 10^3). -----Output----- Print the length of the sequence of questions k (0 ≤ k ≤ n), followed by k numbers — the questions y_{i} (1 ≤ y_{i} ≤ n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them. -----Examples----- Input 4 Output 3 2 4 3 Input 6 Output 4 2 4 3 5 -----Note----- The sequence from the answer to the first sample test is actually correct. If the unknown number is not divisible by one of the sequence numbers, it is equal to 1. If the unknown number is divisible by 4, it is 4. If the unknown number is divisible by 3, then the unknown number is 3. Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter. 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 = int(input()) result = [] for i in range(2, n + 1): j = 2 while j * j <= i: if i % j == 0: break j += 1 else: j = i while j <= n: result.append(j) j *= i print(len(result)) print(' '.join(str(i) for i in result)) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is again playing a game with his best friend Garry. As usual, the rules of this game are extremely strange and uncommon. First, they are given a stack of $N$ discs. Each disc has a distinct, non-negative integer written on it. The players exchange turns to make a move. Before the start of the game, they both agree upon a set of positive integers $S$ of size $K$. It is guaranteed that S contains the integer $1$. In a move, a player can select any value $x$ from $S$ and pop exactly $x$ elements from the top of the stack. The game ends when there are no discs remaining. Chef goes first. Scoring: For every disc a player pops, his score increases by $2^p$ where $p$ is the integer written on the disc. For example, if a player pops the discs, with integers $p_1, p_2, p_3, \dots, p_m$ written on it, during the entire course of the game, then his total score will be $2^{p_1} + 2^{p_2} + 2^{p_3} + \dots + 2^{p_m}$. The player with higher score wins the game. Determine the winner if both the players play optimally, or if the game ends in a draw. -----Input:----- - First line contains $T$, the number of testcases. Then the testcases follow. - The first line of each test case contains two space separated integers $N$ and $K$, denoting the size of the stack and the set S respectively. - Next line contains $N$ space separated integers $A_i$ where $A_1$ is the topmost element, denoting the initial arrangement of the stack. - The last line of each test case contains $K$ space separated integers each denoting $x_i$. -----Output:----- For each testcase, output "Chef" (without quotes) if Chef wins, "Garry" (without quotes) if Garry wins, otherwise "Draw" (without quotes) in a separate line. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^5$ - $1 \leq K \leq \min(100, N)$ - $0 \leq A_i \leq 10^9$ - $1 \leq x_i \leq N$ - $x_i \neq x_j$ for all $i \neq j$ - $A_i \neq A_j$ for all $i \neq j$ - Set $S$ contains integer $1$. - Sum of $N$ over all test cases does not exceed $10^5$. -----Sample Input:----- 1 3 2 5 7 1 1 2 -----Sample Output:----- Chef -----Explanation:----- Chef can select 2 from the set and draw the top two discs (with integers 5 and 7 written on it) from the stack. Garry cannot select 2 from the set as there is only 1 disc left in the stack. However, he can select 1 from the set and pop the last disc. So, Chef's score = $2^5$ + $2^7$ = $160$ Garry's score = $2^1$ = $2$ Chef wins. 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 = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) a = [-1] + a[::-1] mx = a.index(max(a)) dp = [0] * (n + 1) for i in range(1, n + 1): for x in b: if i - x < 0: continue if i - x < mx <= i: dp[i] = 1 else: dp[i] |= not dp[i - x] print('Chef' if dp[-1] else 'Garry') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef found a strange string yesterday - a string of signs s, where each sign is either a '<', '=' or a '>'. Let N be the length of this string. Chef wants to insert N + 1 positive integers into this sequence and make it valid. A valid sequence is a sequence where every sign is preceded and followed by an integer, and the signs are correct. That is, if a sign '<' is preceded by the integer a and followed by an integer b, then a should be less than b. Likewise for the other two signs as well. Chef can take some positive integers in the range [1, P] and use a number in the range as many times as he wants. Help Chef find the minimum possible P with which he can create a valid sequence. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains the string of signs s, where each sign is either '<', '=' or a '>'. -----Output----- For each test case, output a single line containing an integer corresponding to the minimum possible P. -----Constraints----- - 1 ≤ T, |s| ≤ 105 - 1 ≤ Sum of |s| over all test cases in a single test file ≤ 106 -----Subtasks----- Subtask #1 (30 points) - 1 ≤ T, |s| ≤ 103 - 1 ≤ Sum of |s| over all test cases in a single test file ≤ 104 Subtask #2 (70 points) - Original constraints -----Example----- Input: 4 <<< <>< <=> <=< Output: 4 2 2 3 -----Explanation----- Here are some possible valid sequences which can be formed with the minimum P for each of the test cases: 1 < 2 < 3 < 4 1 < 2 > 1 < 2 1 < 2 = 2 > 1 1 < 2 = 2 < 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): st=input().replace("=","") if not len(st):print(1) else: cu=mx=1 for j in range(1,len(st)): if st[j]==st[j-1]:cu+=1 else:mx=max(mx,cu);cu=1 print(max(mx+1,cu+1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In a country called Chef Land, there was a lot of monetary fraud, so Chefu, the head of the country, decided to choose new denominations of the local currency ― all even-valued coins up to an integer $N$ should exist. After a few days, a citizen complained that there was no way to create an odd value, so Chefu decided that he should also introduce coins with value $1$. Formally, you are given an integer $N$; for $v = 1$ and each even positive integer $v \le N$, coins with value $v$ exist. You are also given an integer $S$. To handle transactions quickly, find the minimum number of coins needed to pay a price $S$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $S$ and $N$. -----Output----- For each test case, print a single line containing one integer ― the minimum number of coins. -----Constraints----- - $1 \le T \le 10,000$ - $1 \le S \le 10^9$ - $2 \le N \le 10^9$ - $N$ is even -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 4 2 2 1 14 30 10 31 4 -----Example Output----- 1 1 3 9 -----Explanation----- Example case 1: One coin with value $2$ is sufficient. Example case 2: We need to use one coin with value $1$. Example case 3: We need $3$ coins, each with value $10$. Example case 4: We can use seven coins with value $4$, one coin with value $2$ and one coin with value $1$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for i in range(int(input())): n,k=list(map(int,input().split())) t=0 if n%2!=0: n-=1 t+=1 t+=(n//k) if n%k!=0: t+=1 print(t) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let $a$ and $b$ be two arrays of lengths $n$ and $m$, respectively, with no elements in common. We can define a new array $\mathrm{merge}(a,b)$ of length $n+m$ recursively as follows: If one of the arrays is empty, the result is the other array. That is, $\mathrm{merge}(\emptyset,b)=b$ and $\mathrm{merge}(a,\emptyset)=a$. In particular, $\mathrm{merge}(\emptyset,\emptyset)=\emptyset$. If both arrays are non-empty, and $a_1<b_1$, then $\mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b)$. That is, we delete the first element $a_1$ of $a$, merge the remaining arrays, then add $a_1$ to the beginning of the result. If both arrays are non-empty, and $a_1>b_1$, then $\mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m])$. That is, we delete the first element $b_1$ of $b$, merge the remaining arrays, then add $b_1$ to the beginning of the result. This algorithm has the nice property that if $a$ and $b$ are sorted, then $\mathrm{merge}(a,b)$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $a=[3,1]$ and $b=[2,4]$, then $\mathrm{merge}(a,b)=[2,3,1,4]$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). There is a permutation $p$ of length $2n$. Determine if there exist two arrays $a$ and $b$, each of length $n$ and with no elements in common, so that $p=\mathrm{merge}(a,b)$. -----Input----- The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $2t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 2000$). The second line of each test case contains $2n$ integers $p_1,\ldots,p_{2n}$ ($1\le p_i\le 2n$). It is guaranteed that $p$ is a permutation. It is guaranteed that the sum of $n$ across all test cases does not exceed $2000$. -----Output----- For each test case, output "YES" if there exist arrays $a$, $b$, each of length $n$ and with no common elements, so that $p=\mathrm{merge}(a,b)$. Otherwise, output "NO". -----Example----- Input 6 2 2 3 1 4 2 3 1 2 4 4 3 2 6 1 5 7 8 4 3 1 2 3 4 5 6 4 6 1 3 7 4 5 8 2 6 4 3 2 5 1 11 9 12 8 6 10 7 Output YES NO YES YES NO NO -----Note----- In the first test case, $[2,3,1,4]=\mathrm{merge}([3,1],[2,4])$. In the second test case, we can show that $[3,1,2,4]$ is not the merge of two arrays of length $2$. In the third test case, $[3,2,6,1,5,7,8,4]=\mathrm{merge}([3,2,8,4],[6,1,5,7])$. In the fourth test case, $[1,2,3,4,5,6]=\mathrm{merge}([1,3,6],[2,4,5])$, for example. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) l = [int(x) for x in input().split()] cur = l[0] cll = 1 blocks = [] for x in l[1:]: if x > cur: blocks.append(cll) cur = x cll = 1 else: cll += 1 blocks.append(cll) poss = [[False]*(n+1) for _ in range(len(blocks) + 1)] poss[0][0] = True for i, b in enumerate(blocks): for j in range(n+1): poss[i+1][j] = poss[i][j] if b <= j: poss[i+1][j] |= poss[i][j-b] # print() # print(blocks) # for r in poss: # print(r) print("YES" if poss[len(blocks)][n] else "NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: -----Problem Statement----- A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied: - The students must be in order of non-decreasing height. - Two boys or two girls must not be adjacent to each other. You have been given the heights of the boys in the array $b$ and the heights of the girls in the array $g$. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not. For example, let's say there are $n = 3$ boys and $n = 3$ girls, where the boys' heights are $b = [5, 3, 8]$ and the girls' heights are $g = [2, 4, 6]$. These students can be arranged in the order $[g_0, b_1, g_1, b_0, g_2, b_2]$, which is $[2, 3, 4, 5, 6, 8]$. Because this is in order of non-decreasing height, and no two boys or two girls are adjacent to each other, this satisfies the conditions. Therefore, the answer is "YES". -----Input----- - The first line contains an integer, $t$, denoting the number of test cases. - The first line of each test case contains an integer, $n$, denoting the number of boys and girls in the classroom. - The second line of each test case contains $n$ space separated integers, $b_1,b_2, ... b_n$, denoting the heights of the boys. - The second line of each test case contains $n$ space separated integers, $g_1,g_2,... g_n$, denoting the heights of the girls. -----Output----- Print exactly $t$ lines. In the $i^{th}$ of them, print a single line containing "$YES$" without quotes if it is possible to arrange the students in the $i^{th}$ test case, or "$NO$" without quotes if it is not. -----Constraints----- - $1 \leq t \leq 10$ - $1 \leq n \leq 100$ - $1 \leq b_i, g_i \leq 100$ -----Sample Input----- 1 2 1 3 2 4 -----Sample Output----- YES -----EXPLANATION----- The following arrangement would satisfy the given conditions: $[b_1, g_1, b_2, g_2]$. This is because the boys and girls and separated, and the height is in non-decreasing order. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for u in range(int(input())): n=int(input()) l=list(map(int,input().split())) d=list(map(int,input().split())) ka=[] k=[] l.sort() d.sort() for i in range(n): ka.append(d[i]) ka.append(l[i]) for i in range(n): k.append(l[i]) k.append(d[i]) if(ka==sorted(ka)): print("YES") elif(k==sorted(k)): print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Give me Biscuit Sunny wants to make slices of biscuit of size c * d into identical pieces. but each piece is a square having maximum possible side length with no left over piece of biscuit. Input Format The first line contains an integer N. N lines follow. Each line contains two space separated integers c and d. which denote length and breadth of the biscuit. Constraints 1 <= N <= 1000 1 <= c,d <= 1000 Output Format N lines, each containing an integer that denotes the number of squares of maximum size, when the biscuit is cut as per the given condition. Sample Input 2 2 2 6 9 Sample Output 1 6 Explanation The 1st testcase has a biscuit whose original dimensions are 2 X 2, the biscuit is uncut and is a square. Hence the answer is 1. The 2nd testcase has a biscuit of size 6 X 9 . We can cut it into 54 squares of size 1 X 1 , 6 of size 3 X 3 . For other sizes we will have leftovers. Hence, the number of squares of maximum size that can be cut is 6. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def __gcd(a, b): # Everything divides 0 if (a == 0 or b == 0): return 0; # base case if (a == b): return a; # a is greater if (a > b): return __gcd(a - b, b); return __gcd(a, b - a); # Function to find # number of squares def NumberOfSquares(x, y): # Here in built PHP # gcd function is used s = __gcd(x, y); ans = (x * y) / (s * s); return int(ans); n=int(input()) while n: n=n-1 c,d=map(int,input().split()) print(NumberOfSquares(c, d)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A sophomore Computer Science student is frustrated with boring college lectures. Professor X agreed to give him some questions; if the student answers all questions correctly, then minimum attendance criteria will not apply to him. Professor X chooses a sequence $A_1, A_2, \ldots, A_N$ and asks $Q$ queries. In each query, the student is given an integer $P$; he has to construct a sequence $B_1, B_2, \ldots, B_N$, where $P \oplus A_i = B_i$ for each valid $i$ ($\oplus$ denotes bitwise XOR), and then he has to find the number of elements of this sequence which have an even number of $1$-s in the binary representation and the number of elements with an odd number of $1$-s in the binary representation. Help him answer the queries. -----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 $Q$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. - $Q$ lines follow. Each of these lines contains a single integer $P$ describing a query. -----Output----- For each query, print a single line containing two space-separated integers ― the number of elements with an even number of $1$-s and the number of elements with an odd number of $1$-s in the binary representation. -----Constraints----- - $1 \le T \le 100$ - $1 \le N, Q \le 10^5$ - $ T \cdot (N+Q) \leq 4 \cdot 10^6 $ - $1 \le A_i \le 10^8$ for each valid $i$ - $1 \le P \le 10^5$ The input/output is quite large, please use fast reading and writing methods. -----Subtasks----- Subtask #1 (30 points): $N, Q \le 1,000$ Subtask #2 (70 points): original constraints -----Example Input----- 1 6 1 4 2 15 9 8 8 3 -----Example Output----- 2 4 -----Explanation----- Example case 1: The elements of the sequence $B$ are $P \oplus 4 = 7$, $P \oplus 2 = 1$, $P \oplus 15 = 12$, $P \oplus 9 = 10$, $P \oplus 8 = 11$ and $P \oplus 8 = 11$. The elements which have an even number of $1$-s in the binary representation are $12$ and $10$, while the elements with an odd number of $1$-s are $7$, $1$, $11$ and $11$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from sys import stdin, stdout for _ in range(int(stdin.readline())): n, q = list(map(int, stdin.readline().split())) arr = list(map(int, stdin.readline().split()))[:n] od = ev = 0 for i in arr: if bin(i).count('1')%2==0: ev += 1 else: od += 1 for _ in range(q): p = int(stdin.readline()) if bin(p).count('1')%2==0: stdout.write(str(ev) + " " + str(od) + "\n") else: stdout.write(str(od) + " " + str(ev) + "\n") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mohit(Ex GenSec ) is the most active member of the roasting club who loves giving tasks to other members. One day he observed that none of the members were paying attention to the online classes, so he decided to have some fun and overcome the boring lectures. He wrote N numbers on the virtual board (where the first number is 1, the last one is N and the ith number being i). Then he asked M questions to every other member of the club. In each question, a number K was given by Mohit and the members had to give a single integer as an answer which will be the sum of all numbers present on the whiteboard. There are some conditions that every member has to follow while answering. - If K is already present on the whiteboard then swap the first and last number. - Otherwise, replace the last number with K. -----Input:----- - First-line will consist of space-separated integers N and M. The board will contain the list of numbers from 1 to N and M is the number of questions that Mohit will ask. - Next M lines contain the number Ki, which will be provided by Mohit and (1<=i<=M). -----Output:----- For each question, report the sum of all integers present -----Constraints----- - $1 \leq N,M \leq 1000000$ - $2 \leq K \leq 10^9$ -----Sample Input:----- 5 4 7 12 10 1 -----Sample Output:----- 17 22 20 20 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()) l = n f = 1 s = ((n)*(n+1))//2 - l - f for _ in range(m): k = int(input()) if 2 <= k <= n-1 or k in [f, l]: l, f = f, l else: l = k print(s+l+f) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Our chef has recently opened a new restaurant with a unique style. The restaurant is divided into K compartments (numbered from 1 to K) and each compartment can be occupied by at most one customer. Each customer that visits the restaurant has a strongly preferred compartment p (1 ≤ p ≤ K), and if that compartment is already occupied, then the customer simply leaves. Now obviously, the chef wants to maximize the total number of customers that dine at his restaurant and so he allows (or disallows) certain customers so as to achieve this task. You are to help him with this. Given a list of N customers with their arrival time, departure time and the preferred compartment, you need to calculate the maximum number of customers that can dine at the restaurant. -----Input----- The first line contains an integer T denoting the number of test cases. Each of the next T lines contains two integers N and K , the number of customers that plan to visit the chef's restaurant and the number of compartments the restaurant is divided into respectively. Each of the next N lines contains three integers si, fi and pi , the arrival time, departure time and the strongly preferred compartment of the ith customer respectively. Note that the ith customer wants to occupy the pith compartment from [si, fi) i.e the ith customer leaves just before fi so that another customer can occupy that compartment from fi onwards. -----Output----- For every test case, print in a single line the maximum number of customers that dine at the restaurant. -----Constraints----- - 1 ≤ T ≤ 30 - 0 ≤ N ≤ 105 - 1 ≤ K ≤ 109 - 0 ≤ si < fi ≤ 109 - 1 ≤ pi ≤ K -----Example----- Input: 2 3 3 1 3 1 4 6 2 7 10 3 4 2 10 100 1 100 200 2 150 500 2 200 300 2 Output: 3 3 -----Explanation----- Example case 1. All three customers want different compartments and hence all 3 can be accommodated. Example case 2. If we serve the 1st, 2nd and 4th customers, then we can get a maximum of 3. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python try: for _ in range(int(input())): N, K = map(int, input().split()) cell = [] count = 0 l = [] for __ in range(N): inserted = list(map(int, input().split())) cell.append(inserted) cell.sort(key=lambda x: x[1]) time = {} for number in cell: if number[2] not in time: time[number[2]] = number[1] count += 1 elif number[0] >= time[number[2]]: time[number[2]] = number[1] count += 1 print(count) except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. [Image] Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s_1 with k_1 elements and Morty's is s_2 with k_2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins. Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game. -----Input----- The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game. The second line contains integer k_1 followed by k_1 distinct integers s_{1, 1}, s_{1, 2}, ..., s_{1, }k_1 — Rick's set. The third line contains integer k_2 followed by k_2 distinct integers s_{2, 1}, s_{2, 2}, ..., s_{2, }k_2 — Morty's set 1 ≤ k_{i} ≤ n - 1 and 1 ≤ s_{i}, 1, s_{i}, 2, ..., s_{i}, k_{i} ≤ n - 1 for 1 ≤ i ≤ 2. -----Output----- In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. -----Examples----- Input 5 2 3 2 3 1 2 3 Output Lose Win Win Loop Loop Win Win Win Input 8 4 6 2 3 4 2 3 6 Output Win Win Win Win Win Win Win Lose Win Lose Lose Win Lose Lose The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python f = lambda: list(map(int, input().split()))[1:] n = int(input()) s, p, q = [], [], [] for x in [0, 1]: r = f() s.append(r) t = [len(r)] * n t[0] = 0 p.append(t) q.append((x, 0)) while q: x, i = q.pop() y = 1 - x for d in s[y]: j = (i - d) % n if p[y][j] < 1: continue p[y][j] = -1 for d in s[x]: k = (j - d) % n if p[x][k] < 1: continue p[x][k] -= 1 if p[x][k] == 0: q.append((x, k)) for x in [0, 1]: print(*[['Lose', 'Loop', 'Win'][min(q, 1)] for q in p[x][1:]]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots. For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of damage. In order to break the shield Dante has to deal exactly c units of damage. Find out if this is possible. -----Input----- The first line of the input contains three integers a, b, c (1 ≤ a, b ≤ 100, 1 ≤ c ≤ 10 000) — the number of units of damage dealt by Ebony gun and Ivory gun, and the total number of damage required to break the shield, respectively. -----Output----- Print "Yes" (without quotes) if Dante can deal exactly c damage to the shield and "No" (without quotes) otherwise. -----Examples----- Input 4 6 15 Output No Input 3 2 7 Output Yes Input 6 11 6 Output Yes -----Note----- In the second sample, Dante can fire 1 bullet from Ebony and 2 from Ivory to deal exactly 1·3 + 2·2 = 7 damage. In the third sample, Dante can fire 1 bullet from ebony and no bullets from ivory to do 1·6 + 0·11 = 6 damage. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a, b, c = list(map(int, input().split())) p = [0] * 100000 p[0] = 1 p[a] = 1 p[b] = 1 for i in range(c + 1): if p[i]: p[i + a] = 1 p[i + b] = 1 if p[c]: print('Yes') else: print('No') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an array of n integer numbers a_0, a_1, ..., a_{n} - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. -----Input----- The first line contains positive integer n (2 ≤ n ≤ 10^5) — size of the given array. The second line contains n integers a_0, a_1, ..., a_{n} - 1 (1 ≤ a_{i} ≤ 10^9) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times. -----Output----- Print the only number — distance between two nearest minimums in the array. -----Examples----- Input 2 3 3 Output 1 Input 3 5 6 5 Output 2 Input 9 2 1 3 5 4 1 2 3 1 Output 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) A = [int(x) for x in input().split()] mn = min(A) I = [i for i in range(len(A)) if A[i] == mn] mindiff = min(I[i]-I[i-1] for i in range(1,len(I))) print(mindiff) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is a really nice and respectful person, in sharp contrast to his little brother, who is a very nasty and disrespectful person. Chef always sends messages to his friends in all small letters, whereas the little brother sends messages in all capital letters. You just received a message given by a string s. You don't know whether this message is sent by Chef or his brother. Also, the communication channel through which you received the message is erroneous and hence can flip a letter from uppercase to lowercase or vice versa. However, you know that this channel can make at most K such flips. Determine whether the message could have been sent only by Chef, only by the little brother, by both or by none. -----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 denoting the length of the string s and the maximum number of flips that the erroneous channel can make. - The second line contains a single string s denoting the message you received. -----Output----- For each test case, output a single line containing one string — "chef", "brother", "both" or "none". -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ N ≤ 100 - 0 ≤ K ≤ N - s consists only of (lowercase and uppercase) English letters -----Example----- Input 4 5 1 frauD 5 1 FRAUD 4 4 Life 10 4 sTRAWBerry Output chef brother both none -----Explanation----- Example case 1: Only one flip is possible. So it is possible that Chef sent "fraud" and the channel flipped the last character to get "frauD". However, it is not possible for the brother to have sent "FRAUD", because then it would need 4 flips. Hence the answer is "chef". Example case 2: Only one flip is possible. So it is possible that the brother sent "FRAUD" and the channel didn't flip anything. However, it is not possible for Chef to have sent "fraud", because then it would need 5 flips. Hence the answer is "brother". Example case 3: Four flips are allowed. It is possible that Chef sent "life" and the channel flipped the first character to get "Life". It is also possible that the brother sent "LIFE" and the channel flipped the last three characters to get "Life". Hence the answer is "both". Example case 4: Four flips are allowed. It is not possible that Chef sent "strawberry", because it would need five flips to get "sTRAWBerry". It is also not possible that the brother sent "STRAWBERRY", because that would also need five flips. Hence the answer is "none". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) def do(): n,k=map(int,input().split()) s=input() upper=0 lower=0 for i in s: if i.isupper(): upper+=1 else: lower+=1 if lower>k and upper<=k: print('chef') elif(upper>k and lower<=k): print('brother') elif(upper<=k and lower<=k): print('both') else: print('none') return for i in range(t): do() ```
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, \dots, a_n$, consisting of integers. You can apply the following operation to this sequence: choose some integer $x$ and move all elements equal to $x$ either to the beginning, or to the end of $a$. Note that you have to move all these elements in one direction in one operation. For example, if $a = [2, 1, 3, 1, 1, 3, 2]$, you can get the following sequences in one operation (for convenience, denote elements equal to $x$ as $x$-elements): $[1, 1, 1, 2, 3, 3, 2]$ if you move all $1$-elements to the beginning; $[2, 3, 3, 2, 1, 1, 1]$ if you move all $1$-elements to the end; $[2, 2, 1, 3, 1, 1, 3]$ if you move all $2$-elements to the beginning; $[1, 3, 1, 1, 3, 2, 2]$ if you move all $2$-elements to the end; $[3, 3, 2, 1, 1, 1, 2]$ if you move all $3$-elements to the beginning; $[2, 1, 1, 1, 2, 3, 3]$ if you move all $3$-elements to the end; You have to determine the minimum number of such operations so that the sequence $a$ becomes sorted in non-descending order. Non-descending order means that for all $i$ from $2$ to $n$, the condition $a_{i-1} \le a_i$ is satisfied. Note that 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 the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of elements. The second line of each query contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le n$) — the elements. It is guaranteed that the sum of all $n$ does not exceed $3 \cdot 10^5$. -----Output----- For each query print one integer — the minimum number of operation for sorting sequence $a$ in non-descending order. -----Example----- Input 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 Output 2 0 1 -----Note----- In the first query, you can move all $1$-elements to the beginning (after that sequence turn into $[1, 1, 1, 3, 6, 6, 3]$) and then move all $6$-elements to the end. In the second query, the sequence is sorted initially, so the answer is zero. In the third query, you have to move all $2$-elements to the beginning. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): from sys import stdin, stdout for _ in range(int(stdin.readline())): n = int(stdin.readline()) inp1 = [-1] * (n + 1) inp2 = [-1] * (n + 1) for i, ai in enumerate(map(int, stdin.readline().split())): if inp1[ai] < 0: inp1[ai] = i inp2[ai] = i inp1 = tuple((inp1i for inp1i in inp1 if inp1i >= 0)) inp2 = tuple((inp2i for inp2i in inp2 if inp2i >= 0)) n = len(inp1) ans = 0 cur = 0 for i in range(n): if i and inp1[i] < inp2[i - 1]: cur = 1 else: cur += 1 ans = max(ans, cur) stdout.write(f'{n - ans}\n') main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The garden has a tree with too many leaves on it and gardner wants to cut the unwanted leaves. This is a rooted tree, where a node $v$ is called parent of another node $u$, if there exists a directed edge from $v$ to $u$. Leaf node is a node with no outgoing edges. Gardner cuts the tree in a peculiar way: - For each parent node(which has a valid leaf node attached to it), he cuts $x$ leaf nodes, such that $x$ is a multiple of 3. Example : If a parent node has 7 leaf nodes, 6 leaf nodes will be cut and 1 will be left. - If a parent has all its leaf nodes cut, only then the parent node itself becomes a new leaf node. If new leaf nodes are created, Gardner repeats step 1 until he can cut no more leaf nodes. After completing all operations, gardner wants to know the minimum number of nodes left on the tree. It is guaranteed that the given input is a rooted tree. The root of the tree is vertex 1. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - First line of each testcase contains an integer $n$, the number of vertices in the tree. - Second line of each testcase contains array $A$ of size $n-1$, where $A_{i}(1≤i≤n-1)$, is the index of the parent of the $(i+1)^{th}$ vertex. -----Output:----- For each testcase, output single integer, the number of nodes finally left on the tree. -----Constraints----- - $1 \leq T \leq 10$ - $2 \leq n \leq 10^5$ - $1 \leq A_i \leq i$ -----Sample Input:----- 1 13 1 1 1 1 1 4 3 4 4 3 4 3 -----Sample Output:----- 4 -----EXPLANATION:----- The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def dfs(node): nonlocal adj,leaf val=0 flag=0 for i in adj[node]: x= dfs(i) val+=x if x==0: flag=1 leaf+=val-val%3 if val%3==0 and flag==0: return 1 else: return 0 for _ in range(int(input())): n=int(input()) adj=[[] for i in range(n+2)] arr=[int(i) for i in input().split()] leaf=0 #print(adj) for i in range(2,n+1): #print(i,arr[i-2]) adj[arr[i-2]].append(i) dfs(1) print(n-leaf) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The flag of Berland is such rectangular field n × m that satisfies following conditions: Flag consists of three colors which correspond to letters 'R', 'G' and 'B'. Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color. Each color should be used in exactly one stripe. You are given a field n × m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes). -----Input----- The first line contains two integer numbers n and m (1 ≤ n, m ≤ 100) — the sizes of the field. Each of the following n lines consisting of m characters 'R', 'G' and 'B' — the description of the field. -----Output----- Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes). -----Examples----- Input 6 5 RRRRR RRRRR BBBBB BBBBB GGGGG GGGGG Output YES Input 4 3 BRG BRG BRG BRG Output YES Input 6 7 RRRGGGG RRRGGGG RRRGGGG RRRBBBB RRRBBBB RRRBBBB Output NO Input 4 4 RRRR RRRR BBBB GGGG Output NO -----Note----- The field in the third example doesn't have three parralel stripes. Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights — 2, 1 and 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n,m=list(map(int,input().split())) f=[input() for _ in range(n)] def clr(ss): cc = None for s in ss: for c in s: if cc is None: cc = c elif cc != c: return None return cc if n%3 == 0: s = set() for i in range(0,n,n//3): ret = clr(f[i:i+n//3]) if ret is None: continue s.add(ret) if len(s) == 3: print('YES') return if m%3 == 0: s = set() for j in range(0,m,m//3): ff = [] for i in f: ff.append(i[j:j+m//3]) ret = clr(ff) if ret is None: continue s.add(ret) if len(s) == 3: print('YES') return print('NO') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A beautiful sequence is defined as a sequence that do not have any repeating elements in it. You will be given any random sequence of integers, and you have to tell whether it is a beautiful sequence or not. -----Input:----- - The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows. - The next line of the input contains a single integer $N$. $N$ denotes the total number of elements in the sequence. - The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ denoting the sequence. -----Output:----- - Print "prekrasnyy"(without quotes) if the given sequence is a beautiful sequence, else print "ne krasivo"(without quotes) Note: each test case output must be printed on new line -----Constraints:----- - $1 \leq T \leq 10^2$ - $1 \leq N \leq 10^3$ - $1 \leq A1, A2, A3...An \leq 10^5$ -----Sample Input:----- 2 4 1 2 3 4 6 1 2 3 5 1 4 -----Sample Output:----- prekrasnyy ne krasivo -----Explanation:----- - As 1st sequence do not have any elements repeating, hence it is a beautiful sequence - As in 2nd sequence the element 1 is repeated twice, hence it is not a beautiful sequence The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) l = [] for i in range(0, len(arr)): for j in range(i+1, len(arr)): if(arr[i] == arr[j]): l.append(arr[j]) if (len(l) ==0): print("prekrasnyy") else: print("ne krasivo") ```
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$, which initially is a permutation of numbers from $1$ to $n$. In one operation, you can choose an index $i$ ($1 \leq i < n$) such that $a_i < a_{i + 1}$, and remove either $a_i$ or $a_{i + 1}$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $[1, 3, 2]$, you can choose $i = 1$ (since $a_1 = 1 < a_2 = 3$), then either remove $a_1$ which gives the new array $[3, 2]$, or remove $a_2$ which gives the new array $[1, 2]$. Is it possible to make the length of this array equal to $1$ with these operations? -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 2 \cdot 10^4$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $n$ ($2 \leq n \leq 3 \cdot 10^5$)  — the length of the array. The second line of each test case contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \leq a_i \leq n$, $a_i$ are pairwise distinct) — elements of the array. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $3 \cdot 10^5$. -----Output----- For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so. -----Example----- Input 4 3 1 2 3 4 3 1 2 4 3 2 3 1 6 2 4 6 1 3 5 Output YES YES NO YES -----Note----- For the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation): $[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}]$ $[\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}]$ $[\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3}, \textbf{5}] \rightarrow [\text{4}, \textbf{1}, \textbf{5}] \rightarrow [\textbf{4}, \textbf{5}] \rightarrow [\text{4}]$ 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 case in range(t): n = int(input()) arr = list(map(int, input().split())) if arr[-1] > arr[0]: print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today is Chef's birthday. His mom has surprised him with truly fruity gifts: 2 fruit baskets. The first basket contains N apples, and the second one contains M oranges. Chef likes apples and oranges very much but he likes them equally, and therefore, wants to have the minimum possible difference between the number of apples and oranges he has. To do so, he can purchase 1 apple or 1 orange by paying exactly 1 gold coin (that's some expensive fruit, eh?). Chef can purchase fruits at most K times (as he has only K gold coins in his pocket) to make the difference the minimum possible. Our little Chef is busy in celebrating his birthday to the fullest, and therefore, he has handed this job to his best friend — you. Can you help him by finding the minimum possible difference he can achieve between the number of apples and orange he owns? -----Input----- The first line of input contains a single integer T denoting the number of test cases. The first and only line of each test case contains 3 space separated integers — N, M and K — denoting the number of apples, number of oranges, and number of gold coins our little Chef has. -----Output----- For each test case, output the minimum possible difference between the number of apples and oranges that Chef can achieve. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N, M, K ≤ 100 -----Example-----Input 3 3 4 1 5 2 1 3 4 3 Output 0 2 0 -----Explanation----- - Test 1: Chef will buy 1 apple by paying 1 gold coin and will have equal number of apples and oranges. - Test 2: Chef will buy 1 orange by paying 1 gold coin and will have 5 apples and 3 oranges. 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())): a,o,g=map(int,input().split()) while g>0: if a<o: a+=1 g-=1 elif o<a: o+=1 g-=1 else: break print(abs(a-o)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Rodriguez is a happy and content farmer. He has got a square field of side length $x$. Miguel, his son has himself grown into a man and his father wants to gift him something out of which he can make a living. So he gift's his son a square piece of land cut out from a corner of his field of side length $ y (y < x) $ leaving him with a L-shaped land. But in Spanish tradition, it is considered inauspicious to own something which is prime in number. This worries Rodriguez as he doesn't want his left out area to be a prime number leading to bad luck. Find whether the spilt will be in terms with the tradition leaving Rodriguez happy. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains two integers $x, y$. -----Output:----- Print YES if Rodriguez will be happy. Otherwise print NO. -----Constraints----- - $1 \leq T \leq 5$ - $1 \leq y < x \leq 100000000000$ -----Sample Input:----- 2 7 5 6 5 -----Sample Output:----- YES NO -----EXPLANATION:----- In case 1 : Left out area is 24, which is not prime. In case 2: Left out area is 11, which is prime. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import sqrt def isPrime(n): for i in range(2, int(sqrt(n))+1): if(n%i==0): return True return False ans = [] for _ in range(int(input())): x, y = map(int, input().split()) ans.append('NO' if(isPrime(x**2-y**2)) else 'YES') print('\n'.join(ans)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Akshay is interested in mathematics, one day he came across a problem of modulus operator.He has a list of M integers say arr[M] and has to find all integers K such that : - K > 1 - arr[1]%K = arr[2]%K = arr[3]%K = … = arr[M]%K where '%' is a modulus operator. Help Akshay to find all such K's. -----Input:----- - First line of input contains an integer M. Then M lines follow each containing one integer of the list. Input data is such that at least one integer K will always exist. -----Output:----- - Output all possible integers K separated by space in increasing order. -----Constraints----- - 2<= M <=100 - 1< value of each integer <109 - All integers will be distinct -----Sample Input:----- 3 38 6 34 -----Sample Output:----- 2 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python l = [] for _ in range(int(input())): l.append(int(input())) for i in range(2,max(l)): r = [x%i for x in l] if len(set([x%i for x in l])) == 1: print(i, end = ' ') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first. On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems. Determine the index of day when Polycarp will celebrate the equator. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of days to prepare for the programming contests. The second line contains a sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10\,000$), where $a_i$ equals to the number of problems, which Polycarp will solve on the $i$-th day. -----Output----- Print the index of the day when Polycarp will celebrate the equator. -----Examples----- Input 4 1 3 2 1 Output 2 Input 6 2 2 2 2 2 2 Output 3 -----Note----- In the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $4$ out of $7$ scheduled problems on four days of the training. In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $6$ out of $12$ scheduled problems on six days of the training. 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 = int(input()) a = list(int(x) for x in input().split()) s = sum(a) t = 0 for i in range(n): t += a[i] if 2 * t >= s: print(i + 1) return main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity. Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2^{i} - 1 liters and costs c_{i} roubles. The number of bottles of each type in the store can be considered infinite. You want to buy at least L liters of lemonade. How many roubles do you have to spend? -----Input----- The first line contains two integers n and L (1 ≤ n ≤ 30; 1 ≤ L ≤ 10^9) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively. The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^9) — the costs of bottles of different types. -----Output----- Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade. -----Examples----- Input 4 12 20 30 70 90 Output 150 Input 4 3 10000 1000 100 10 Output 10 Input 4 3 10 100 1000 10000 Output 30 Input 5 787787787 123456789 234567890 345678901 456789012 987654321 Output 44981600785557577 -----Note----- In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles. In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles. In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python 3 # Copyright (C) 2017 Sayutin Dmitry. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; version 3 # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. def solve(a, l): if l == 0: return 0 if l == 1: return a[0] k = 0 while (2 ** k) < l: k += 1 return min(a[k], a[k - 1] + solve(a, l - (2 ** (k - 1)))) def main(): n, l = list(map(int, input().split())) a = list(map(int, input().split())) for i in range(n - 2, -1, -1): if a[i] > a[i + 1]: a[i] = a[i + 1] for i in range(1, n): if a[i] > 2 * a[i - 1]: a[i] = 2 * a[i - 1] while len(a) < 35: a.append(2 * a[len(a) - 1]) #print(a) print(solve(a, l)) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: N Soldiers are lined up for a memory test. They are numbered from 0 to N-1 from left to right. In the test, there are M rounds. In each round, Captain selects one position. Soldier at that position will be numbered 0. All the soldiers to the right of selected position will be numbered one greater than the soldier to his left. All the soldiers to the left of selected position will be numbered one greater than the soldier to his right. eg. if N = 6 and selected position is 3, then the numbering will be [3, 2, 1, 0, 1, 2]. After M rounds, Captain asked each soldier to shout out the greatest number he was assigned during the M rounds. In order to check the correctness, Captain asked you to produce the correct values for each soldier (That is the correct value each soldier should shout out). -----Input----- The first line of the input contains an integer T denoting the number of test cases. First line of each test case contains two integers, N and M. Second line of each test case contains M integers, the positions selected by Captain, in that order. -----Output----- For each test case, output one line with N space separated integers. -----Constraints----- - 1 ≤ T ≤ 10^4 - 1 ≤ N ≤ 10^5 - 1 ≤ M ≤ 10^5 - 1 ≤ Sum of N over all testcases ≤ 10^5 - 1 ≤ Sum of M over all testcases ≤ 10^5 - 0 ≤ Positions selected by captain ≤ N-1 -----Example----- Input 2 4 1 1 6 2 2 3 Output 1 0 1 2 3 2 1 1 2 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python test = int(input()) for _ in range(test): n, m = map(int, input().split()) indexArray = list(map(int, input().split())) mini = min(indexArray) maxi = max(indexArray) result = n*[0] for i in range(n): result[i] = max(maxi - i, i - mini) print(result[i], end=" ") print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: -----Problem description----- As a holiday gift, Tojo received a probability problem. The problem read as follows Consider an N by M grid. Rows are numbered 1 to N, from top to bottom. Columns are numbered 1 to M, from left to right. You are initially at cell (1, 1) and want to go to cell (N, M). From any cell you can move to the cell below it or to the cell right to it. You should never go out of the grid. At any point you should consider all the possibilities of movement with equal probability Let P[i][j] be the probability of visiting cell (i, j). You need to calculate the sum of P[i][j] for 1 ≤ i ≤ N, 1 ≤ i ≤ M. As we all know, Tojo really hates probability related problems. He wants you to solve this task -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.Only line of each test case has two integer N and M. -----Output----- For each test case, output a single line containing the required answer. Answers within an absolute or relative error of 10-6 will be accepted. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ N ≤ 1000 - 1 ≤ M ≤ 1000 -----Example----- Input: 2 2 2 1 6 Output: 3.000000 6.000000 -----Explanation----- Example case 1 Probability matrix P for N=2, M=2 is 1.0 0.5 0.5 1.0 You are at (1, 1) initially. So the probablity of visiting (1, 1) is 1. At (1, 1) you have 2 options, move below to (2, 1) or to right cell (1, 2). Probablity of going to (1, 2) is 0.5. Probability of going to (2, 1) is 0.5. You always end up at (2, 2), so P[2][2] is 1. Required sum = 1.0 + 0.5 + 0.5 + 1.0 = 3.0 Example case 2 Probability matrix P for N=1, M=6 is 1.0 1.0 1.0 1.0 1.0 1.0 Because at any position there is only one possible next position. 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 for _ in range(int(input())): N,M=[int(a) for a in input().split()] print(float(N+M-1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chefland is a grid with N$N$ rows and M$M$ columns. Each cell of this grid is either empty or contains a house. The distance between a pair of houses is the Manhattan distance between the cells containing them. For each d$d$ between 1$1$ and N+M−2$N+M-2$ inclusive, Chef wants to calculate the number of unordered pairs of distinct houses with distance equal to d$d$. Please help him! -----Input----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains two space-separated integers N$N$ and M$M$. - N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains a binary string with length M$M$; for each j$j$ (1≤j≤M$1 \le j \le M$), the j$j$-th character of this string is '1' if the cell in the i$i$-th row and j$j$-th column contains a house or '0' if it is empty. -----Output----- For each test case, print a single line containing N+M−2$N+M-2$ space-separated integers. For each valid i$i$, the i$i$-th integer should denote the number of pairs with distance i$i$. -----Constraints----- - 1≤T≤3$1 \le T \le 3$ - 2≤N,M≤300$2 \le N, M \le 300$ -----Subtasks----- Subtask #1 (50 points): N,M≤50$N, M \le 50$ Subtask #2 (50 points): original constraints -----Example Input----- 1 3 4 0011 0000 0100 -----Example Output----- 1 0 1 1 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for a in range(int(input())): N,M=map(int,input().split()) b=[] for o in range(N): b.append(input()) c=[] for d in b: f=[] for e in range(len(d)): if d[e]=='1': f.append(e) c.append(f) i=[] for g in range(len(c)): for h in range(len(c[g])): for j in range(len(c)): for k in range(len(c[j])): if (j>g) or(j==g and k>h): if c[g][h]-c[j][k]>=0: i.append(c[g][h]-c[j][k]+j-g) else: i.append(-1*(c[g][h]-c[j][k])+j-g) l=[m for m in range(1,N+M-1)] for n in l: print(i.count(n),end=' ') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: For an array $b$ of length $m$ we define the function $f$ as $ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $ where $\oplus$ is bitwise exclusive OR. For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$ You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 5000$) — the length of $a$. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$) — the elements of the array. The third line contains a single integer $q$ ($1 \le q \le 100\,000$) — the number of queries. Each of the next $q$ lines contains a query represented as two integers $l$, $r$ ($1 \le l \le r \le n$). -----Output----- Print $q$ lines — the answers for the queries. -----Examples----- Input 3 8 4 1 2 2 3 1 2 Output 5 12 Input 6 1 2 4 8 16 32 4 1 6 2 5 3 4 1 2 Output 60 30 12 3 -----Note----- In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment. In second sample, optimal segment for first query are $[3,6]$, for second query — $[2,5]$, for third — $[3,4]$, for fourth — $[1,2]$. 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, = map(int, input().split()) dp = [[0 for i in range(n + 1)] for j in range(n + 1)] for i in range(n): dp[0][i] = a[i] for i in range(1, n): for j in range(n - i + 1): dp[i][j] = dp[i - 1][j] ^ dp[i - 1][j + 1] for i in range(1, n): for j in range(n - i): dp[i][j] = max(dp[i][j], dp[i - 1][j], dp[i - 1][j + 1]) for i in range(int(input())): l, r = map(int, input().split()) print(dp[r - l][l - 1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chang's new maths teacher is very enthusiastic about making sure that students understand the concept rather than remembering it. On her first day at teaching, she gives an assignment to all the students to test their potential. Chang wants to demonstrate that he understands the concept rather than rote learning. Help Chang in doing this by solving the hardest problem in the assignment. The problem is written as follows. A perfect function is defined in the following manner. - F(x, y) = x2 + y for 1 ≤ x ≤ A, 1 ≤ y ≤ B - F(x, y) = 2 otherwise Find the number of integral pairs (x, y) such that F(x, y) is a perfect square. -----Input----- First and the only line of the input contains two single space separated integers A and B. -----Output----- Output a single integer indicating the output to the only test case. -----Constraints----- - 1 ≤ A, B ≤ 106 -----Example----- Input: 4 4 Output: 1 -----Explanation----- Example case 1. (1, 3) is the only pair such that x = 1, y = 3 satisfying x <= 4 and y <= 4. 1^2 + 3 = 4 which is a perfect square. 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 a, b = map(int, input().split()) pairs = 0 for i in range(1, a+1): for j in range(1, b+1): root = sqrt(i**2 + j) if not root - int(root): pairs += 1 print(pairs) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A plot of land can be described by $M x N$ dots such that horizontal and vertical distance between any two dots is 10m. Mr. Wolf would like to build a house in the land such that all four sides of the house are equal. Help Mr. Wolf to find the total number of unique positions where houses can be built. Two positions are different if and only if their sets of four dots are different. -----Input:----- The first line of the input gives the number of test cases, $T$. $T$ lines follow. Each line has two integers $M$ and $N$: the number of dots in each row and column of the plot, respectively. -----Output:----- For each test case, output one single integer containing the total number of different positions where the house can be built. -----Constraints----- - $1 \leq T \leq 100$ - $2 \leq M \leq 10^9$ - $2 \leq N \leq 10^9$ -----Sample Input:----- 4 2 4 3 4 4 4 1000 500 -----Sample Output:----- 3 10 20 624937395 -----EXPLANATION:----- Map 1 Map 2 Map 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from sys import stdin,stdout,setrecursionlimit from math import ceil mod = 1000000007 t = int(stdin.readline()) for _ in range(t): m,n = list(map(int,input().split())) if m < n: m,n = n,m y = n-1 s1 = ((y*(y+1)) //2)%mod s2 = ((y*(y+1)*(2*y+1)) //6)%mod s3 = ((y*y*(y+1)*(y+1)) //4)%mod ans = (m*n*s1 - (m+n)*s2+s3)%mod # ans = (m*(m+1)*(2*m*n + 4*n + 2 - m*m - m)//12) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams. Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry. However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that the items are split into two groups, and one group contains exactly K items. Then Chef will carry the heavier group, and his son will carry the other group. Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the maximum possible difference between the weight carried by him and the weight carried by the kid. -----Input:----- The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each test contains two space-separated integers N and K. The next line contains N space-separated integers W1, W2, ..., WN. -----Output:----- For each test case, output the maximum possible difference between the weights carried by both in grams. -----Constraints:----- - 1 ≤ T ≤ 100 - 1 ≤ K < N ≤ 100 - 1 ≤ Wi ≤ 100000 (105) -----Example:----- Input: 2 5 2 8 4 5 2 10 8 3 1 1 1 1 1 1 1 1 Output: 17 2 -----Explanation:----- Case #1: The optimal way is that Chef gives his son K=2 items with weights 2 and 4. Chef carries the rest of the items himself. Thus the difference is: (8+5+10) − (4+2) = 23 − 6 = 17. Case #2: Chef gives his son 3 items and he carries 5 items himself. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): T = int(input()) for t in range(T): N,K = map(int, input().split()) W = list(map(int, input().split())) W.sort() if 2*K > N: K = N - K kid = sum(W[:K]) dad = sum(W[K:]) diff = dad - kid print(diff) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: $Gogi$, $Tapu$ and $Sonu$ are the elite members of $Tapu$ $Sena$. $Gogi$ is always stoned and asks absurd questions, But this time he asked a question which seems to be very serious and interesting. $Tapu$ wants to solve this question to impress $Sonu$. He gave an array of length N to $Tapu$, $Tapu$ can perform the following operations exactly once: - Remove any subarray from the given array given the resulting array formed after the removal is non-empty. - Reverse the whole array. Remember you can’t shuffle the elements of the array. Tapu needs to find out the maximum possible GCD of all the numbers in the array after applying the given operations exactly once. Tapu is very weak at programming, he wants you to solve this problem so that he can impress $Sonu$. -----Input:----- - The first line contains $T$, the number of test cases. - For each test case -FIrst line contains $N$. - Last line contains $N$ numbers of the array. -----Output:----- A single integer in a new line, maximum possible GCD. -----Constraints----- - $1 \leq T \leq 10^2$ - $1 \leq N \leq 10^4$ - $1 \leq a[i] \leq 10^9$ Summation of N for all testcases is less than $10^6$ -----Sample Input 1:----- 1 1 2 -----Sample Output 1:----- 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) gcd = max(a[0], a[-1]) print(gcd) except EOFError:pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an array A, consisting of N integers and an array B, consisting of M integers. The subsequence of A is the array that can be obtained by picking the elements at the arbitrary sorted set of positions from A. Your task is to count the number of such subsequences C of A that: - C contains exactly M elements. - The array (C+B) is non-decreasing. Here by + operation, we mean element-wise sum. For example, the array (4, 8, 5) plus the array (10, 20, 30) is (14, 28, 35). Formally, (C+B) is an array of size M such that (C+B)i = Ci + Bi. In case some subsequence appears more that once, you should counts it as many times as it appears. Formally, two subarrays of an array a, (ai_1, ai_2, ... ,ai_n) and (aj_1, aj_2, ... ,aj_m) will be considered different if either their lengths are different i.e. n != m or there exists an index k such that such that i_k != j_k. Since the answer can be very large, we ask you to calculate it, modulo 109+7. -----Input----- The first line of input contains a pair of space separated integers N and M, denoting the number of elements in the array A and the number of elements in the array B. The second line contains N space-separated integers Ai, denoting the array A. The third line contains M space-separated integers Bj, denoting the array B. -----Output----- Output a single line containing the number of subsequences C as asked in the problem, modulo 109+7. -----Constraints----- - 1 ≤ Ai, Bi ≤ 109 - 1 ≤ M ≤ N -----Subtasks----- - Subtask #1 (33 points): 1 ≤ N ≤ 50, 1 ≤ M ≤ 5 - Subtask #2 (33 points): 1 ≤ N ≤ 500, 1 ≤ M ≤ 50 - Subtask #3 (34 points): 1 ≤ N ≤ 2000, 1 ≤ M ≤ 1000 -----Example----- Input #1: 5 3 1 5 2 4 7 7 9 6 Output #1: 4 Input #2: 4 2 7 7 7 7 3 4 Output #2: 6 -----Explanation----- Example case 1. The suitable subsequences are (1, 2, 7), (1, 4, 7), (5, 4, 7), (2, 4, 7). Example case 2. The suitable subsequence is (7, 7), and it appears 6 times: - at indices (1, 2) - at indices (1, 3) - at indices (1, 4) - at indices (2, 3) - at indices (2, 4) - at indices (3, 4) So, the answer is 6. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python mod =(10**9)+7 n,m = list(map(int,input().split())) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] dp = [] for i in range(n): dp += [[0]*m] dp[-1][-1]=1 for i in range(n-2,-1,-1): dp[i][-1]=1 for j in range(m-1): x = (a[i]+b[j])-(b[j+1]) temp = 0 for k in range(i+1,n): if(a[k]>=x): temp += dp[k][j+1] dp[i][j]=temp ans = 0 for i in range(n): ans += dp[i][0] print(ans%mod) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given two binary strings $a$ and $b$ of the same length. You can perform the following two operations on the string $a$: Swap any two bits at indices $i$ and $j$ respectively ($1 \le i, j \le n$), the cost of this operation is $|i - j|$, that is, the absolute difference between $i$ and $j$. Select any arbitrary index $i$ ($1 \le i \le n$) and flip (change $0$ to $1$ or $1$ to $0$) the bit at this index. The cost of this operation is $1$. Find the minimum cost to make the string $a$ equal to $b$. It is not allowed to modify string $b$. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the length of the strings $a$ and $b$. The second and third lines contain strings $a$ and $b$ respectively. Both strings $a$ and $b$ have length $n$ and contain only '0' and '1'. -----Output----- Output the minimum cost to make the string $a$ equal to $b$. -----Examples----- Input 3 100 001 Output 2 Input 4 0101 0011 Output 1 -----Note----- In the first example, one of the optimal solutions is to flip index $1$ and index $3$, the string $a$ changes in the following way: "100" $\to$ "000" $\to$ "001". The cost is $1 + 1 = 2$. The other optimal solution is to swap bits and indices $1$ and $3$, the string $a$ changes then "100" $\to$ "001", the cost is also $|1 - 3| = 2$. In the second example, the optimal solution is to swap bits at indices $2$ and $3$, the string $a$ changes as "0101" $\to$ "0011". The cost is $|2 - 3| = 1$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try : #raise ModuleNotFoundError import numpy def dprint(*args, **kwargs): print(*args, **kwargs, file=sys.stderr) dprint('debug mode') except ModuleNotFoundError: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId>0: dprint('use input', inId) sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件 if outId>0: dprint('use output', outId) sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件 atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit N, = getIntList() s1 = input() +'0' s2 = input() +'0' res = 0 i = 0 while i<N: if s1[i] != s2[i]: if s1[i+1] == s2[i] and s2[i+1] == s1[i]: res+=1 i+=2 continue res+=1 i+=1 print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program. Program is very simple, Given two integers A and B, write a program to add these two numbers. -----Input----- The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains two Integers A and B. -----Output----- For each test case, add A and B and display it in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 0 ≤ A,B ≤ 10000 -----Example----- Input 3 1 2 100 200 10 40 Output 3 300 50 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #Note that it's python3 Code. Here, we are using input() instead of raw_input(). #You can check on your local machine the version of python by typing "python --version" in the terminal. #Read the number of test cases. T = int(input()) for tc in range(T): # Read integers a and b. (a, b) = list(map(int, input().split(' '))) ans = a + b print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements. Right now he has a map of some imaginary city with $n$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once. One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them. Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $u$ and $v$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $w$ that the original map has a tunnel between $u$ and $w$ and a tunnel between $w$ and $v$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map. -----Input----- The first line of the input contains a single integer $n$ ($2 \leq n \leq 200\,000$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $n - 1$ lines contains two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i \ne v_i$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $n$ stations and $n - 1$ tunnels form a tree. -----Output----- Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map. -----Examples----- Input 4 1 2 1 3 1 4 Output 6 Input 4 1 2 2 3 3 4 Output 7 -----Note----- In the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $6$. In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $(1, 4)$. For these two stations the distance 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 main(): def countchildren(graph,vert,memo,pard=None): dumi=0 for child in graph[vert]: if child!=pard: if len(graph[child])==1: memo[child]=0 else: memo[child]=countchildren(graph,child,memo,vert)[0] dumi+=memo[child]+1 return((dumi,memo)) n=int(input()) neigh=[] for i in range(n): neigh.append([]) for i in range(n-1): a,b=map(int,input().split()) neigh[a-1].append(b-1) neigh[b-1].append(a-1) same=1 layer=[0] pars=[None] j=0 while layer!=[]: j+=1 newlayer=[] newpars=[] for i in range(len(layer)): for vert in neigh[layer[i]]: if vert!=pars[i]: newlayer.append(vert) newpars.append(layer[i]) layer=newlayer pars=newpars if j%2==0: same+=len(layer) bipartite=same*(n-same) info=countchildren(neigh,0,[None]*n)[1] dist=0 for guy in info: if guy!=None: dist+=(guy+1)*(n-guy-1) print((dist+bipartite)//2) import sys import threading sys.setrecursionlimit(2097152) threading.stack_size(134217728) main_thread=threading.Thread(target=main) main_thread.start() main_thread.join() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters $s_i$ and $s_{i+1}$, and if $s_i$ is 1 and $s_{i + 1}$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing. Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $s$ as clean as possible. He thinks for two different strings $x$ and $y$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner. Now you should answer $t$ test cases: for the $i$-th test case, print the cleanest possible string that Lee can get by doing some number of moves. Small reminder: if we have two strings $x$ and $y$ of the same length then $x$ is lexicographically smaller than $y$ if there is a position $i$ such that $x_1 = y_1$, $x_2 = y_2$,..., $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$. -----Input----- The first line contains the integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Next $2t$ lines contain test cases — one per two lines. The first line of each test case contains the integer $n$ ($1 \le n \le 10^5$) — the length of the string $s$. The second line contains the binary string $s$. The string $s$ is a string of length $n$ which consists only of zeroes and ones. It's guaranteed that sum of $n$ over test cases doesn't exceed $10^5$. -----Output----- Print $t$ answers — one per test case. The answer to the $i$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero). -----Example----- Input 5 10 0001111111 4 0101 8 11001101 10 1110000000 1 1 Output 0001111111 001 01 0 1 -----Note----- In the first test case, Lee can't perform any moves. In the second test case, Lee should erase $s_2$. In the third test case, Lee can make moves, for example, in the following order: 11001101 $\rightarrow$ 1100101 $\rightarrow$ 110101 $\rightarrow$ 10101 $\rightarrow$ 1101 $\rightarrow$ 101 $\rightarrow$ 01. 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())): # a, b = map(int, input().split()) n = int(input()) # arr = list(map(int, input().split())) s = input() l = 0 r = n - 1 if s.count('0') == n: print(s) continue if s.count('1') == n: print(s) continue while s[l] == '0': l += 1 while s[r] == '1': r -= 1 if r <= l: print(s) continue print(l * '0' + '0' + (n - r - 1) * '1') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has three baskets and two of them have multiple balls(Natural numbers written on them). The first basket has N balls, the second basket has M balls and the third basket is empty. Chef starts choosing all the unique balls(only occurring once in both the baskets) and puts into the third basket and throw the repetitive ones. Print numbers on the balls of the third basket in ascending order. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains three lines of input. - First-line has two integers $N, M$. - Second-line with N space-separated numbers. - Third-line with M space-separated numbers. -----Output:----- For each testcase, output in a single line answer. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 10^5$ - $1 \leq M \leq 10^5$ -----Sample Input:----- 1 4 5 1 2 3 4 2 3 4 5 6 -----Sample Output:----- 1 5 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for i in range(t): n, m = map(int, input().split()) arr1 = list(map(int, input().split())) arr2 = list(map(int, input().split())) hmap = {} for i in range(n): if arr1[i] in hmap: hmap[arr1[i]] += 1 else: hmap[arr1[i]] = 1 for i in range(m): if arr2[i] in hmap: hmap[arr2[i]] += 1 else: hmap[arr2[i]] = 1 ans = [] #print(hmap) for key in hmap: if hmap[key]==1: ans.append(key) ans.sort() for x in ans: print(x,end=' ') print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A printer – who still uses moveable type – is preparing to print a set of pages for a book. These pages are to be numbered, as usual. The printer needs to know how many instances of each decimal digit will be required to set up the page numbers in the section of the book to be printed. For example, if pages 10, 11, 12, 13, 14 and 15 are to be printed, computing the number of digits is relatively simple: just look at the page numbers that will appear, and count the number of times each digit appears. The digit 0 appears only once, the digit 1 appears 7 times, the digits 2, 3, 4 and 5 each appear once, and 6, 7, 8 and 9 don’t appear at all. Your task in this problem is to provide the printer with the appropriate counts of the digits. You will be given the numbers of the two pages that identify the section of the book to be printed. You may safely assume that all pages in that section are to be numbered, that no leading zeroes will be printed, that page numbers are positive, and that no page will have more than three digits in its page number. -----Input----- There will be multiple cases to consider. The input for each case has two integers, A and B, each of which is guaranteed to be positive. These identify the pages to be printed. That is, each integer P between A and B, including A and B, is to be printed. A single zero will follow the input for the last case. -----Output----- For each input case, display the case number (1, 2, …) and the number of occurrences of each decimal digit 0 through 9 in the specified range of page numbers. Display your results in the format shown in the examples below. -----Example----- Input: 10 15 912 912 900 999 0 Output: Case 1: 0:1 1:7 2:1 3:1 4:1 5:1 6:0 7:0 8:0 9:0 Case 2: 0:0 1:1 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:1 Case 3: 0:20 1:20 2:20 3:20 4:20 5:20 6:20 7:20 8:20 9:120 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python line = input() test = 0 while line != "0": test += 1 d = {'0':0,'1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0} a = list(map(int,line.split())) for i in range(min(a),max(a)+1): for c in str(i): d[c] += 1 pairs = list(d.items()) pairs.sort() print("Case %s: %s" % (test, " ".join(["%s:%s" % (k,v) for k,v in pairs]))) line = input() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The bustling town of Siruseri has just one sports stadium. There are a number of schools, colleges, sports associations, etc. that use this stadium as the venue for their sports events. Anyone interested in using the stadium has to apply to the Manager of the stadium indicating both the starting date (a positive integer $S$) and the length of the sporting event in days (a positive integer $D$) they plan to organise. Since these requests could overlap it may not be possible to satisfy everyone. Also, there should be at least one gap day between any two approved events, so that the stadium can be cleaned. It is the job of the Manager to decide who gets to use the stadium and who does not. The Manager, being a genial man, would like to keep as many organisations happy as possible and hence would like to allocate the stadium so that maximum number of events are held. Suppose, for example, the Manager receives the following 4 requests: $ $ Event No. Starting Date Length 1 2 5 2 9 7 3 15 6 4 9 3 $ $ He would allot the stadium to events $1$, $4$ and $3$. Event $1$ begins on day $2$ and ends on day $6$, event $4$ begins on day $9$ and ends on day $11$ and event $3$ begins on day $15$ and ends on day $20$. You can verify that it is not possible to schedule all the $4$ events (since events $2$ and $3$ overlap and only one of them can get to use the stadium). Your task is to help the manager find the best possible allotment (i.e., the maximum number of events that can use the stadium). -----Input:----- The first line of the input will contain a single integer $N$ indicating the number of events for which the Manager has received a request. Lines $2,3,...,N+1$ describe the requirements of the $N$ events. Line $i+1$ contains two integer $S_i$ and $D_i$ indicating the starting date and the duration of event $i$. -----Output:----- Your output must consist of a single line containing a single integer $M$, indicating the maximum possible number of events that can use the stadium. -----Constraints:----- - $1 \leq N \leq 100000$. - $1 \leq S_i \leq 1000000$. - $1 \leq D_i \leq 1000$. - $50 \%$ of test cases will also satisfy $1 \leq N \leq 10000$. -----Sample input:----- 4 2 5 9 7 15 6 9 3 -----Sample output:----- 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here n=(int(input())) x=[] for _ in range(n): a,b=map(int,input().split()) a=[a,a+b] x.append(a) x = sorted(x, key= lambda i:i[1]) y=-1 c=0 for i in range(len(x)): if x[i][0]>y: c+=1 y=x[i][1] print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Let's call a string balanced if all characters that occur in this string occur in it the same number of times. You are given a string $S$; this string may only contain uppercase English letters. You may perform the following operation any number of times (including zero): choose one letter in $S$ and replace it by another uppercase English letter. Note that even if the replaced letter occurs in $S$ multiple times, only the chosen occurrence of this letter is replaced. Find the minimum number of operations required to convert the given string to a balanced string. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains a single string $S$. -----Output----- For each test case, print a single line containing one integer ― the minimum number of operations. -----Constraints----- - $1 \le T \le 10,000$ - $1 \le |S| \le 1,000,000$ - the sum of $|S|$ over all test cases does not exceed $5,000,000$ - $S$ contains only uppercase English letters -----Subtasks----- Subtask #1 (20 points): - $T \le 10$ - $|S| \le 18$ Subtask #2 (80 points): original constraints -----Example Input----- 2 ABCB BBC -----Example Output----- 1 1 -----Explanation----- Example case 1: We can change 'C' to 'A'. The resulting string is "ABAB", which is a balanced string, since the number of occurrences of 'A' is equal to the number of occurrences of 'B'. Example case 2: We can change 'C' to 'B' to make the string "BBB", which is a balanced string. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin from collections import Counter def func(arr,n,l): count=0 k=l//n if n<len(arr): for ele in arr[0:n]: count+=max(0,k-ele) else: for ele in arr: count+=max(0,ele-k) return count for _ in range(int(stdin.readline())): s=stdin.readline().strip() d=Counter(s) arr=sorted(list(d.values()),reverse=True) l=len(s) val=[1] for i in range(2,27): if l%i==0: val.append(i) ans = float('inf') for ele in val: x = func(arr,ele,l) if x < ans: ans = x print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Indian National Olympiad in Informatics 2015 In this problem you are given two lists of N integers, a1, a2, ..., aN and b1, b2, ... bN. For any pair (i, j) with i, j ϵ {1, 2, ..., N} we define the segment from i to j, written as [i, j], to be i, i + 1, ..., j if i ≤ j and i, i + 1, ..., N, 1, 2, ...,j if i > j. Thus if N = 5 then the [2, 4] = {2, 3, 4} and [4, 2] = {4, 5, 1, 2}. With each segment [i, j] we associate a special sum SSum[i, j] as follows: - SSum[i, i] = ai. - If i ≠ j then, The positions i and j contribute ai and aj, respectively, to the sum while every other position k in [i, j] contributes bk. Suppose N = 5 and that the two given sequences are as follows: i 1 2 3 4 5 ai 2 3 2 3 1 bi 3 4 4 6 3 Then, SSum[1, 1] = 2, SSum[2, 4] = 3 + 4 + 3 = 10 and SSum[4, 2] = 3 + 3 + 3 + 3 = 12. Your aim is to compute the maximum value of SSum[i, j] over all segments [i, j]. In this example you can verify that this value is 18 (SSum[2, 1] = 18). -----Input format----- - The first line contains a single positive integer N. - This is followed by a line containing N integers giving the values of the ais and this is followed by a line containing N integers giving the values of the bis. -----Output format----- A single integer in a single line giving the maximum possible special segment sum. Note: The final value may not fit in a 32 bit integer. Use variables of an appropriate type to store and manipulate this value (long long in C/C++, long in Java). -----Test Data----- You may assume that -109 ≤ ai, bi ≤ 109. Subtask 1 (10 Marks) 1 ≤ N ≤ 3000. Subtask 2 (20 Marks) 1 ≤ N ≤ 106 and ai = bi for all 1 ≤ i ≤ N. Subtask 3 (30 Marks) 3 ≤ N ≤106. Further a1 = b1 = aN = bN = -109 and for each 1 < k < N we have -999 ≤ ak, bk ≤ 999. Subtask 4 (40 Marks) 1 ≤ N ≤ 106. -----Example----- Here is the sample input and output corresponding to the example above: -----Sample input----- 5 2 3 2 3 1 3 4 4 6 3 -----Sample output----- 18 Note: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect! The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline #import io,os; input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #for pypy inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] from collections import deque def getmax(x,n,k): mx = [] dq = deque() for i in range(k): while dq and x[i] >= x[dq[-1]]: dq.pop() dq.append(i) mx.append(x[dq[0]]) for i in range(k,n): while dq and dq[0] <= i-k: dq.popleft() while dq and x[i] >= x[dq[-1]]: dq.pop() dq.append(i) mx.append(x[dq[0]]) return mx n = inp() m = n+n A = ip() B = ip() A += A B += B pre = [0]*(m+1) for i in range(1,m+1): pre[i] += pre[i-1] + B[i-1] plus = [0]*m minus = [0]*m for i in range(m): plus[i] = A[i]+pre[i] minus[i] = A[i]-pre[i+1] a = getmax(plus,m,n-1) ans = float('-inf') for i in range(n): ans = max(ans,minus[i]+a[i+1]) print(max(ans,*A)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: VK gave a problem to Chef, but Chef is too lazy, so he asked you to solve the problem for him. The statement of the problem follows. Consider an integer with $N$ digits (in decimal notation, without leading zeroes) $D_1, D_2, D_3, \dots, D_N$. Here, $D_1$ is the most significant digit and $D_N$ the least significant. The weight of this integer is defined as ∑i=2N(Di−Di−1).∑i=2N(Di−Di−1).\sum_{i=2}^N (D_i - D_{i-1})\,. You are given integers $N$ and $W$. Find the number of positive integers with $N$ digits (without leading zeroes) and weight equal to $W$. Compute this number modulo $10^9+7$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $N$ and $W$ denoting the number of digits and the required weight. -----Output----- For each test case, print a single line containing one integer — the number of $N$-digit positive integers with weight $W$, modulo $10^9+7$. -----Constraints----- - $1 \le T \le 10^5$ - $2 \le N \le 10^{18}$ - $|W| \le 300$ -----Subtasks----- Subtask #1 (20 points): - $1 \le T \le 10^3$ - $2 \le N \le 10^3$ Subtask #2 (80 points): original constraints -----Example Input----- 1 2 3 -----Example Output----- 6 -----Explanation----- Example case 1: Remember that the digits are arranged from most significant to least significant as $D_1, D_2$. The two-digit integers with weight $3$ are $14, 25, 36, 47, 58, 69$. For example, the weight of $14$ is $D_2-D_1 = 4-1 = 3$. We can see that there are no other possible numbers. 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,w = map(int , input().split()) sigma = 1 #len(str(num)) == n and D[i] - D[i - 1] ... = w if(w > 9 or w < -9): print(0) continue sigma = pow(10,n - 2,1000000007) if(w >= 0): sigma *= (9 - w) else: sigma *= (w + 10) print(sigma % 1000000007) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes. The schedule on Monday is known for each group, i. e. time slots when group will have classes are known. Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups. Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot. -----Output----- Print minimum number of rooms needed to hold all groups classes on Monday. -----Examples----- Input 2 0101010 1010101 Output 1 Input 3 0101011 0011001 0110111 Output 3 -----Note----- In the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group. In the second example three rooms is enough, because in the seventh time slot all three groups have classes. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python strings = int(input()) count = [0 for x in range(7)] for k in range(strings): s = input() for index in range(7): if s[index] == '1': count[index] += 1 print(max(count)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef Vivek is good in mathematics and likes solving problems on prime numbers. One day his friend Jatin told him about Victory numbers. Victory number can be defined as a number formed after summing up all the prime numbers till given number n. Now, chef Vivek who is very fond of solving questions on prime numbers got busy in some other tasks. Your task is to help him finding victory number. -----Input:----- - First line will contain $T$, number of test cases. Then the test cases follow. - Each test case contains of a single line of input $N$ till which sum of all prime numbers between 1 to n has to be calculated. -----Output:----- For each test case, output in a single line answer to the victory number. -----Constraints----- - $1 <= T <= 1000$ - $1 <= N <= 10^6$ -----Sample Input:----- 3 22 13 10 -----Sample Output:----- 77 41 17 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 test = int(input()) for i in range(test): sum = 0 max = int(input()) if max==1: sum = 0 elif max==2: sum += 2 else: sum = sum + 2 for x in range(3,max+1): half = int(sqrt(x)) + 1 if all(x%y!=0 for y in range(2,half)): sum = sum + x print(sum) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $(0, 0)$ on an infinite grid. You also have the sequence of instructions of this robot. It is written as the string $s$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $(x, y)$ right now, he can move to one of the adjacent cells (depending on the current instruction). If the current instruction is 'L', then the robot can move to the left to $(x - 1, y)$; if the current instruction is 'R', then the robot can move to the right to $(x + 1, y)$; if the current instruction is 'U', then the robot can move to the top to $(x, y + 1)$; if the current instruction is 'D', then the robot can move to the bottom to $(x, y - 1)$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $(0, 0)$) twice then it breaks. So the sequence of instructions is valid if the robot starts in the cell $(0, 0)$, performs the given instructions, visits no cell other than $(0, 0)$ two or more times and ends the path in the cell $(0, 0)$. Also cell $(0, 0)$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $(0, 0)$) and "UUDD" (the cell $(0, 1)$ is visited twice). The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain. Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric). You have to answer $q$ independent test cases. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^4$) — the number of test cases. The next $q$ lines contain test cases. The $i$-th test case is given as the string $s$ consisting of at least $1$ and no more than $10^5$ characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions. It is guaranteed that the sum of $|s|$ (where $|s|$ is the length of $s$) does not exceed $10^5$ over all test cases ($\sum |s| \le 10^5$). -----Output----- For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $t$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $0$, you are allowed to print an empty line (but you can don't print it). -----Example----- Input 6 LRU DURLDRUDRULRDURDDL LRUDDLRUDRUL LLLLRRRR URDUR LLL Output 2 LR 14 RUURDDDDLLLUUR 12 ULDDDRRRUULL 2 LR 2 UD 0 -----Note----- There are only two possible answers in the first test case: "LR" and "RL". The picture corresponding to the second test case: [Image] Note that the direction of traverse does not matter Another correct answer to the third test case: "URDDLLLUURDR". 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 _ in range(n): s = input() l,r,u,d = [s.count(i) for i in 'LRUD'] lr = min(l, r) ud = min(u, d) res = "" if lr == 0 and ud == 0: res = "" elif lr == 0: res = "UD" elif ud == 0: res = 'LR' else: res = 'R' * lr + 'U' * ud + 'L' * lr + 'D' * ud print(len(res)) print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: ----- Statement ----- You need to find a string which has exactly K positions in it such that the character at that position comes alphabetically later than the character immediately after it. If there are many such strings, print the one which has the shortest length. If there is still a tie, print the string which comes the lexicographically earliest (would occur earlier in a dictionary). -----Input----- The first line contains the number of test cases T. Each test case contains an integer K (≤ 100). -----Output----- Output T lines, one for each test case, containing the required string. Use only lower-case letters a-z. -----Sample Input ----- 2 1 2 -----Sample Output----- ba cba The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for i in range(int(input())): N = int(input()) s = 'zyxwvutsrqponmlkjihgfedcba' r = '' while True: r = s[-N-1:] + r if N < 26: break N -= 25 print(r) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chandler has a list of non zero positive integers with him. He made a very interesting observation about the list. He noticed that the number of unique integers in an array of size $N$ is in the range $L$ to $R$ (both inclusive) and every element was either 1 or an even number x, in which case x/2 was also definitely present in the array. Chandler has misplaced the list of integers but he wants to impress Monica with his problem solving skills by finding out the minimum and maximum possible sum of all elements of the list of integers. Can you also help him solve the problem so that he can win over Monica? -----Input:----- - First line will contain $T$, the number of testcases. - The first line of each test case contains integers $N$, $L$, and $R$. -----Output:----- For each test case print 2 space-separated integers, the minimum and the maximum possible sum of N elements based on the above facts. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N \leq 1000$ - $1 \leq L \leq R \leq min(N,20)$ -----Sample Input:----- 2 4 2 2 5 1 5 -----Sample Output:----- 5 7 5 31 -----EXPLANATION:----- - Example 1: For an array of size 4, with minimum 2 unique integers and maximum 2 unique integers, the possible arrays are (1,1,1,2), (1,1,2,2), (1,2,2,2) Out of these, the minimum possible sum of elements is 5(1+1+1+2) and maximum possible sum is 7(1+2+2+2) - Example 2: For an array of size 5, with minimum 1 unique integer and maximum 5 unique integers, minimum possible sum of elements is 5(1+1+1+1+1) and maximum possible sum is 31(1+2+4+8+16) 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,l,h=list(map(int,input().split())) print(n-l+1+2**(l)-2,1+2**(h)-2+2**(h-1)*(n-h)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen. -----Input----- The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain c_{i}, the number of balls of the i-th color (1 ≤ c_{i} ≤ 1000). The total number of balls doesn't exceed 1000. -----Output----- A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007. -----Examples----- Input 3 2 2 1 Output 3 Input 4 1 2 3 4 Output 1680 -----Note----- In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 3 1 1 2 2 3 2 1 1 2 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python 3 import sys from functools import lru_cache MOD = 1000000007 cnk = [[1 for i in range(1001)] for j in range(1001)] for i in range(1, 1001): for j in range(1, i): cnk[i][j] = cnk[i - 1][j - 1] + cnk[i - 1][j] k = int(input()) cs = [int(input()) for i in range(k)] ans = 1 sm = 0 for c in cs: sm += c ans = (ans * cnk[sm - 1][c - 1]) % MOD print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Harry is a bright student. To prepare thoroughly for exams, he completes all the exercises in his book! Now that the exams are approaching fast, he is doing book exercises day and night. He writes down and keeps updating the remaining number of exercises on the back cover of each book. Harry has a lot of books messed on the floor. Therefore, he wants to pile up the books that still have some remaining exercises into a single pile. He will grab the books one-by-one and add the books that still have remaining exercises to the top of the pile. Whenever he wants to do a book exercise, he will pick the book with the minimum number of remaining exercises from the pile. In order to pick the book, he has to remove all the books above it. Therefore, if there are more than one books with the minimum number of remaining exercises, he will take the one which requires the least number of books to remove. The removed books are returned to the messy floor. After he picks the book, he will do all the remaining exercises and trash the book. Since number of books is rather large, he needs your help to tell him the number of books he must remove, for picking the book with the minimum number of exercises. Note that more than one book can have the same name. -----Input----- The first line contains a single integer N denoting the number of actions. Then N lines follow. Each line starts with an integer. If the integer is -1, that means Harry wants to do a book exercise. Otherwise, the integer is number of the remaining exercises in the book he grabs next. This is followed by a string denoting the name of the book. -----Output----- For each -1 in the input, output a single line containing the number of books Harry must remove, followed by the name of the book that Harry must pick. -----Constraints----- 1 < N ≤ 1,000,000 0 ≤ (the number of remaining exercises of each book) < 100,000 The name of each book consists of between 1 and 15 characters 'a' - 'z'. Whenever he wants to do a book exercise, there is at least one book in the pile. -----Example----- Input: 6 9 english 6 mathematics 8 geography -1 3 graphics -1 Output: 1 mathematics 0 graphics The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=eval(input()) a=[] b=[] top=-1 for __ in range(0,t): x=input().split() if(x[0]!="-1" and x[0]!="0"): add=int(x[0]) if top!=-1 and add>a[top][0] : b[top]+=1 else: a.append((add,x[1])) b.append(0) top+=1 elif (x[0]=="-1"): #print("%s %s" %(b[top],a[top][1])) print((b[top]), end=' ') print(a[top][1]) foo=a.pop() bar=b.pop() top-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half. [Image] English alphabet You are given a string s. Check if the string is "s-palindrome". -----Input----- The only line contains the string s (1 ≤ |s| ≤ 1000) which consists of only English letters. -----Output----- Print "TAK" if the string s is "s-palindrome" and "NIE" otherwise. -----Examples----- Input oXoxoXo Output TAK Input bod Output TAK Input ER Output NIE The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys, math s=input() pal='AHIMOoTUVvWwXxY' n=len(s) l=0 r=n-1 flag=True fir='pq' sec='bd' while l<=r: if s[l]==s[r] and s[l] in pal: l+=1 r-=1 continue elif s[l]==s[r]: flag=False break elif (s[l] in fir) and (s[r] in fir): l+=1 r-=1 continue elif (s[l] in sec) and (s[r] in sec): l+=1 r-=1 continue else: flag=False break if flag: print('TAK') else: print('NIE') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Teddy and Tracy like to play a game based on strings. The game is as follows. Initially, Tracy writes a long random string on a whiteboard. Then, each player starting with Teddy makes turn alternately. Each turn, the player must erase a contiguous substring that exists in the dictionary. The dictionary consists of N words. Of course, the player that can't erase any substring in his turn loses the game, and the other player is declared the winner. Note that after a substring R is erased, the remaining substring becomes separated, i.e. they cannot erase a word that occurs partially to the left of R and partially to the right of R. Determine the winner of the game, assuming that both players play optimally. -----Input----- The first line contains a single integer T, the number of test cases. T test cases follow. The first line of each testcase contains a string S, the string Tracy writes on the whiteboard. The next line contains a single integer N. N lines follow. The i-th line contains a single string wi, the i-th word in the dictionary. -----Output----- For each test case, output a single line containing the name of the winner of the game. -----Example----- Input: 3 codechef 2 code chef foo 1 bar mississippi 4 ssissi mippi mi ppi Output: Tracy Tracy Teddy -----Constraints----- - 1 <= T <= 5 - 1 <= N <= 30 - 1 <= |S| <= 30 - 1 <= |wi| <= 30 - S and wi contain only characters 'a'-'z' 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 mex(S,W,C,start,end): """Returns Nim-number of S[start:end]""" key=(start,end) try: return C[key] except KeyError: pass A=set() for s in range(start,end): for e in range(start+1,end+1): if S[s:e] not in W: continue A.add(mex(S,W,C,start,s)^mex(S,W,C,e,end)) a=0 while a in A: a+=1 C[key]=a return a a=sys.stdin #a=open('astrgame.txt','r') T=int(a.readline()) for t in range(T): S=a.readline().strip() N=int(a.readline()) W=set([a.readline().strip() for n in range(N)]) print('Teddy' if mex(S,W,{},0,len(S)) else 'Tracy') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Mr. Wire Less is not that good at implementing circuit in a breadboard. In his Digital Logic Design course, he has to implement several boolean functions using the breadboard. In a breadboard, inputs are given through the switches and outputs are taken through the LEDs. Each input switch can be either in ground state or in high state. So, if he wishes to implement a boolean function, f(x1, x2, .., xn) that takes n boolean values as input and returns m boolean values as output, he will use n switches and m LEDs. Mr. Wire Less can quickly assemble the necessary ICs and wires, but the key problem is testing. While testing he has to check with all possible input combination, to make sure whether the output of LED corresponds to the expected output or not. This is taking too long for him, as most of the switches are jammed and difficult to toggle. Mr. Wire Less is asking for help to minimize his time of testing. So, your task is to minimize the total number of switch-toggle throughout the testing. For example, if Mr. Wire Less has to test a function f(x0, x1) of two variables, he may choose this switching-sequence for testing 00, 11, 10, 01. In this case, the total number of switch-toggle will be 2+1+2 = 5. But if he tests in this sequence 00, 10, 11, 01 total number of toggle will be 1+1+1 = 3. Given n, you have to output the minimum number of toggle needed for complete testing. Though it seems impractical, he wants you to solve the problem for a very large value of n. But, then the toggle value can be quite big. So, he is completely okay with the toggle value modulo 8589934592 (233).

 -----Input----- The first line of the input contains a positive integer T(T ≤ 105), denoting the number of test-case. Each of the following T lines contains a single non-negative integer n(n ≤ 1020). -----Output----- For every test-case, output a single containing test-case number and the minimum number of switch-toggle modulo 8589934592 (233). -----Sample----- Input 2 1 2 Output Case 1: 1 Case 2: 3 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=8589934592 list1=[] for i in range(int(input())): x=int(input()) ans=(pow(2,x,mod)-1)%mod list1.append((i+1,ans)) for i in list1: print(f'Case {i[0]}: {i[1]}') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Evlampiy has found one more cool application to process photos. However the application has certain limitations. Each photo i has a contrast v_{i}. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible. Evlampiy already knows the contrast v_{i} for each of his n photos. Now he wants to split the photos into groups, so that each group contains at least k photos. As a result, each photo must belong to exactly one group. He considers a processing time of the j-th group to be the difference between the maximum and minimum values of v_{i} in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups. Split n photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible. -----Input----- The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3·10^5) — number of photos and minimum size of a group. The second line contains n integers v_1, v_2, ..., v_{n} (1 ≤ v_{i} ≤ 10^9), where v_{i} is the contrast of the i-th photo. -----Output----- Print the minimal processing time of the division into groups. -----Examples----- Input 5 2 50 110 130 40 120 Output 20 Input 4 1 2 3 4 1 Output 0 -----Note----- In the first example the photos should be split into 2 groups: [40, 50] and [110, 120, 130]. The processing time of the first group is 10, and the processing time of the second group is 20. Maximum among 10 and 20 is 20. It is impossible to split the photos into groups in a such way that the processing time of division is less than 20. In the second example the photos should be split into four groups, each containing one photo. So the minimal possible processing time of a division is 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def f(m): nonlocal dp, sdp l = 0 for i in range(n): while l < n and v[l] < v[i] - m: l += 1 if l - 1 > i - k: dp[i] = False else: dp[i] = (sdp[i - k + 1] != sdp[l - 1]) sdp[i + 1] = sdp[i] + (1 if dp[i] else 0) return dp[n - 1] n, k = list(map(int, input().split())) dp = [False for i in range(n + 2)] sdp = [0 for i in range(n + 2)] dp[-1] = True sdp[0] = 1 v = list(map(int, input().split())) v.sort() le = -1 r = v[-1] - v[0] while r - le > 1: m = (r + le) // 2 if f(m): r = m else: le = m print(r) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In ChefLand, there is a mountain range consisting of $N$ hills (numbered $1$ through $N$) in a straight line. Let's denote the height of the $i$-th hill from the left by $h_i$. Ada is working on the water supply system of ChefLand. On some of the hills, she wants to place water reservoirs; then, for each reservoir, she will decide in which direction the water should flow from it — either to the left or to the right (water may not flow in both directions from the same reservoir). From a reservoir on a hill with height $h$, water flows in the chosen direction until it reaches the first hill that is strictly higher than $h$; all hills before this hill (including the hill containing the reservoir) are therefore supplied with water. For example, suppose we have hills with heights $[7, 2, 3, 5, 8]$. If we place a reservoir on the hill with height $5$, and pump water from it to the left, then the hills with heights $2$, $3$ and $5$ are supplied with water. Help Ada find the minimum numer of reservoirs needed to provide water to all the hills if she chooses the directions optimally. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $h_1, h_2, \dots, h_N$. -----Output----- For each test case, print a single line containing one integer — the minimum required number of reservoirs. -----Constraints----- - $2 \le N \le 10^5$ - $1 \le h_i \le 10^9$ for each valid $i$ - $h_i \neq h_j $ for any valid $i \neq j$ - the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$ -----Example Input----- 1 6 4 16 32 6 8 2 -----Example Output----- 2 -----Explanation----- Example case 1: We can place reservoirs on the second and third hill, pumping water to the left and right respectively. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def solve(l): m = l.index(max(l)) if m == 0 or m == len(l) - 1: return 1 return 1 + min(solve(l[0:m]), solve(l[m+1:])) tc = int(input()) for test in range(tc): n = int(input()) l = list(map(int, input().split())) print(solve(l)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's define the following recurrence: $$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$ Here $minDigit(x)$ and $maxDigit(x)$ are the minimal and maximal digits in the decimal representation of $x$ without leading zeroes. For examples refer to notes. Your task is calculate $a_{K}$ for given $a_{1}$ and $K$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of independent test cases. Each test case consists of a single line containing two integers $a_{1}$ and $K$ ($1 \le a_{1} \le 10^{18}$, $1 \le K \le 10^{16}$) separated by a space. -----Output----- For each test case print one integer $a_{K}$ on a separate line. -----Example----- Input 8 1 4 487 1 487 2 487 3 487 4 487 5 487 6 487 7 Output 42 487 519 528 544 564 588 628 -----Note----- $a_{1} = 487$ $a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519$ $a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528$ $a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544$ $a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564$ $a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588$ $a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628$ 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 for _ in range(int(input())): a, k = list(map(int, input().split())) for _ in range(k - 1): if '0' in str(a): break a += int(min(list(str(a)))) * int(max(list(str(a)))) print(a) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Consider the following $4 \times 4$ pattern: 1 2 4 7 3 5 8 11 6 9 12 14 10 13 15 16 You are given an integer $N$. Print the $N \times N$ pattern of the same kind (containing integers $1$ through $N^2$). -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains a single integer $N$. -----Output----- For each test case, print $N$ lines; each of them should contain $N$ space-separated integers. -----Constraints----- - $1 \le T \le 10$ - $1 \le N \le 100$ -----Subtasks----- Subtask #1 (100 points): Original constraints -----Example Input----- 1 4 -----Example Output----- 1 2 4 7 3 5 8 11 6 9 12 14 10 13 15 16 -----Explanation----- The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for i in range(int(input())): t=int(input()) n=0 for i in range(1,t+1): n=n+i x=[n] y=n for j in range(i,t+i-1): if j<t: z=y+j else: z=y+(2*t-j-1) x.append(z) y=z print(*x) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of h_{i} identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time. Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. -----Input----- The first line contains single integer n (1 ≤ n ≤ 10^5). The second line contains n space-separated integers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9) — sizes of towers. -----Output----- Print the number of operations needed to destroy all towers. -----Examples----- Input 6 2 1 4 6 2 2 Output 3 Input 7 3 3 3 1 3 3 3 Output 2 -----Note----- The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. [Image] After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python x = int(input()) y = list(map(int, input().split(' '))) y[0] = 1 y[x-1] = 1 z = y[:] for i in range(1, x): z[i] = min(z[i], z[i-1] + 1) w = y[:] for i in range(x-2, -1, -1): w[i] = min(w[i], w[i+1]+1) ans = 0 for i in range(x): ans = max(ans, min(z[i], w[i])) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: k kids seem to have visited your home for the festival. It seems like the kids had all been fighting with each other, so you decided to keep them as far as possible from each other. You had placed n chairs on the positive number line, each at position x i , 1 ≤ i ≤ n. You can make the kids sit in any of the chairs. Now you want to know the largest possible minimum distance between each kid. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains two lines. First line contains two space separated integers n and k. Second line contains n space separated values, x1, x2, x3, … ,xn. -----Output:----- For each test case print the largest possible minimum distance. -----Sample Input:----- 1 2 2 1 2 -----Sample Output:----- 1 -----Constraints----- - $2 \leq n \leq 100000$ - $0 \leq xi \leq 10^9$ - $k \leq n $ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] def check(mid): pos = x[0] ct = 1 for i in range(1,n): if x[i]-pos >= mid: pos = x[i] ct += 1 if ct == k: return True return False for _ in range(inp()): n,k = ip() x = ip() x.sort() ans = -1 l,r = 1,x[-1] while l < r: mid = (l+r)//2 if check(mid): ans = max(ans,mid) l = mid +1 else: r = mid print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a integer $n$ ($n > 0$). Find any integer $s$ which satisfies these conditions, or report that there are no such numbers: In the decimal representation of $s$: $s > 0$, $s$ consists of $n$ digits, no digit in $s$ equals $0$, $s$ is not divisible by any of it's digits. -----Input----- The input consists of multiple test cases. The first line of the input contains a single integer $t$ ($1 \leq t \leq 400$), the number of test cases. The next $t$ lines each describe a test case. Each test case contains one positive integer $n$ ($1 \leq n \leq 10^5$). It is guaranteed that the sum of $n$ for all test cases does not exceed $10^5$. -----Output----- For each test case, print an integer $s$ which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for $s$, print any solution. -----Example----- Input 4 1 2 3 4 Output -1 57 239 6789 -----Note----- In the first test case, there are no possible solutions for $s$ consisting of one digit, because any such solution is divisible by itself. For the second test case, the possible solutions are: $23$, $27$, $29$, $34$, $37$, $38$, $43$, $46$, $47$, $49$, $53$, $54$, $56$, $57$, $58$, $59$, $67$, $68$, $69$, $73$, $74$, $76$, $78$, $79$, $83$, $86$, $87$, $89$, $94$, $97$, and $98$. For the third test case, one possible solution is $239$ because $239$ is not divisible by $2$, $3$ or $9$ and has three digits (none of which equals zero). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #JMD #Nagendra Jha-4096 import sys import math #import fractions #import numpy ###File Operations### fileoperation=0 if(fileoperation): orig_stdout = sys.stdout orig_stdin = sys.stdin inputfile = open('W:/Competitive Programming/input.txt', 'r') outputfile = open('W:/Competitive Programming/output.txt', 'w') sys.stdin = inputfile sys.stdout = outputfile ###Defines...### mod=1000000007 ###FUF's...### def nospace(l): ans=''.join(str(i) for i in l) return ans ##### Main #### t=int(input()) for tt in range(t): n=int(input()) if n==1: print(-1) else: s="2" for i in range(n-1): s+='3' print(s) #n,k,s= map(int, sys.stdin.readline().split(' ')) #a=list(map(int,sys.stdin.readline().split(' '))) #####File Operations##### if(fileoperation): sys.stdout = orig_stdout sys.stdin = orig_stdin inputfile.close() outputfile.close() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? - The vertices are numbered 1,2,..., N. - The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. - For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1. If such a tree exists, construct one such tree. -----Constraints----- - 2 \leq N \leq 100000 - 1 \leq D_i \leq 10^{12} - D_i are all distinct. -----Input----- Input is given from Standard Input in the following format: N D_1 D_2 : D_N -----Output----- If a tree with n vertices that satisfies the conditions does not exist, print -1. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. -----Sample Input----- 7 10 15 13 18 11 14 19 -----Sample Output----- 1 2 1 3 1 5 3 4 5 6 6 7 The tree shown below satisfies the conditions. 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 N = int(input()) C = defaultdict(int) for i in range(N): D = int(input()) C[D] = i + 1 E = [] H = [1] * (N + 1) DD = sorted([[k, v] for k, v in C.items()], reverse=True) Adj = [[] for i in range(N)] for D, n in DD[:-1]: try: p = C[D - N + 2 * H[n]] if n == p: raise Error E.append([n, p]) Adj[n - 1].append(p - 1) Adj[p - 1].append(n - 1) H[p] += H[n] except: print(-1) break else: dist = [N] * N dist[DD[-1][1] - 1] = 0 Q = [DD[-1][1] - 1] + [N] * N tail = 1 for i in range(N): s = Q[i] if s == N: print(-1) break for adj in Adj[s]: if dist[adj] == N: dist[adj] = dist[s] + 1 Q[tail] = adj tail += 1 else: if sum(dist) == DD[-1][0]: for e in E: print(e[0], e[1]) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The following graph G is called a Petersen graph and its vertices have been numbered from 0 to 9. Some letters have also been assigned to vertices of G, as can be seen from the following picture: Let's consider a walk W in graph G, which consists of L vertices W1, W2, ..., WL, such that Wi is connected with Wi + 1 for 1 ≤ i < L. A string S of L letters 'A'-'E' is realized by walk W if the sequence of letters written along W is equal to S. Vertices can be visited multiple times while walking along W. For example, S = 'ABBECCD' is realized by W = (0, 1, 6, 9, 7, 2, 3). Your task is to determine whether there is a walk W which realizes a given string S in graph G, and if so, find the lexicographically least such walk. -----Input----- The first line of the input contains one integer T denoting the number of testcases to process. The only line of each testcase contains one string S. It is guaranteed that S only consists of symbols 'A'-'E'. -----Output----- The output should contain exactly T lines, one line per each testcase in the order of their appearance. For each testcase, if there is no walk W which realizes S, then output -1. Otherwise, you should output the least lexicographical walk W which realizes S. Since all of the vertices are numbered from 0 to 9, then it can be encoded as a string consisting of symbols '0'-'9' (see the "Examples" section for more details). -----Constraints----- 1 ≤ T ≤ 8; 1 ≤ |S| ≤ 100000(105). -----Examples----- Input: 2 AAB AABE Output: 501 -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python let_to_num = {'A':[0,5], 'B':[1,6], 'C':[2,7], 'D':[3,8], 'E':[4,9]} num_to_let = {0:'A', 1:'B', 2:'C', 3:'D', 4:'E', 5:'A', 6:'B', 7:'C', 8:'D', 9:'E'} connections = {0:(1,4,5), 1:(0,2,6), 2:(1,3,7), 3:(2,4,8), 4:(0,3,9), 5:(0,7,8), 6:(1,8,9), 7:(2,5,9), 8:(3,5,6), 9:(4,6,7)} T = int(input()) for i in range(T): s = input() out_1, out_2= [],[] flag1, flag2 = True, True for c in range(len(s)): #print out_1, out_2, flag1, flag2 if c == 0: out_1.append(let_to_num[s[c]][0]) out_2.append(let_to_num[s[c]][1]) #print out_1, out_2, '\n' else: if flag1: conn_1 = set(connections[out_1[-1]]) to_conn_1 = set(let_to_num[s[c]]) if len(conn_1.intersection(to_conn_1))==0: flag1 = False else: out_1.extend(list(conn_1.intersection(to_conn_1))) #print 'out1',conn_1, to_conn_1, flag1, conn_1.intersection(to_conn_1) if flag2: conn_2 = set(connections[out_2[-1]]) to_conn_2 = set(let_to_num[s[c]]) if len(conn_2.intersection(to_conn_2))==0: flag2 = False else: out_2.extend(list(conn_2.intersection(to_conn_2))) #print 'out2', conn_2, to_conn_2, flag2, conn_2.intersection(to_conn_2) #print out_1, out_2, flag1, flag2, '\n' if (not flag1) and (not flag2): break if (not flag1) and (not flag2): print(-1) continue elif flag1 and (not flag2): print(''.join(str(k) for k in out_1)) continue elif flag2 and (not flag1): print(''.join(str(k) for k in out_2)) continue else: print(min(''.join(str(k) for k in out_1), ''.join(str(k) for k in out_2))) continue ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Every character in the string “IITMANDI” is given a certain number of points. You are given a scrabble board with only one row. The input contains the positions of score modifiers such as: Double Letter, Triple Letter, Double Word and Triple Word. You need to find the best position to place the string “IITMANDI” such that your score is maximized. Double Letter - Doubles the number of points you get for the letter placed on the double letter. Triple Letter - Triples the number of points you get for the letter placed on the triple letter. Double Word - Doubles the number of points you get for the word. Applied after applying above modifiers. Triple Word - Triples the number of points you get for the word. Applied after applying the above modifiers. The word has to be read from left to right. You can’t place it in the reverse direction. The letters have to be placed continuously on the board. If there is no modifier or a double word or triple word modifier before a tile, it's score is added to the total score. The double word and triple modifiers are applied at the end. -----Input Format----- - First line containes a single integer $T$ - the number of test cases. - First line of each test case contains a single integer $N$ - the size of the board. - Second line of each test case contains a string of size $N$ representing the board according to the following convention: '.' - No modifier 'd' - Double letter 't' - Triple letter 'D' - Double word 'T' - Triple word - Third line of each test case contains 8 integers corresponding to the points associated with each letter of the string "IITMANDI". Note that the 3 'I's in IITMANDI cannot be interchanged freely. The score of the first 'I' will be equal to the first integer, score of the second 'I' will be equal to the second integer and the score of the last 'I' will be equal to the last integer. -----Output Format----- For each test case, output a single integer in a new line, the maximum possible score. -----Constraints----- $ 1 \leq T \leq 1000 $ $ 8 \leq N \leq 100 $ $ 0 \leq $ Points for each character $ \leq 10^5 $ -----Sample Input----- 2 10 ..d.t.D..d 10 11 12 9 8 10 11 15 22 dtDtTD..ddT.TtTdDT..TD 12297 5077 28888 17998 12125 27400 31219 21536 -----Sample Output----- 270 35629632 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: T = int(input()) for i in range(T): n = int(input()) s = input() arr = [int(i) for i in input().strip().split(" ")] res = 1 result = 0 for j in range(n-7): res = 1 res1= 0 s1 = s[j:j+8] for i in range(8): if s1[i] == 'D': res = res*2 res1 += arr[i] elif s1[i] == 'T': res = res*3 res1 = res1 + arr[i] elif s1[i] == 'd': res1 = res1 + arr[i]*2 elif s1[i] == 't': res1 += arr[i]*3 else: res1 += arr[i] res = res*res1 result = max(res,result) print(result) except EOFError: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has decided to retire and settle near a peaceful beach. He had always been interested in literature & linguistics. Now when he has leisure time, he plans to read a lot of novels and understand structure of languages. Today he has decided to learn a difficult language called Smeagolese. Smeagolese is an exotic language whose alphabet is lowercase and uppercase roman letters. Also every word on this alphabet is a meaningful word in Smeagolese. Chef, we all know is a fierce learner - he has given himself a tough exercise. He has taken a word and wants to determine all possible anagrams of the word which mean something in Smeagolese. Can you help him ? -----Input----- Input begins with a single integer T, denoting the number of test cases. After that T lines follow each containing a single string S - the word chef has chosen. You can assume that 1 <= T <= 500 and 1 <= |S| <= 500. You can also assume that no character repeats more than 10 times in the string. -----Output----- Output one line per test case - the number of different words that are anagrams of the word that chef has chosen. As answer can get huge, print it modulo 10^9 + 7 -----Example----- Input: 4 ab aa aA AAbaz Output: 2 1 2 60 Description: In first case "ab" & "ba" are two different words. In third case, note that A & a are different alphabets and hence "Aa" & "aA" are different words. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from collections import Counter from math import factorial for _ in range(int(input())): s=input() c=Counter(s) k=factorial(len(s)) for value in c.values(): if value>1: k=k//factorial(value) print(k%(10**9+7)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples. Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows: - Move: When at town i (i < N), move to town i + 1. - Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money. For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.) During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel. Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i. Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen. -----Constraints----- - 1 ≦ N ≦ 10^5 - 1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N) - A_i are distinct. - 2 ≦ T ≦ 10^9 - In the initial state, Takahashi's expected profit is at least 1 yen. -----Input----- The input is given from Standard Input in the following format: N T A_1 A_2 ... A_N -----Output----- Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen. -----Sample Input----- 3 2 100 50 200 -----Sample Output----- 1 In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows: - Move from town 1 to town 2. - Buy one apple for 50 yen at town 2. - Move from town 2 to town 3. - Sell one apple for 200 yen at town 3. If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1. There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen. 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())) A = list(map(int,input().split())) cummax = [A[-1]] for a in reversed(A[:-1]): cummax.append(max(cummax[-1], a)) cummax.reverse() maxgain = n = 0 for buy,sell in zip(A,cummax): gain = sell - buy if gain > maxgain: maxgain = gain n = 1 elif gain == maxgain: n += 1 print(n) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport c_{i} burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. -----Input----- The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^7), here c_{i} is the cost of delaying the i-th flight for one minute. -----Output----- The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t_1, t_2, ..., t_{n} (k + 1 ≤ t_{i} ≤ k + n), here t_{i} is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. -----Example----- Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 -----Note----- Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from heapq import heappush,heappop,heapify n,k=map(int,input().split()) *l,=map(int,input().split()) q=[(-l[i],i)for i in range(k)];heapify(q) a=[0]*n s=0 for i in range(k,n): heappush(q,(-l[i],i)) x,j=heappop(q) s-=x*(i-j) a[j]=i+1 for i in range(n,n+k): x,j=heappop(q) s-=x*(i-j) a[j]=i+1 print(s) print(' '.join(map(str,a))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Bohan loves milk tea so much and he drinks one cup of milk tea every day. The local shop sells milk tea in two sizes: a Medium cup for $3 and a Large cup for $4. For every cup of milk tea purchased Bohan receives a promotional stamp. Bohan may redeem 6 stamps for a free drink of milk tea regardless of the size. No stamp will be given for a free drink. Determine the amount of money Bohan have spent on milk tea, given a sequence of milk tea sizes he got in the past a few days. Assume Bohan had no stamps in the beginning and he always redeemed the stamps for the next drink once he had collected 6 stamps. -----Input----- The input begins with the number of test cases T. Each test case has a single line of letters. The i-th letter is either 'M' or 'L' denoting a Medium cup or a Large cup of milk tea Bohan got on the i-th day. -----Output----- For each case, output the amount of money in dollars Bohan have spent on milk tea. -----Constraints----- - T ≤ 100 - 1 ≤ length of each sequence ≤ 100 -----Example----- Input: 3 MLM MMLLMMLL MMMMMMML Output: 10 24 22 -----Explanation----- Example 1: Bohan didn't redeem any stamps. Example 2: Bohan redeemed 6 stamps for the Large cup of milk tea on the 7th day. Example 3: Bohan redeemed 6 stamps for the Medium cup of milk tea on the 7th day. 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 tc in range(t): seq = input() dollar = 0 stamp = 0 for ct in seq: if stamp >= 6: stamp -= 6 continue elif ct == 'M': dollar += 3 elif ct == 'L': dollar += 4 stamp += 1 print(dollar) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef wants to teach a lesson of sharing to the students. There are $N$ students (numbered from $1$ to $N$ from left to right) who are asked to stand in a row. Initially Chef gave $A$$i$ candies to the $i$$th$ child. In one operation any child can give any number of candies to the child standing to his immediate left (i.e. $i$$th$ child can give any amount of candies to the $(i-1)$$th$ child. In particular 1st child cannot give his candies to anyone). He asked them to minimize the maximum value of candies a student can possess after performing any number of operations (possibly zero). Help the students finding such maximum value. -----Input:----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - First line of each test case contains a single integer $N$ denoting the number of students. - Second line contains $N$ space-separated integers $A$$1$,$A$$2$,$.....$ $A$$N$ denoting the initial amount of candies chef gave to them. -----Output:----- - For each test case, print a single line containing one integer ― maximum value after sharing. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N \leq 10^5$ - $0$ $\leq$ $A$$i$ $\leq$ $10^9$ - Sum of $N$ over all Test Cases does not exceed $10^5$ -----Sample Input----- 2 5 1 2 3 4 5 5 5 4 3 2 1 -----Sample Output----- 3 5 -----Explanation----- - For First Test Case: The $5$$th$ student will give $2$ candies to $4$$th$ student and $4$$th$ will give $3$ candies to $3$$rd$ and $3$$rd$ will give $3$ candies to $2$$nd$ and $2$$nd$ will give $2$ candies to $1$$st$. So finally the number of candies that they will have are $[3,3,3,3,3]$ and the value of maximum candies is $3$. - For Second Test Case: Sharing to the left student will not change the maximum value as $1$$st$ cannot share to anyone. So the maximum value will remain $5$. 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 ceil for _ in range(int(input())): n = int(input()) arr = [int(x) for x in input().split()] sarr = sum(arr) mavg = sarr/n while n>1: sarr -= arr.pop() n-=1 mavg = max(mavg, sarr/n) print(int(ceil(mavg))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Kabir Singh is playing a game on the non-negative side of x-axis. It takes him $1 second$ to reach from Pth position to (P−1)th position or (P+1)th position. Kabir never goes to the negative side and also doesn't stop at any moment of time. The movement can be defined as : - At the beginning he is at $x=0$ , at time $0$ - During the first round, he moves towards $x=1$ and comes back to the $x=0$ position. - In the second round, he moves towards the $x=2$ and comes back again to $x=0$. - So , at $Kth$ round , he moves to $x=K$ and comes back to $x=0$ So in this way game goes ahead. For Example, the path of Kabir for $3rd$ round is given below. $0−1−2−3−2−1−0$ The overall path followed by Kabir would look somewhat like this: $0−1−0−1−2−1−0−1−2−3−2−1−0−1−2−3−4−3−…$ Now the task is , You are given Two Non-Negative integers $N$ , $K$ . You have to tell the time at which Kabir arrives at $x=N$ for the $Kth$ time. Note - Kabir visits all the points , he can not skip or jump over one point. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, two integers $N, K$. -----Output:----- For each testcase, output in a single line answer i.e Time Taken by Kabir Singh modulo 1000000007. -----Constraints----- - $1 \leq T \leq 10^5$ - $0 \leq N \leq 10^9$ - $1 \leq K \leq 10^9$ -----Sample Input:----- 4 0 1 1 1 1 3 4 6 -----Sample Output:----- 0 1 5 46 -----EXPLANATION:----- Test Case 1: Kabir starts the journey from the $N=0$ at time $t=0$ and it's the first time$ (K=1)$, he is here. So, the answer is $0$. Test Case 3: The path followed by Kabir to reach 1 for the third time is given below. $0−1−0−1−2−1$ He reaches $1$ for the third time at $ t=5$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here T=int(input()) MOD=int(1e9+7) for t in range(T): N,K=[int(a) for a in input().split()] M=K//2 # ans= ((K%2)?( (N+M)*(N+M) + M ):( (N+M)*(N+M) - M) ) ans=(N+M)*(N+M) -M if(K%2): ans+=2*M if(N==0): ans=K*(K-1) print(ans%MOD) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0. It is allowed to leave a as it is. -----Input----- The first line contains integer a (1 ≤ a ≤ 10^18). The second line contains integer b (1 ≤ b ≤ 10^18). Numbers don't have leading zeroes. It is guaranteed that answer exists. -----Output----- Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists. The number in the output should have exactly the same length as number a. It should be a permutation of digits of a. -----Examples----- Input 123 222 Output 213 Input 3921 10000 Output 9321 Input 4940 5000 Output 4940 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a = list(input()) b = int(input()) a.sort() a = a[::-1] prefix = "" while(len(a) > 0): for i in range(len(a)): num = prefix + a[i] + "".join(sorted(a[:i] + a[i + 1:])) if (int(num) <= b): prefix += a[i] a = a[:i] + a[i+1:] break print(prefix) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are $n$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $1$ to $n$. Two fairs are currently taking place in Berland — they are held in two different cities $a$ and $b$ ($1 \le a, b \le n$; $a \ne b$). Find the number of pairs of cities $x$ and $y$ ($x \ne a, x \ne b, y \ne a, y \ne b$) such that if you go from $x$ to $y$ you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities $x,y$ such that any path from $x$ to $y$ goes through $a$ and $b$ (in any order). Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs $(x,y)$ and $(y,x)$ must be taken into account only once. -----Input----- The first line of the input contains an integer $t$ ($1 \le t \le 4\cdot10^4$) — the number of test cases in the input. Next, $t$ test cases are specified. The first line of each test case contains four integers $n$, $m$, $a$ and $b$ ($4 \le n \le 2\cdot10^5$, $n - 1 \le m \le 5\cdot10^5$, $1 \le a,b \le n$, $a \ne b$) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively. The following $m$ lines contain descriptions of roads between cities. Each of road description contains a pair of integers $u_i, v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$) — numbers of cities connected by the road. Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities. The sum of the values of $n$ for all sets of input data in the test does not exceed $2\cdot10^5$. The sum of the values of $m$ for all sets of input data in the test does not exceed $5\cdot10^5$. -----Output----- Print $t$ integers — the answers to the given test cases in the order they are written in the input. -----Example----- Input 3 7 7 3 5 1 2 2 3 3 4 4 5 5 6 6 7 7 5 4 5 2 3 1 2 2 3 3 4 4 1 4 2 4 3 2 1 1 2 2 3 4 1 Output 4 0 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 from collections import deque t=int(input()) for testcaess in range(t): n,m,a,b=list(map(int,input().split())) E=[[] for i in range(n+1)] for i in range(m): x,y=list(map(int,input().split())) E[x].append(y) E[y].append(x) USE1=[0]*(n+1) Q=deque() Q.append(a) USE1[a]=1 while Q: x=Q.pop() for to in E[x]: if to==b: continue if USE1[to]==0: USE1[to]=1 Q.append(to) USE2=[0]*(n+1) Q=deque() Q.append(b) USE2[b]=1 while Q: x=Q.pop() for to in E[x]: if to==a: continue if USE2[to]==0: USE2[to]=1 Q.append(to) #print(USE1,USE2) ANS1=0 ANS2=0 for i in range(n+1): if i==a or i==b: continue if USE1[i]==1 and USE2[i]==0: ANS1+=1 elif USE1[i]==0 and USE2[i]==1: ANS2+=1 print(ANS1*ANS2) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an $array$ of size $N$ and an integer $K$ ( $N > 1 , K > 0$ ). Each element in the array can be incremented by $K$ or decremented by $K$ $at$ $most$ $once$. So there will be $3^n$ possible combinations of final array. (As there are 3 options for every element). Out of these combinations, you have to select a combination, in which the $absolute$ difference between the largest and the smallest element is $maximum$. You have to print the $maximum$ $absolute$ $difference$. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a two lines of input - First line contains two integers $N, K$. - Second line contains $N$ space separated integers. -----Output:----- For each testcase, output the maximum absolute difference that can be achieved on a new line. -----Constraints----- - $1 \leq T \leq 10$ - $2 \leq N \leq 1000$ - $1 \leq K , arr[i] \leq 10000$ $NOTE$: Large input files, Use of fastio is recommended. -----Sample Input:----- 2 4 3 4 2 5 1 3 5 2 5 3 -----Sample Output:----- 10 13 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 testcases=int(input()) for _ in range(testcases): (N,K)=list(map(int,input().split())) array=list(map(int,input().split())) max=array[0] min=array[0] for i in array: if i>max: max=i if i<min: min=i max=max+K min=min-K print(abs(max-min)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Devu has n weird friends. Its his birthday today, so they thought that this is the best occasion for testing their friendship with him. They put up conditions before Devu that they will break the friendship unless he gives them a grand party on their chosen day. Formally, ith friend will break his friendship if he does not receive a grand party on dith day. Devu despite being as rich as Gatsby, is quite frugal and can give at most one grand party daily. Also, he wants to invite only one person in a party. So he just wonders what is the maximum number of friendships he can save. Please help Devu in this tough task !! -----Input----- - The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. - First line will contain a single integer denoting n. - Second line will contain n space separated integers where ith integer corresponds to the day dith as given in the problem. -----Output----- Print a single line corresponding to the answer of the problem. -----Constraints----- - 1 ≤ T ≤ 104 - 1 ≤ n ≤ 50 - 1 ≤ di ≤ 100 -----Example----- Input: 2 2 3 2 2 1 1 Output: 2 1 -----Explanation----- Example case 1. Devu can give party to second friend on day 2 and first friend on day 3, so he can save both his friendships. Example case 2. Both the friends want a party on day 1, and as the Devu can not afford more than one party a day, so he can save only one of the friendships, so 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 # cook your dish here test = int(input()) for _ in range(0,test): n = int(input()) lister = set(map(int,input().split())) print(len(lister)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Write a program that reads two numbers $X$ and $K$. The program first finds the factors of $X$ and then gives the sum of $K$th power of every factor. The program also finds the factor of $k$ and outputs the sum of $X$ times of every factor. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, two integers $X, R$. -----Output:----- For each testcase, output in a single line the factors of $X$ and the $K$th power of every factor, seperated by a space. -----Constraints----- - $1 \leq T \leq 1000$ - $2 \leq X, K \leq 10^9$ -----Sample Input:----- 1 8 6 -----Sample Output:----- 266304 88 -----EXPLANATION:----- Factors of x = 8 are 2, 4, and 8. Also, factors of k = 6 are 2, 3, and 6. 2^6 + 4^6 + 8^6 = 266304 and 2 × 8 + 3 × 8 + 6 × 8 = 88. (Where a ^b denotes a raised to the power of b). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python try: for _ in range(int(input())): s,s1=0,0 x,k=[int(i) for i in input().split()] for i in range(2,x+1): if(x%i==0): s=s+i**k for i in range(2,k+1): if(k%i==0): s1+=i*x print(s,s1) except EOFError as e: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. -----Input----- The first line contains a single integer — n (1 ≤ n ≤ 5·10^5). Each of the next n lines contains an integer s_{i} — the size of the i-th kangaroo (1 ≤ s_{i} ≤ 10^5). -----Output----- Output a single integer — the optimal number of visible kangaroos. -----Examples----- Input 8 2 5 7 6 9 8 4 2 Output 5 Input 8 9 1 6 2 6 5 8 3 Output 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # -*- coding: utf-8 -*- from time import perf_counter from sys import stdin def run(n, s): m = 0 small = n // 2 for big in range(n-1, (n+1)//2-1, -1): while small >= 0 and s[small] > s[big] / 2: small -= 1 if small == -1: break #print(small, big) small -= 1 m += 1 print(n-m) def run2(n, s): r = n - 1 l = n // 2 - 1 result = 0 while l >= 0: if s[l] * 2 <= s[r]: result += 1 r -= 1 l -= 1 print(n - result) n = int(input()) s = sorted([int(x) for x in stdin.read().strip().split('\n')]) run(n, s) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef was playing with numbers and he found that natural number N can be obtained by sum various unique natural numbers, For challenging himself chef wrote one problem statement, which he decided to solve in future. Problem statement: N can be obtained as the sum of Kth power of integers in multiple ways, find total number ways? After that Cheffina came and read what chef wrote in the problem statement, for having some fun Cheffina made some changes in the problem statement as. New problem statement: N can be obtained as the sum of Kth power of unique +ve integers in multiple ways, find total number ways? But, the chef is now confused, how to solve a new problem statement, help the chef to solve this new problem statement. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, two integers $N, K$. -----Output:----- For each test case, output in a single line answer to the problem statement. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 1000$ - $1 \leq K \leq 6$ -----Sample Input:----- 2 4 1 38 2 -----Sample Output:----- 2 1 -----EXPLANATION:----- For 1) 4 can be obtained by as [ 4^1 ], [1^1, 3^1], [2^1, 2^1]. (here ^ stands for power) But here [2^1, 2^1] is not the valid way because it is not made up of unique +ve integers. For 2) 38 can be obtained in the way which is [2^2, 3^2, 5^2] = 4 + 9 + 25 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())): x,n = map(int,input().split()) reach = [0]*(x+1) reach[0] = 1 i=1 while i**n<=x: j = 1 while j+i**n<=x: j+=1 j-=1 while j>=0: if reach[j]>0: reach[j+i**n]+=reach[j] j-=1 i+=1 #print(reach) print(reach[-1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a permutation $p_1, p_2, \ldots, p_n$. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment $1,2,\ldots, k$, in other words in the end there should be an integer $i$, $1 \leq i \leq n-k+1$ such that $p_i = 1, p_{i+1} = 2, \ldots, p_{i+k-1}=k$. Let $f(k)$ be the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation. You need to find $f(1), f(2), \ldots, f(n)$. -----Input----- The first line of input contains one integer $n$ ($1 \leq n \leq 200\,000$): the number of elements in the permutation. The next line of input contains $n$ integers $p_1, p_2, \ldots, p_n$: given permutation ($1 \leq p_i \leq n$). -----Output----- Print $n$ integers, the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation, for $k=1, 2, \ldots, n$. -----Examples----- Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 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 reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ class Binary_Indexed_Tree(): def __init__(self, n): self.n = n self.data = [0]*(n+1) def add(self, i, x): while i <= self.n: self.data[i] += x i += i & -i def get(self, i): return self.sum_range(i, i) def sum(self, i): ret = 0 while i: ret += self.data[i] i &= i-1 return ret def sum_range(self, l, r): return self.sum(r)-self.sum(l-1) def lower_bound(self, w): if w<=0: return 0 i = 0 k = 1<<(self.n.bit_length()) while k: if i+k <= self.n and self.data[i+k] < w: w -= self.data[i+k] i += k k >>= 1 return i+1 n = int(input()) a = list(map(int, input().split())) d = {j:i for i,j in enumerate(a)} BIT1 = Binary_Indexed_Tree(n) BIT2 = Binary_Indexed_Tree(n) BIT3 = Binary_Indexed_Tree(n) tentou = 0 ans = [] for i in range(n): tmp = 0 p = d[i+1] inv_p = n-p tentou += BIT1.sum(inv_p) BIT1.add(inv_p, 1) BIT2.add(p+1, 1) BIT3.add(p+1, p+1) m = i//2+1 mean = BIT2.lower_bound(i//2+1) tmp = 0 if i%2 == 0: tmp -= m*(m-1) else: tmp -= m*m tmp += tentou left = BIT3.sum_range(1, mean) right = BIT3.sum_range(mean, n) if i%2 == 0: left = mean*m - left right = right - mean*m else: left = mean*m - left right = right - mean*(m+1) tmp += left + right ans.append(tmp) print(*ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a binary string $s$ consisting of $n$ zeros and ones. Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones). Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100". You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$. The second line of the test case contains $n$ characters '0' and '1' — the string $s$. It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer: in the first line print one integer $k$ ($1 \le k \le n$) — the minimum number of subsequences you can divide the string $s$ to. In the second line print $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the number of subsequence the $i$-th character of $s$ belongs to. If there are several answers, you can print any. -----Example----- Input 4 4 0011 6 111111 5 10101 8 01010000 Output 2 1 2 2 1 6 1 2 3 4 5 6 1 1 1 1 1 1 4 1 1 1 1 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 import sys input=sys.stdin.readline #t=1 t=int(input()) for _ in range(t): n=int(input()) s=input().rstrip() s=[s[-i-1] for i in range(n)] ans=[] zero=[] one=[] res=[-1]*n pos=0 while s: b=s.pop() if b=="0": if not one: new=1 ans.append(new) res[pos]=len(ans) zero.append(len(ans)-1) else: id=one.pop() ans[id]+=1 res[pos]=id+1 zero.append(id) else: if not zero: new=1 ans.append(new) res[pos]=len(ans) one.append(len(ans)-1) else: id=zero.pop() ans[id]+=1 res[pos]=id+1 one.append(id) pos+=1 print(len(ans)) print(*res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X". Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 2^2 + 3^2 + 2^2 = 17. If there are no correct clicks in a play then the score for the play equals to 0. You know that the probability to click the i-th (1 ≤ i ≤ n) click correctly is p_{i}. In other words, the i-th character in the play sequence has p_{i} probability to be "O", 1 - p_{i} to be "X". You task is to calculate the expected score for your play. -----Input----- The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of clicks. The second line contains n space-separated real numbers p_1, p_2, ..., p_{n} (0 ≤ p_{i} ≤ 1). There will be at most six digits after the decimal point in the given p_{i}. -----Output----- Print a single real number — the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}. -----Examples----- Input 3 0.5 0.5 0.5 Output 2.750000000000000 Input 4 0.7 0.2 0.1 0.9 Output 2.489200000000000 Input 5 1 1 1 1 1 Output 25.000000000000000 -----Note----- For the first example. There are 8 possible outcomes. Each has a probability of 0.125. "OOO" → 3^2 = 9; "OOX" → 2^2 = 4; "OXO" → 1^2 + 1^2 = 2; "OXX" → 1^2 = 1; "XOO" → 2^2 = 4; "XOX" → 1^2 = 1; "XXO" → 1^2 = 1; "XXX" → 0. So the expected score is $\frac{9 + 4 + 2 + 1 + 4 + 1 + 1}{8} = 2.75$ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = input() read = input() p = [] for x in read.split(): p.append((float)(x)) v = 0.0 l = 0.0 for item in p: v = v*(1-item) + item*(v + 2*l + 1) l = (l + 1)*item print(v) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd. You are given a regular polygon with $2 \cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$. Let's name it as $2n$-gon. Your task is to find the square of the minimum size such that you can embed $2n$-gon in the square. Embedding $2n$-gon in the square means that you need to place $2n$-gon in the square in such way that each point which lies inside or on a border of $2n$-gon should also lie inside or on a border of the square. You can rotate $2n$-gon and/or the square. -----Input----- The first line contains a single integer $T$ ($1 \le T \le 200$) — the number of test cases. Next $T$ lines contain descriptions of test cases — one per line. Each line contains single odd integer $n$ ($3 \le n \le 199$). Don't forget you need to embed $2n$-gon, not an $n$-gon. -----Output----- Print $T$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $2n$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $10^{-6}$. -----Example----- Input 3 3 5 199 Output 1.931851653 3.196226611 126.687663595 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math T = int(input()) for _ in range(T): n = int(input()) diags = 1/math.sin(math.pi/2/n) print(diags * math.cos(math.pi/4/n)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. -----Input----- The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer type_{i} — type of the i-th event. If type_{i} = 1 or type_{i} = 2 then it is followed by an integer x_{i}. Otherwise it is followed by an integer t_{i} (1 ≤ type_{i} ≤ 3, 1 ≤ x_{i} ≤ n, 1 ≤ t_{i} ≤ q). -----Output----- Print the number of unread notifications after each event. -----Examples----- Input 3 4 1 3 1 1 1 2 2 3 Output 1 2 3 2 Input 4 6 1 2 1 4 1 2 3 3 1 3 1 3 Output 1 2 3 0 1 2 -----Note----- In the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). 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 python #-*-coding:utf-8 -*- import sys,collections n,q=list(map(int,input().split())) M=collections.defaultdict(collections.deque) Q=collections.deque() L=[] s=n=m=0 for _ in range(q): y,x=list(map(int,input().split())) if 2>y: s+=1 Q.append(x) M[x].append(n) n+=1 elif 3>y: y=M.get(x) if y: s-=len(y) del M[x] else: while x>m: z=Q.popleft() y=M.get(z) if y and y[0]<x: s-=1 y.popleft() if not y:del M[z] m+=1 L.append(s) sys.stdout.write('\n'.join(map(str,L))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is solving mathematics problems. He is preparing for Engineering Entrance exam. He's stuck in a problem. $f(n)=1^n*2^{n-1}*3^{n-2} * \ldots * n^{1} $ Help Chef to find the value of $f(n)$.Since this number could be very large, compute it modulo $1000000007$. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, $N$. -----Output:----- For each testcase, output in a single line the value of $f(n)$ mod $1000000007$. -----Constraints----- - $1 \leq T \leq 10^6$ - $1 \leq N \leq 10^6$ -----Subtasks----- Subtask 1(24 points) : - $1 \leq T \leq 5000$ - $1 \leq N \leq 5000$ Subtask 2(51 points) : original constraints -----Sample Input:----- 1 3 -----Sample Output:----- 12 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()) t=[] for _ in range(T): N=int(input()) t.append(N) N=max(t)+1 l=[0 for i in range(N)] p=1 a=1 for i in range(1,N): a=(a*i)%1000000007 p=p*a%1000000007 l[i]=p for i in t: print(l[i]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You're given an array $a$ of $n$ integers, such that $a_1 + a_2 + \cdots + a_n = 0$. In one operation, you can choose two different indices $i$ and $j$ ($1 \le i, j \le n$), decrement $a_i$ by one and increment $a_j$ by one. If $i < j$ this operation is free, otherwise it costs one coin. How many coins do you have to spend in order to make all elements equal to $0$? -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 5000$). Description of the test cases follows. The first line of each test case contains an integer $n$ ($1 \le n \le 10^5$)  — the number of elements. The next line contains $n$ integers $a_1, \ldots, a_n$ ($-10^9 \le a_i \le 10^9$). It is given that $\sum_{i=1}^n a_i = 0$. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case, print the minimum number of coins we have to spend in order to make all elements equal to $0$. -----Example----- Input 7 4 -3 5 -3 1 2 1 -1 4 -3 2 -3 4 4 -1 1 1 -1 7 -5 7 -6 -4 17 -13 4 6 -1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000 1 0 Output 3 0 4 1 8 3000000000 0 -----Note----- Possible strategy for the first test case: Do $(i=2, j=3)$ three times (free), $a = [-3, 2, 0, 1]$. Do $(i=2, j=1)$ two times (pay two coins), $a = [-1, 0, 0, 1]$. Do $(i=4, j=1)$ one time (pay one coin), $a = [0, 0, 0, 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()) while t>0 : n=int(input()) a=list(map(int,input().split())) an=0 s=0 for i in a : if s+i>=0 : s+=i else : s+=i an-=s s=0 print(an) t-=1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a colored permutation $p_1, p_2, \dots, p_n$. The $i$-th element of the permutation has color $c_i$. Let's define an infinite path as infinite sequence $i, p[i], p[p[i]], p[p[p[i]]] \dots$ where all elements have same color ($c[i] = c[p[i]] = c[p[p[i]]] = \dots$). We can also define a multiplication of permutations $a$ and $b$ as permutation $c = a \times b$ where $c[i] = b[a[i]]$. Moreover, we can define a power $k$ of permutation $p$ as $p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$. Find the minimum $k > 0$ such that $p^k$ has at least one infinite path (i.e. there is a position $i$ in $p^k$ such that the sequence starting from $i$ is an infinite path). It can be proved that the answer always exists. -----Input----- The first line contains single integer $T$ ($1 \le T \le 10^4$) — the number of test cases. Next $3T$ lines contain test cases — one per three lines. The first line contains single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the permutation. The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, $p_i \neq p_j$ for $i \neq j$) — the permutation $p$. The third line contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le n$) — the colors of elements of the permutation. It is guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$. -----Output----- Print $T$ integers — one per test case. For each test case print minimum $k > 0$ such that $p^k$ has at least one infinite path. -----Example----- Input 3 4 1 3 4 2 1 2 2 3 5 2 3 4 5 1 1 2 3 4 5 8 7 4 5 6 1 8 3 2 5 3 6 4 7 5 8 4 Output 1 5 2 -----Note----- In the first test case, $p^1 = p = [1, 3, 4, 2]$ and the sequence starting from $1$: $1, p[1] = 1, \dots$ is an infinite path. In the second test case, $p^5 = [1, 2, 3, 4, 5]$ and it obviously contains several infinite paths. In the third test case, $p^2 = [3, 6, 1, 8, 7, 2, 5, 4]$ and the sequence starting from $4$: $4, p^2[4]=8, p^2[8]=4, \dots$ is an infinite path since $c_4 = c_8 = 4$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin input = stdin.readline q = int(input()) for rwerew in range(q): n = int(input()) p = list(map(int,input().split())) c = list(map(int,input().split())) for i in range(n): p[i] -= 1 przyn = [0] * n grupa = [] i = 0 while i < n: if przyn[i] == 1: i += 1 else: nowa_grupa = [i] j = p[i] przyn[i] = 1 while j != i: przyn[j] = 1 nowa_grupa.append(j) j = p[j] grupa.append(nowa_grupa) grupacol = [] for i in grupa: cyk = [] for j in i: cyk.append(c[j]) grupacol.append(cyk) #print(grupacol) mini = 234283742834 for cykl in grupacol: dziel = [] d = 1 while d**2 <= len(cykl): if len(cykl)%d == 0: dziel.append(d) d += 1 dodat = [] for d in dziel: dodat.append(len(cykl)/d) dziel_ost = list(map(int,dziel + dodat)) #print(dziel_ost, len(cykl)) for dzielnik in dziel_ost: for i in range(dzielnik): indeks = i secik = set() chuj = True while indeks < len(cykl): secik.add(cykl[indeks]) indeks += dzielnik if len(secik) > 1: chuj = False break if chuj: mini = min(mini, dzielnik) print(mini) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Bharat was given a problem to solve, by his brother, Lord Ram. The problem was like, given integers, $N$ and $K$, Bharat has to find the number (possibilities) of non-increasing arrays of length $K$, where each element of the array is between $1$ and $N$ (both inclusive). He was confused, regarding this problem. So, help him solve the problem, so that, he can give the answer of the problem, to his brother, Lord Rama. Since, the number of possible sub-arrays can be large, Bharat has to answer the problem as "number of possible non-increasing arrays", modulo $10^9$ $+$ $7$. -----Input:----- - Two space-seperated integers, $N$ and $K$. -----Output:----- - Output in a single line, the number of possible non-increasing arrays, modulo $10^9$ $+$ $7$. -----Constraints:----- - $1 \leq N, K \leq 2000$ -----Sample Input:----- 2 5 -----Sample Output:----- 6 -----Explanation:----- - Possible Arrays, for the "Sample Case" are as follows: - {1, 1, 1, 1, 1} - {2, 1, 1, 1, 1} - {2, 2, 1, 1, 1} - {2, 2, 2, 1, 1} - {2, 2, 2, 2, 1} - {2, 2, 2, 2, 2} - Hence, the answer to the "Sample Case" is $6$ ($6$ % ($10^9$ $+$ $7$)). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math p=7+10**9 n,k=list(map(int,input().split())) c=math.factorial(n+k-1)//((math.factorial(k))*(math.factorial(n-1))) print(c%p) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Once, a genius guy Cristo visited NASA where he met many scientists. A young intern Mark at NASA asked Cristo to observe the strange behaviour of two independent particles (say Alpha and Beta) moving in the free space.Cristo was astonished to see the movement of Alpha and Beta. However, he formulated a procedure to evaluate the distance covered by the particles in given time. The procedure calculates the distance covered by Alpha and Beta for a given time. Mark, however struggles to evaluate the procedure manually and asks you to help him. Cristo's Procedure :- alpha = 0 beta = 0 Procedure CristoSutra( Ti ) : if Ti <= 0 : alpha = alpha + 1 else if Ti == 1 : beta = beta + 1 else : CristoSutra(Ti-1) CristoSutra(Ti-2) CristoSutra(Ti-3) end procedure Note: Print the answer by taking mod from 109+7 . -----Constraints:----- - 1<=T<=105 - 1<=Ti<=105 -----Input Format:----- First line consists an integer t, number of Test cases.For each test case, there is an integer denoting time Ti. -----Output Format:----- For each test case, a single output line contains two space seperated numbers ,distance covered by alpha and beta in the given time. -----Subtasks:----- Subtask 1 (30 points) - 1<=T<=10 - 1<=Ti<=1000 Subtask 2 (70 points) original contraints Sample Input: 2 1 2 Sample Output: 0 1 2 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(eval(input())): n=eval(input()) mod=1000000007 f1,f2=[0]*101000,[0]*101000 f1[1]=0 f1[2]=2 f1[3]=3 f2[1]=1 f2[2]=1 f2[3]=2; for i in range(4,100001): f1[i]=f1[i-1]%mod+f1[i-2]%mod+f1[i-3]%mod f2[i]=f2[i-1]%mod+f2[i-2]%mod+f2[i-3]%mod print(f1[n]%mod,f2[n]%mod) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given N integer sequences A1, A2, ..., AN. Each of these sequences contains N elements. You should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1. Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead. -----Input----- - The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains a single integer N. - N lines follow. For each valid i, the i-th of these lines contains N space-separated integers Ai1, Ai2, ..., AiN denoting the elements of the sequence Ai. -----Output----- For each test case, print a single line containing one integer — the maximum sum of picked elements. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 700 - 1 ≤ sum of N in all test-cases ≤ 3700 - 1 ≤ Aij ≤ 109 for each valid i, j -----Subtasks----- Subtask #1 (18 points): 1 ≤ Aij ≤ N for each valid i, j Subtask #2 (82 points): original constraints -----Example----- Input: 1 3 1 2 3 4 5 6 7 8 9 Output: 18 -----Explanation----- Example case 1: To maximise the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for _ in range(t): n=int(input()) grid=[] for _ in range(n): temp=[] temp=list(map(int,input().strip().split())) temp.sort() grid.append(temp) curr=max(grid[n-1]) total=curr for i in range(n-2,0-1,-1): flag=0 for j in range(n-1,0-1,-1): if grid[i][j]<curr: flag=1 curr=grid[i][j] total+=curr break if flag==0: total=-1 break print(total) ```