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: Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is. You are to determine the total number of times Vasily takes the top card from the deck. -----Input----- The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck. The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100 000), where a_{i} is the number written on the i-th from top card in the deck. -----Output----- Print the total number of times Vasily takes the top card from the deck. -----Examples----- Input 4 6 3 1 2 Output 7 Input 1 1000 Output 1 Input 7 3 3 3 3 3 3 3 Output 7 -----Note----- In the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) s = list(map(int,input().split(' '))) a = [] for i in range(max(s)): a.append([]) for i in range(len(s)): a[s[i]-1].append(i) a = list([x for x in a if x != []]) if len(a) > 1: for i in range(1,len(a)): if len(a[i]) > 1: s = a[i-1][-1] if s > a[i][0] and s < a[i][-1]: for j in range(1,len(a[i])): if s < a[i][j]: a[i] = a[i][j:] + a[i][:j] break t = [] for i in a: t += i c = 0 x = t[0] + 1 i = n-1 while i > 0: if t[i] < t[i-1]: k = t[i] - t[i-1] + n else: k = t[i] - t[i-1] c += k x -= c//n i -= 1 print(c+x) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today is rose day, batch mates of Kabir and Tara decided to celebrate this day by exchanging roses with each other. Note:$Note:$ exchanging means both the boy and the girl will give rose to each other. In the class there are B$B$ boys and G$G$ girls. Exchange of rose will take place if and only if at least one of them hasn't received a rose from anyone else and a rose can be exchanged only once. Tara has to bring maximum sufficient roses for everyone and is confused as she don't know how many roses to buy.You are a friend of Kabir, so help him to solve the problem so that he can impress Tara by helping her. -----Input:----- - First line will contain T$T$, number of test cases. - Each test case contains two space separated integers B$B$ (Number of boys) and G$G$ (Number of Girls). -----Output:----- For each test case, output in a single line the total number of roses exchanged. -----Constraints:----- - 1≤T≤105$1 \leq T \leq 10^5$ - 1≤B≤109$1 \leq B \leq 10^{9}$ - 1≤G≤109$1 \leq G \leq 10^{9}$ -----Sample Input:----- 1 2 3 -----Sample Output:----- 8 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())): print(2*(sum(list(map(int, input().split())))-1)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Tired of the overpopulated world, Miu - The introverted cat visits a new continent in search for a new house. There are $N$ houses lying on the X-axis. Their positions are given by $X$$i$ , where $i$ refers to the $i$th house. ( $1 <= i <= N$ ) Each of these positions are pairwise distinct Miu is supposed to choose one of these houses for herself. Miu defines a term - The Distance of Peace, as the minimum distance from her house to any other house. Miu wonders what is maximum Distance of Peace she can obtain. Can you help her? -----Input:----- - The first line of the input consists of a single integer $T$, denoting the number of test cases - The first line of each test case consists of a single integer $N$ - The second line of each test case consists of $N$ space-separated integers $X$$1$ $X$$2$ $X$$3$ … $X$$N$ -----Output:----- - For each test case print the answer in a single line, the maximum Distance of Peace Miu can obtain -----Constraints----- - 1 <= $T$ <= 100 - 2 <= $N$ <= 105 - -109 <= $X$$i$ <= 109 - Sum of $N$ over all test cases does not exceed 106 -----Subtasks----- Subtask #1 (30 points): - $N$ <= 103 Subtask #2 (70 points): - Original Constraints -----Sample Input:----- 2 6 7 -1 2 13 -5 15 4 6 10 3 12 -----Sample Output:----- 5 3 -----EXPLANATION:----- Test Case 1: The $1$st house has the maximum Distance of Peace, which is from the $3$rd house: $| 7 - 2 | = 5$ Hence, the answer is $5$ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) for i in range(n) : t = int(input()) li = sorted(list(map(int , input().split()))) ans = 1 dp = [li[1]-li[0]] + [0] * (t-2) + [li[t-1] - li[t-2]] for i in range(1 , t-1) : dp[i] = min(li[i] - li[i-1] , li[i+1] - li[i]) print(max(dp)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is having one string of English lower case alphabets only. The chef wants to remove all "abc" special pairs where a,b,c are occurring consecutively. After removing the pair, create a new string and again remove "abc" special pair from a newly formed string. Repeate the process until no such pair remains in a string. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, $String$. -----Output:----- For each testcase, output in a single line answer, new String with no "abc" special pair. -----Constraints:----- $T \leq 2 $ $1 \leq String length \leq 1000 $ -----Sample Input:----- 2 aabcc bababccc -----Sample Output:----- ac bc -----EXPLANATION:----- For 1) after removing "abc" at middle we get a new string as ac. For 2) string = bababccc newString1 = babcc // After removing middle "abc" newString2 = bc //After removing "abc" The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): s=input() while(s.count("abc")!=0): s=s.replace("abc","") print(s) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Unlucky year in Berland is such a year that its number n can be represented as n = x^{a} + y^{b}, where a and b are non-negative integer numbers. For example, if x = 2 and y = 3 then the years 4 and 17 are unlucky (4 = 2^0 + 3^1, 17 = 2^3 + 3^2 = 2^4 + 3^0) and year 18 isn't unlucky as there is no such representation for it. Such interval of years that there are no unlucky years in it is called The Golden Age. You should write a program which will find maximum length of The Golden Age which starts no earlier than the year l and ends no later than the year r. If all years in the interval [l, r] are unlucky then the answer is 0. -----Input----- The first line contains four integer numbers x, y, l and r (2 ≤ x, y ≤ 10^18, 1 ≤ l ≤ r ≤ 10^18). -----Output----- Print the maximum length of The Golden Age within the interval [l, r]. If all years in the interval [l, r] are unlucky then print 0. -----Examples----- Input 2 3 1 10 Output 1 Input 3 5 10 22 Output 8 Input 2 3 3 5 Output 0 -----Note----- In the first example the unlucky years are 2, 3, 4, 5, 7, 9 and 10. So maximum length of The Golden Age is achived in the intervals [1, 1], [6, 6] and [8, 8]. In the second example the longest Golden Age is the interval [15, 22]. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python x,y,l,r=list(map(int,input().split())) b=set() a=0 b.add(l-1) b.add(r+1) for i in range(100): xx=x**i if xx>r: break for j in range(100): rr=xx+(y**j) if rr>r: break if rr>=l: b.add(rr) b=sorted(list(b)) for i in range(1,len(b)): a=max(a,b[i]-b[i-1]-1) print(a) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is playing a game with his brother Chefu. He asked Chefu to choose a positive integer $N$, multiply it by a given integer $A$, then choose a divisor of $N$ (possibly $N$ itself) and add it to the product. Let's denote the resulting integer by $M$; more formally, $M = A \cdot N + d$, where $d$ is some divisor of $N$. Chefu told Chef the value of $M$ and now, Chef should guess $N$. Help him find all values of $N$ which Chefu could have chosen. -----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 $A$ and $M$. -----Output----- For each test case, print two lines. The first line should contain a single integer $C$ denoting the number of possible values of $N$. The second line should contain $C$ space-separated integers denoting all possible values of $N$ in increasing order. It is guaranteed that the sum of $C$ over all test cases does not exceed $10^7$. -----Constraints----- - $1 \le T \le 100$ - $2 \le M \le 10^{10}$ - $1 \le A < M$ -----Subtasks----- Subtask #1 (50 points): - $M \le 10^6$ Subtask #2 (50 points): original constraints -----Example Input----- 3 3 35 5 50 4 65 -----Example Output----- 1 10 0 3 13 15 16 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math def divisors(n): arr = [] for i in range(1,1+int(math.ceil(math.sqrt(n)))): if n%i == 0: arr.append(i) arr.append(n//i) arr = list(sorted(set(arr))) return arr try: t = int(input()) while t: t -= 1 a,m = map(int, input().split()) divs = divisors(m) ans = [] for d in divs: q = (m//d-1)/a if q%1 == 0 and q>0: ans.append((int(d*q))) ans.sort() print(len(ans)) for i in ans: print(i, end = ' ') print() except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Every day, Mike goes to his job by a bus, where he buys a ticket. On the ticket, there is a letter-code that can be represented as a string of upper-case Latin letters. Mike believes that the day will be successful in case exactly two different letters in the code alternate. Otherwise, he believes that the day will be unlucky. Please see note section for formal definition of alternating code. You are given a ticket code. Please determine, whether the day will be successful for Mike or not. Print "YES" or "NO" (without quotes) corresponding to the situation. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first and only line of each test case contains a single string S denoting the letter code on the ticket. -----Output----- For each test case, output a single line containing "YES" (without quotes) in case the day will be successful and "NO" otherwise. -----Note----- Two letters x, y where x != y are said to be alternating in a code, if code is of form "xyxyxy...". -----Constraints----- - 1 ≤ T ≤ 100 - S consists only of upper-case Latin letters Subtask 1 (50 points): - |S| = 2 Subtask 2 (50 points): - 2 ≤ |S| ≤ 100 -----Example----- Input: 2 ABABAB ABC Output: YES NO The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def res(s): if len(s) == 2: if s[0] == s[1]: print("NO") else: print("YES") elif s[0] != s[1]: counte = 0 for i in range(2, len(s)): if i % 2 == 0: if s[i] != s[0]: counte = 1 break else: if s[i] != s[1]: counte = 1 break if counte == 0: print("YES") else: print("NO") else: print("NO") def __starting_point(): t = int(input()) for _ in range(t): stri = str(input()) res(stri) __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef owns an icecream shop in Chefland named scoORZ. There are only three types of coins in Chefland: Rs. 5, Rs. 10 and Rs. 15. An icecream costs Rs. 5. There are $N$ people (numbered $1$ through $N$) standing in a queue to buy icecream from scoORZ. Each person wants to buy exactly one icecream. For each valid $i$, the $i$-th person has one coin with value $a_i$. It is only possible for someone to buy an icecream when Chef can give them back their change exactly ― for example, if someone pays with a Rs. 10 coin, Chef needs to have a Rs. 5 coin that he gives to this person as change. Initially, Chef has no money. He wants to know if he can sell icecream to everyone in the queue, in the given order. Since he is busy eating his own icecream, can you tell him if he can serve all these people? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $a_1, a_2, \ldots, a_N$. -----Output----- For each test case, print a single line containing the string "YES" if all people can be served or "NO" otherwise (without quotes). -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 10^3$ - $a_i \in \{5, 10, 15\}$ for each valid $i$ -----Subtasks----- Subtask #1 (40 points): $a_i \in \{5, 10\}$ for each valid $i$ Subtask #2 (60 points): original constraints -----Example Input----- 3 2 5 10 2 10 5 2 5 15 -----Example Output----- YES NO NO -----Explanation----- Example case 1: The first person pays with a Rs. 5 coin. The second person pays with a Rs. 10 coin and Chef gives them back the Rs. 5 coin (which he got from the first person) as change. Example case 2: The first person already cannot buy an icecream because Chef cannot give them back Rs. 5. Example case 3: The first person pays with a Rs. 5 coin. The second person cannot buy the icecream because Chef has only one Rs. 5 coin, but he needs to give a total of Rs. 10 back as change. 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()) lst=list(map(int,input().split())) f=0 t=0 p=1 for i in lst: if(i==5): f+=1 elif(i==10): if(f>0): f-=1 t+=1 else: p=0 break else: if(t>0): t-=1 else: if(f>1): f-=2 else: p=0 break if(p==1): print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Rani is teaching Raju maths via a game called N-Cube, which involves three sections involving N. Rani gives Raju a number N, and Raju makes a list of Nth powers of integers in increasing order (1^N, 2^N, 3^N.. so on). This teaches him exponentiation. Then Raju performs the following subtraction game N times : Take all pairs of consecutive numbers in the list and take their difference. These differences then form the new list for the next iteration of the game. Eg, if N was 6, the list proceeds as [1, 64, 729, 4096 ... ] to [63, 685, 3367 ...], and so on 5 more times. After the subtraction game, Raju has to correctly tell Rani the Nth element of the list. This number is the value of the game. After practice Raju became an expert in the game. To challenge him more, Rani will give two numbers M (where M is a prime) and R instead of just a single number N, and the game must start from M^(R - 1) instead of N. Since the value of the game can now become large, Raju just have to tell the largest integer K such that M^K divides this number. Since even K can be large, output K modulo 1000000007 (109+7). -----Input----- First line will contain T, number of testcases. Then the testcases follow Each testcase contains of a single line of input, two integers M R -----Output----- For each testcase, output in a single line answer given by Raju to Rani modulo 1000000007. -----Constraints----- 1<=T<=1000 2<=M<=109 30 points : 1<=R<=10000 70 points : 1<=R<=109 M is a prime number -----Example----- Input: 1 2 2 Output: 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python tc=int(input()) for case in range(tc): m,r=list(map(int,input().split())) n=m**(r-1) a=[i**n for i in range(1,2*n+1)] tmp=2*n-1 for i in range(n): for j in range(tmp-i): a[j]=a[j+1]-a[j] print((a[n-1]/m)%1000000007) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes). The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation. -----Input----- The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 10^5 digits. -----Output----- In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem. -----Examples----- Input 101 Output 11 Input 110010 Output 11010 -----Note----- In the first sample the best strategy is to delete the second digit. That results in number 11_2 = 3_10. In the second sample the best strategy is to delete the third or fourth digits — that results in number 11010_2 = 26_10. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python x = input () flag = 0 s = 0 for each_item in x: if each_item == '0': if flag == 0: flag = 1; continue else: print (each_item, end = '') else: if (s == len (x) - 1 and flag == 0) : continue print (each_item, end = '') s = s + 1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In the State of Takahashi in AtCoderian Federation, there are N cities, numbered 1, 2, ..., N. M bidirectional roads connect these cities. The i-th road connects City A_i and City B_i. Every road connects two distinct cities. Also, for any two cities, there is at most one road that directly connects them. One day, it was decided that the State of Takahashi would be divided into two states, Taka and Hashi. After the division, each city in Takahashi would belong to either Taka or Hashi. It is acceptable for all the cities to belong Taka, or for all the cities to belong Hashi. Here, the following condition should be satisfied: - Any two cities in the same state, Taka or Hashi, are directly connected by a road. Find the minimum possible number of roads whose endpoint cities belong to the same state. If it is impossible to divide the cities into Taka and Hashi so that the condition is satisfied, print -1. -----Constraints----- - 2 \leq N \leq 700 - 0 \leq M \leq N(N-1)/2 - 1 \leq A_i \leq N - 1 \leq B_i \leq N - A_i \neq B_i - If i \neq j, at least one of the following holds: A_i \neq A_j and B_i \neq B_j. - If i \neq j, at least one of the following holds: A_i \neq B_j and B_i \neq A_j. -----Input----- Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M -----Output----- Print the answer. -----Sample Input----- 5 5 1 2 1 3 3 4 3 5 4 5 -----Sample Output----- 4 For example, if the cities 1, 2 belong to Taka and the cities 3, 4, 5 belong to Hashi, the condition is satisfied. Here, the number of roads whose endpoint cities belong to the same state, is 4. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import deque N, M = list(map(int, input().split())) adj = [[1 for _ in range(N + 1)] for _ in range(N + 1)] for _ in range(M): a, b = list(map(int, input().split())) adj[a][b] = 0 adj[b][a] = 0 adj_inv = [[] for _ in range(N + 1)] for i in range(1, N+1): for j in range(i+1, N+1): if adj[i][j] == 1: adj_inv[i].append(j) adj_inv[j].append(i) seen = [0] * (N+1) num = [] for i in range(1, N+1): if seen[i] == 0: plus = 0 minus = 0 que = deque() que.append(i) seen[i] = 1 plus += 1 while que: v = que.pop() u_list = adj_inv[v] for u in u_list: if seen[u] == 0: que.append(u) seen[u] = -seen[v] if seen[u] == 1: plus += 1 else: minus += 1 else: if seen[u] == seen[v]: print((-1)) return num.append((min(plus, minus), max(plus, minus))) min_sum = 0 add = [] for i in range(len(num)): min_sum += num[i][0] add.append(num[i][1] - num[i][0]) dp = [[0 for _ in range((N // 2) + 1)] for _ in range(len(add) + 1)] dp[0][min_sum] = 1 for i in range(len(add)): for j in range(min_sum, (N // 2) + 1): if dp[i][j] == 1: if j + add[i] <= (N // 2): dp[i+1][j+add[i]] = 1 dp[i+1][j] = 1 dp_last = dp[-1] for i in range(len(dp_last)-1, -1, -1): if dp_last[i] == 1: N1 = i break print(((N1 * (N1 - 1)) // 2 + ((N - N1) * (N - N1 - 1)) // 2)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system. Since the number n on the board was small, Vova quickly guessed which x could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. Write such a program for Vova. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^9). -----Output----- In the first line print one integer k — number of different values of x satisfying the condition. In next k lines print these values in ascending order. -----Examples----- Input 21 Output 1 15 Input 20 Output 0 -----Note----- In the first test case x = 15 there is only one variant: 15 + 1 + 5 = 21. In the second test case there are no such x. 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()) q=[] for i in range(max(0,n-100),n+1): j=i res=i while j: res+=j%10 j//=10 if res==n: q.append(i) print(len(q)) for i in q: print(i) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: and Bengali as well. There are N$N$ cats (numbered 1$1$ through N$N$) and M$M$ rats (numbered 1$1$ through M$M$) on a line. Each cat and each rat wants to move from some point to some (possibly the same) point on this line. Naturally, the cats also want to eat the rats when they get a chance. Both the cats and the rats can only move with constant speed 1$1$. For each valid i$i$, the i$i$-th cat is initially sleeping at a point a_i$a_i$. At a time s_i$s_i$, this cat wakes up and starts moving to a final point b_i$b_i$ with constant velocity and without any detours (so it arrives at this point at the time e_i = s_i + |a_i-b_i|$e_i = s_i + |a_i-b_i|$). After it arrives at the point b_i$b_i$, it falls asleep again. For each valid i$i$, the i$i$-th rat is initially hiding at a point c_i$c_i$. At a time r_i$r_i$, this rat stops hiding and starts moving to a final point d_i$d_i$ in the same way as the cats ― with constant velocity and without any detours, arriving at the time q_i = r_i + |c_i-d_i|$q_i = r_i + |c_i-d_i|$ (if it does not get eaten). After it arrives at the point d_i$d_i$, it hides again. If a cat and a rat meet each other (they are located at the same point at the same time), the cat eats the rat, the rat disappears and cannot be eaten by any other cat. A sleeping cat cannot eat a rat and a hidden rat cannot be eaten ― formally, cat i$i$ can eat rat j$j$ only if they meet at a time t$t$ satisfying s_i \le t \le e_i$s_i \le t \le e_i$ and r_j \le t \le q_j$r_j \le t \le q_j$. Your task is to find out which rats get eaten by which cats. It is guaranteed that no two cats will meet a rat at the same time. -----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 \le i \le N$1 \le i \le N$), the i$i$-th of these lines contains three space-separated integers a_i$a_i$, b_i$b_i$ and s_i$s_i$. - M$M$ more lines follow. For each i$i$ (1 \le i \le M$1 \le i \le M$), the i$i$-th of these lines contains three space-separated integers c_i$c_i$, d_i$d_i$ and r_i$r_i$. -----Output----- For each test case, print M$M$ lines. For each valid i$i$, the i$i$-th of these lines should contain a single integer ― the number of the cat that will eat the i$i$-th rat, or -1$-1$ if no cat will eat this rat. -----Constraints----- - 1 \le T \le 10$1 \le T \le 10$ - 0 \le N \le 1,000$0 \le N \le 1,000$ - 1 \le M \le 1,000$1 \le M \le 1,000$ - 1 \le a_i, b_i, s_i \le 10^9$1 \le a_i, b_i, s_i \le 10^9$ for each valid i$i$ - 1 \le c_i, d_i, r_i \le 10^9$1 \le c_i, d_i, r_i \le 10^9$ for each valid i$i$ - all initial and final positions of all cats and rats are pairwise distinct -----Example Input----- 2 8 7 2 5 1 1 4 1 9 14 10 20 7 9 102 99 1 199 202 1 302 299 3 399 402 3 6 3 1 10 15 10 100 101 1 201 200 1 300 301 5 401 400 5 1000 1010 1020 8 8 2 8 2 12 18 2 22 28 4 32 38 4 48 42 2 58 52 3 68 62 1 78 72 3 3 6 3 13 19 3 21 25 3 31 39 3 46 43 4 59 53 2 65 61 4 79 71 2 -----Example Output----- 1 4 5 6 7 8 -1 1 2 3 4 5 6 7 8 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here class Animal: def __init__(self): start, end, starting_time = map(int, input().split()) self.ending_time = starting_time + abs(start - end) self.velocity = 1 if end >= start else -1 self.eaten_by = -1, 10 ** 10 self.start = start self.end = end self.starting_time = starting_time def will_collide(self, z): if self.starting_time > z.ending_time or self.ending_time < z.starting_time: return False if self.velocity == z.velocity: if self.starting_time > z.starting_time: self, z = z, self if z.start == self.start + self.velocity * (z.starting_time - self.starting_time): return z.starting_time else: return False if self.velocity == -1: self, z = z, self t = ( z.start - self.start + z.starting_time + self.starting_time ) / 2 return t if self.starting_time <= t <= self.ending_time and z.starting_time <= t <= z.ending_time else False def main(): for _ in range(int(input())): no_cats, no_rats = map(int, input().split()) Cats = [Animal() for i in range(no_cats)] for i in range(no_rats): rat = Animal() for j in range(no_cats): time = rat.will_collide(Cats[j]) if time: # print(time) if time < rat.eaten_by[1]: rat.eaten_by = j + 1, time print(rat.eaten_by[0]) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is very fond of horses. He enjoys watching them race. As expected, he has a stable full of horses. He, along with his friends, goes to his stable during the weekends to watch a few of these horses race. Chef wants his friends to enjoy the race and so he wants the race to be close. This can happen only if the horses are comparable on their skill i.e. the difference in their skills is less. There are N horses in the stable. The skill of the horse i is represented by an integer S[i]. The Chef needs to pick 2 horses for the race such that the difference in their skills is minimum. This way, he would be able to host a very interesting race. Your task is to help him do this and report the minimum difference that is possible between 2 horses in the race. -----Input:----- First line of the input file contains a single integer T, the number of test cases. Every test case starts with a line containing the integer N. The next line contains N space separated integers where the i-th integer is S[i]. -----Output:----- For each test case, output a single line containing the minimum difference that is possible. -----Constraints:----- 1 ≤ T ≤ 10 2 ≤ N ≤ 5000 1 ≤ S[i] ≤ 1000000000 -----Example:-----Input: 1 5 4 9 1 32 13 Output: 3 Explanation: The minimum difference can be achieved if we pick horses with skills 1 and 4 for the race. 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()) for q in range(t): l=eval(input()) a=input().split() a=[int(x) for x in a] a=sorted(a) for i in range(l-1): a[i]=(a[i+1]-a[i]) print(min(a[0:l-1])) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given are integer sequence of length N, A = (A_1, A_2, \cdots, A_N), and an integer K. For each X such that 1 \le X \le K, find the following value: \left(\displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} (A_L+A_R)^X\right) \bmod 998244353 -----Constraints----- - All values in input are integers. - 2 \le N \le 2 \times 10^5 - 1 \le K \le 300 - 1 \le A_i \le 10^8 -----Input----- Input is given from Standard Input in the following format: N K A_1 A_2 \cdots A_N -----Output----- Print K lines. The X-th line should contain the value \left(\displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} (A_L+A_R)^X \right) \bmod 998244353. -----Sample Input----- 3 3 1 2 3 -----Sample Output----- 12 50 216 In the 1-st line, we should print (1+2)^1 + (1+3)^1 + (2+3)^1 = 3 + 4 + 5 = 12. In the 2-nd line, we should print (1+2)^2 + (1+3)^2 + (2+3)^2 = 9 + 16 + 25 = 50. In the 3-rd line, we should print (1+2)^3 + (1+3)^3 + (2+3)^3 = 27 + 64 + 125 = 216. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import numpy as np N,K = list(map(int,input().split())) A=np.array(list(map(int,input().split()))) mod = 998244353 fact = [1]*(K+1) for i in range(1,K+1): fact[i]=i*fact[i-1]%mod inv_fact = [pow(f,mod-2,mod) for f in fact] # r = [sum(pow(aa,t,mod) for aa in A)%mod for t in range(K+1)]##遅い r = [0]*(K+1) r[0] = N temp = np.ones(N,dtype="int32") for i in range(1,K+1): temp = temp*A%mod r[i] = int(np.sum(temp))%mod inv2 = pow(2,mod-2,mod) for x in range(1,K+1): ans = sum((fact[x]*inv_fact[t]*inv_fact[x-t] *r[x-t]*r[t]) %mod for t in range(x+1))%mod ans-= r[x]*pow(2,x,mod) %mod print(((ans*inv2)%mod)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers $a$ and $b$ and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of ($a \oplus x$) + ($b \oplus x$) for any given $x$, where $\oplus$ denotes the bitwise XOR operation. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^{4}$). Description of the test cases follows. The only line of each test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^{9}$). -----Output----- For each testcase, output the smallest possible value of the given expression. -----Example----- Input 6 6 12 4 9 59 832 28 14 4925 2912 1 1 Output 10 13 891 18 6237 0 -----Note----- For the first test case Sana can choose $x=4$ and the value will be ($6 \oplus 4$) + ($12 \oplus 4$) = $2 + 8$ = $10$. It can be shown that this is the smallest possible value. 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): a, b = list(map(int, input().split())) print(a ^ b) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets. But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition A_{i} ≥ B_{j} holds. Help Leha rearrange the numbers in the array A so that the sum $\sum_{i = 1}^{m} F(A_{i}^{\prime}, B_{i})$ is maximally possible, where A' is already rearranged array. -----Input----- First line of input data contains single integer m (1 ≤ m ≤ 2·10^5) — length of arrays A and B. Next line contains m integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — array A. Next line contains m integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 10^9) — array B. -----Output----- Output m integers a'_1, a'_2, ..., a'_{m} — array A' which is permutation of the array A. -----Examples----- Input 5 7 3 5 3 4 2 1 3 2 3 Output 4 7 3 5 3 Input 7 4 6 5 8 8 2 6 2 1 2 2 1 1 2 Output 2 6 4 5 8 8 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ Author : Arif Ahmad Date : Algo : Difficulty : """ from sys import stdin, stdout, setrecursionlimit import threading def main(): m = int(stdin.readline().strip()) a = [int(_) for _ in stdin.readline().strip().split()] b = [int(_) for _ in stdin.readline().strip().split()] c = [] for i, v in enumerate(b): c.append((v, i)) a = sorted(a, reverse=True) c = sorted(c) ans = [0 for i in range(m)] j = 0 for v, i in c: ans[i] = a[j] j += 1 stdout.write(' '.join(str(_) for _ in ans)) def __starting_point(): # the following 4 lines of code are required to increase # the recursion limit and stack size # * if is cause any problem, comment out the lines, # * and just call main() setrecursionlimit(10**6) threading.stack_size(134217728) # 128MB thread = threading.Thread(target=main) thread.start() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let us consider the following operations on a string consisting of A and B: - Select a character in a string. If it is A, replace it with BB. If it is B, replace with AA. - Select a substring that is equal to either AAA or BBB, and delete it from the string. For example, if the first operation is performed on ABA and the first character is selected, the string becomes BBBA. If the second operation is performed on BBBAAAA and the fourth through sixth characters are selected, the string becomes BBBA. These operations can be performed any number of times, in any order. You are given two string S and T, and q queries a_i, b_i, c_i, d_i. For each query, determine whether S_{a_i} S_{{a_i}+1} ... S_{b_i}, a substring of S, can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, a substring of T. -----Constraints----- - 1 \leq |S|, |T| \leq 10^5 - S and T consist of letters A and B. - 1 \leq q \leq 10^5 - 1 \leq a_i \leq b_i \leq |S| - 1 \leq c_i \leq d_i \leq |T| -----Input----- Input is given from Standard Input in the following format: S T q a_1 b_1 c_1 d_1 ... a_q b_q c_q d_q -----Output----- Print q lines. The i-th line should contain the response to the i-th query. If S_{a_i} S_{{a_i}+1} ... S_{b_i} can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, print YES. Otherwise, print NO. -----Sample Input----- BBBAAAABA BBBBA 4 7 9 2 5 7 9 1 4 1 7 2 5 1 7 2 4 -----Sample Output----- YES NO YES NO The first query asks whether the string ABA can be made into BBBA. As explained in the problem statement, it can be done by the first operation. The second query asks whether ABA can be made into BBBB, and the fourth query asks whether BBBAAAA can be made into BBB. Neither is possible. The third query asks whether the string BBBAAAA can be made into BBBA. As explained in the problem statement, it can be done by the second operation. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python S = input() SA = [0] n = 0 for c in S: if c=='A': n+=1 SA.append(n) T = input() TA = [0] n = 0 for c in T: if c=='A': n+=1 TA.append(n) q = int(input()) for _ in range(q): a, b, c, d = list(map(int, input().split())) nSA = SA[b]-SA[a-1] nSB = b-a+1-nSA nTA = TA[d]-TA[c-1] nTB = d-c+1-nTA print(('YES' if (nSA-nSB)%3 == (nTA-nTB)%3 else 'NO')) ```
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$ non-negative integers. You have to choose a non-negative integer $x$ and form a new array $b$ of size $n$ according to the following rule: for all $i$ from $1$ to $n$, $b_i = a_i \oplus x$ ($\oplus$ denotes the operation bitwise XOR). An inversion in the $b$ array is a pair of integers $i$ and $j$ such that $1 \le i < j \le n$ and $b_i > b_j$. You should choose $x$ in such a way that the number of inversions in $b$ is minimized. If there are several options for $x$ — output the smallest one. -----Input----- First line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of elements in $a$. Second line contains $n$ space-separated integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of $a$. -----Output----- Output two integers: the minimum possible number of inversions in $b$, and the minimum possible value of $x$, which achieves those number of inversions. -----Examples----- Input 4 0 1 3 2 Output 1 0 Input 9 10 7 9 10 7 5 5 3 5 Output 4 14 Input 3 8 10 3 Output 0 8 -----Note----- In the first sample it is optimal to leave the array as it is by choosing $x = 0$. In the second sample the selection of $x = 14$ results in $b$: $[4, 9, 7, 4, 9, 11, 11, 13, 11]$. It has $4$ inversions: $i = 2$, $j = 3$; $i = 2$, $j = 4$; $i = 3$, $j = 4$; $i = 8$, $j = 9$. In the third sample the selection of $x = 8$ results in $b$: $[0, 2, 11]$. It has no inversions. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) l = list(map(int, input().split())) inv = 0 out = 0 mult = 1 for i in range(32): curr = dict() opp = 0 same = 0 for v in l: if v ^ 1 in curr: if v & 1: opp += curr[v ^ 1] else: same += curr[v ^ 1] if v not in curr: curr[v] = 0 curr[v] += 1 for i in range(n): l[i] >>= 1 if same <= opp: inv += same else: inv += opp out += mult mult *= 2 print(inv, out) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Bears love candies and games involving eating them. Limak and Bob play the following game. Limak eats 1 candy, then Bob eats 2 candies, then Limak eats 3 candies, then Bob eats 4 candies, and so on. Once someone can't eat what he is supposed to eat, he loses. Limak can eat at most A candies in total (otherwise he would become sick), while Bob can eat at most B candies in total. Who will win the game? Print "Limak" or "Bob" accordingly. -----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 two integers A and B denoting the maximum possible number of candies Limak can eat and the maximum possible number of candies Bob can eat respectively. -----Output----- For each test case, output a single line containing one string — the name of the winner ("Limak" or "Bob" without the quotes). -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A, B ≤ 1000 -----Example----- Input: 10 3 2 4 2 1 1 1 2 1 3 9 3 9 11 9 12 9 1000 8 11 Output: Bob Limak Limak Bob Bob Limak Limak Bob Bob Bob -----Explanation----- Test case 1. We have A = 3 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies. Then Limak is supposed to eat 3 candies but that would mean 1 + 3 = 4 candies in total. It's impossible because he can eat at most A candies, so he loses. Bob wins, and so we print "Bob". Test case 2. Now we have A = 4 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies, then Limak eats 3 candies (he has 1 + 3 = 4 candies in total, which is allowed because it doesn't exceed A). Now Bob should eat 4 candies but he can't eat even a single one (he already ate 2 candies). Bob loses and Limak is the winner. Test case 8. We have A = 9 and B = 12. The game looks as follows: - Limak eats 1 candy. - Bob eats 2 candies. - Limak eats 3 candies (4 in total). - Bob eats 4 candies (6 in total). - Limak eats 5 candies (9 in total). - Bob eats 6 candies (12 in total). - Limak is supposed to eat 7 candies but he can't — that would exceed A. Bob wins. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for t in range(int(input())): limakMax, bobMax = list(map(int, input().split())) limakEat = 0; bobEat = 0 eating = 1 while limakEat <= limakMax or bobEat <= bobMax: if eating % 2 != 0 and limakEat <= limakMax: limakEat += eating eating += 1 if limakEat > limakMax: print("Bob") break elif eating % 2 == 0 and bobEat <= bobMax: bobEat += eating eating += 1 if bobEat > bobMax: print("Limak") break ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef's dog Snuffles has so many things to play with! This time around, Snuffles has an array A containing N integers: A1, A2, ..., AN. Bad news: Snuffles only loves to play with an array in which all the elements are equal. Good news: We have a mover of size D. ! A mover of size D is a tool which helps to change arrays. Chef can pick two existing elements Ai and Aj from the array, such that i + D = j and subtract 1 from one of these elements (the element should have its value at least 1), and add 1 to the other element. In effect, a single operation of the mover, moves a value of 1 from one of the elements to the other. Chef wants to find the minimum number of times she needs to use the mover of size D to make all the elements of the array A equal. Help her find this out. -----Input----- - The first line of the input contains an integer T, denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains two integers N and D, denoting the number of elements in the array and the size of the mover. - The second line of each testcase contains N space-separated integers: A1, A2, ..., AN, denoting the initial elements of the array. -----Output----- - For each test case, output a single line containing the minimum number of uses or -1 if it is impossible to do what Snuffles wants. -----Constraints----- - 1 ≤ T ≤ 10 - 2 ≤ N ≤ 105 - 1 ≤ D < N - 1 ≤ Ai ≤ 109 -----Subtasks----- - Subtask 1 (30 points) : N ≤ 103 - Subtask 2 (70 points) : Original constraints -----Example----- Input: 3 5 2 1 4 5 2 3 3 1 1 4 1 4 2 3 4 3 5 Output: 3 2 -1 -----Explanation----- Testcase 1: Here is a possible sequence of usages of the mover: - Move 1 from A3 to A1 - Move 1 from A3 to A1 - Move 1 from A2 to A4 At the end, the array becomes (3, 3, 3, 3, 3), which Snuffles likes. And you cannot achieve this in fewer moves. Hence the answer is 3. Testcase 2: Here is a possible sequence of usages of the mover: - Move 1 from A2 to A1 - Move 1 from A2 to A3 At the end, the array becomes (2, 2, 2), which Snuffles likes. And you cannot achieve this in fewer moves. Hence the answer is 2. Testcase 3: It is impossible to make all the elements equal. Hence the answer is -1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python tc=int(input()) for case in range(tc): n,d=list(map(int,input().split())) a=list(map(int,input().split())) sm=sum(a) f=True if sm%n==0: avg=sm/n for i in range(d): tmp_sm=0 tmp_n=0 for j in range(i,n,d): tmp_sm=tmp_sm+a[j] tmp_n+=1 if tmp_sm%tmp_n==0: if avg!=tmp_sm/tmp_n: f=False break else: f=False break else: f=False if f: ans=0 cur=0 for i in range(d): for j in range(i,n,d): cur=cur+avg-a[j] ans=ans+abs(cur) print(ans) else: print(-1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Polycarp has $n$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100". Polycarp wants to offer his set of $n$ binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001". Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011". Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that: the final set of $n$ words still contains different words (i.e. all words are unique); there is a way to put all words of the final set of words in the order so that the final sequence of $n$ words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. The first line of a test case contains one integer $n$ ($1 \le n \le 2\cdot10^5$) — the number of words in the Polycarp's set. Next $n$ lines contain these words. All of $n$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $4\cdot10^6$. All words are different. Guaranteed, that the sum of $n$ for all test cases in the input doesn't exceed $2\cdot10^5$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $4\cdot10^6$. -----Output----- Print answer for all of $t$ test cases in the order they appear. If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain $k$ ($0 \le k \le n$) — the minimal number of words in the set which should be reversed. The second line of the output should contain $k$ distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from $1$ to $n$ in the order they appear. If $k=0$ you can skip this line (or you can print an empty line). If there are many answers you can print any of them. -----Example----- Input 4 4 0001 1000 0011 0111 3 010 101 0 2 00000 00001 4 01 001 0001 00001 Output 1 3 -1 0 2 1 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): n = int(input()) mass = [] zo = 0 oz = 0 zz = 0 oo = 0 ozs = [] zos = [] ozss = set() zoss = set() for j in range(n): k = input() mass.append(k) if k[0] == '0' and k[-1] == '1': zoss.add(k) zos.append(j + 1) zo += 1 elif k[0] == '1' and k[-1] == '0': ozss.add(k) ozs.append(j + 1) oz += 1 elif k[0] == '0' and k[-1] == '0': zz += 1 else: oo += 1 if zz and oo and not oz and not zo: print(-1) continue else: if zo > oz: print((zo - oz) // 2) ans = [] need = (zo - oz) // 2 i = 0 while need: zzz = mass[zos[i] - 1][len(mass[zos[i] - 1]) - 1:: -1] if zzz not in ozss: ans.append(zos[i]) need -= 1 i += 1 print(*ans) else: print((oz - zo) // 2) ans = [] need = (oz - zo) // 2 i = 0 while need: zzz = mass[ozs[i] - 1][len(mass[ozs[i] - 1]) - 1:: -1] if zzz not in zoss: ans.append(ozs[i]) need -= 1 i += 1 print(*ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The median of a sequence is the element in the middle of the sequence after it is sorted. For a sequence with even size, the median is the average of the two middle elements of the sequence after sorting. For example, for a sequence $A = [1, 3, 3, 5, 4, 7, 11]$, the median is equal to $4$, and for $A = [2, 3, 4, 5]$, the median is equal to $(3+4)/2 = 3.5$. Fulu is a famous programmer in his country. He wrote the following program (given in pseudocode) for finding the median in a sequence $A$ with length $N$: read(N) read(A[0], A[1], ..., A[N-1]) sort(A) # simultaneously remove elements A[K] and A[N mod K] from the array A # the order of the remaining N-2 elements is unchanged remove(A[K], A[N mod K]) return A[(N-2)/2] # integer division The program takes an integer $K$ as a parameter. Fulu can choose this integer arbitrarily between $1$ and $N-1$ inclusive. Little Lima, Fulu's friend, thinks Fulu's program is wrong (as always). As finding one counterexample would be an easy task for Lima (he has already found the sequence $A = [34, 23, 35, 514]$, which is a counterexample for any $K \le 3$), Lima decided to make hacking more interesting. Fulu should give him four parameters $S, K, m, M$ (in addition to $N$) and Lima should find the lexicographically smallest proper sequence $A$ with length $N$ as a counterexample. We say that a sequence $A$ with length $N$ ($0$-indexed) is proper if it satisfies the following conditions: - it contains only positive integers - $A_0 + A_1 +A_2 + \dots + A_{N-1} = S$ - $m \le A_i \le M$ for each $0 \le i < N$ - the number returned by Fulu's program, ran with the given parameter $K$, is different from the correct median of the sequence $A$ Can you help Lima find the lexicographically smallest counterexample or determine that Fulu's program works perfectly for the given parameters? -----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 five space-separated integers $N$, $S$, $K$, $m$ and $M$. -----Output----- For each test case, if there is no proper sequence, print a single line containing the integer $-1$; otherwise, print a single line containing $N$ space-separated integers — the lexicographically smallest proper sequence. -----Constraints----- - $1 \le T \le 8$ - $3 \le N \le 10^5$ - $1 \le K \le N-1$ - $1 \le S \le 10^9$ - $1 \le m \le M \le S$ -----Example Input----- 2 3 6 1 1 5 4 4 2 1 3 -----Example Output----- 1 1 4 -1 -----Explanation----- Example case 1: For the sequence $A = [1, 1, 4]$, it is already sorted, so the program would just remove the first two elements ($K=1$, $N\%K=0$) and return the only remaining element $4$. Obviously, the median of the original sequence is $1$. It can be shown that there is no lexicographically smaller proper sequence. Example case 2: The only possible sequence is $A = [1, 1, 1, 1]$, which is not proper, since Fulu's program will give the correct answer $1$ for it. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here import numpy as np import sys def findSeq(n, s, k, m, M): midInd = n // 2 seqs = [] for ind in range(midInd + 2, midInd - 3, -1): if ind >= n or ind < 0: continue seq = genBestSeq(n, ind, m, M, s) if seq is not -1 and testSeq(k, seq): seqs.append(list(seq)) if len(seqs) == 0: return -1 return min(seqs) #def findSeq(n, s, k, m, M): # midInd = n // 2 # if k <= midInd: #and (n % 2 == 1 or s < m * midInd + M * (n - midInd)): # return genBestSeq(n, midInd + 1, m, M, s) # elif k > midInd + 1 and n % 2 == 1: # return -1 # return genBestSeq(n, midInd, m, M, s) def genBestSeq(n, diffInd, m, M, s): #inc = M - m - 1 arr = np.full((n,), m) arr[diffInd:] += 1 #remainder = s - np.sum(arr) #if remainder < 0: # return -1 #nFull, remainder = divmod(remainder, inc) #if nFull > n or (nFull == n and remainder > 0): # return -1 #addingInd = n - nFull -1 #arr[addingInd + 1:] += inc #arr[addingInd] += remainder #return arr s = s - np.sum(arr) if s < 0: return -1 inc = M - m - 1 ind = n - 1 while (ind >= 0): z = min(inc, s) arr[ind] += z s -= z ind -= 1 if s != 0: return -1 return arr def testSeq(k, seq): seq = sorted(seq) n = len(seq) if n % 2 == 1: median = seq[n // 2] else: median = (seq[n // 2 - 1] + seq[n // 2]) / 2 seq.pop(n % k) seq.pop(k - 1) return (median != seq[(n - 2) // 2]) def __starting_point(): nCases = int(input()) answers = [] #ks = [] for i in range(nCases): #nums = [int(val) for val in input().split()] #ks.append(nums[2]) #answers.append(findSeq(*nums)) answers.append(findSeq(*(int(val) for val in input().split()))) ans = answers[-1] if not isinstance(ans, int): print(*ans, sep=' ') else: print(ans) #for i, ans in enumerate(answers): #for ans in answers: # if isinstance(ans, np.ndarray): # print(*ans, sep=' ') # else: # print(ans) __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Get excited, folks, because it is time for the final match of Codechef Premier League (CPL)! Mike and Tracy also want to watch the grand finale, but unfortunately, they could not get tickets to the match. However, Mike is not someone who gives up so easily — he has a plan to watch the match. The field where the match is played is surrounded by a wall with height $K$. Outside, there are $N$ boxes (numbered $1$ through $N$). For each valid $i$, the $i$-th box has a height $H_i$. Mike wants to take some boxes and stack them on top of each other to build two towers. The height of each tower is the sum of heights of all the boxes that form it. Of course, no box may be in both towers. The height of each tower should be at least $K$. Then Mike can climb on top of one tower and Tracy on top of the other, and they can watch the match uninterrupted! While Mike is busy stacking the boxes, Tracy would like to know the smallest number of boxes required to build two towers such that each of them has height at least $K$, or at least that it is impossible to build such towers. Can you help Tracy? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $K$. - The second line contains $N$ space-separated integers $H_1, H_2, \ldots, H_N$. -----Output----- For each test case, print a single line containing one integer — the smallest number of boxes required to build two towers, or $-1$ if it is impossible. -----Constraints----- - $1 \leq T \leq 5$ - $1 \leq N, K \leq 4,000$ - $1 \leq H_i \leq 10^5$ for each valid $i$ -----Subtasks----- Subtask #1 (30 points): - $1 \leq N, K \leq 100$ - $1 \leq H_i \leq 100$ for each valid $i$ Subtask #2 (70 points): original constraints -----Example Input----- 2 8 38 7 8 19 7 8 7 10 20 4 5 2 10 4 9 -----Example Output----- 7 2 -----Explanation----- Example case 1: The first tower can be built with boxes $8 + 10 + 20 = 38$ and the second tower with boxes $7 + 7 + 8 + 19 = 41$. In this case, the box with height $7$ is left unused. Example case 2: We only need the box with height $10$ for one tower and the box with height $9$ for the other tower. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys sys.setrecursionlimit(100000) memo = {} def recurse(arr, T1, T2, k, i): if T1 >= k and T2 >= k: return i if i >= len(arr): return float('inf') if (T1, T2) in memo: return memo[(T1, T2)] t1 = recurse(arr, T1 + arr[i], T2, k, i+1) t2 = recurse(arr, T1, T2 + arr[i], k, i+1) memo[(T1, T2)] = min(t1, t2) return memo[(T1, T2)] for _ in range(int(input())): n, k = list(map(int, input().split())) lst = list(map(int, input().split())) lst.sort(reverse = True) memo = {} res = recurse(lst, 0, 0, k, 0) if res == float('inf'): print(-1) else: print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Alice and Johnny are playing a simple guessing game. Johnny picks an arbitrary positive integer n (1<=n<=109) and gives Alice exactly k hints about the value of n. It is Alice's task to guess n, based on the received hints. Alice often has a serious problem guessing the value of n, and she's beginning to suspect that Johnny occasionally cheats, that is, gives her incorrect hints. After the last game, they had the following little conversation: - [Alice] Johnny, you keep cheating! - [Johnny] Indeed? You cannot prove it. - [Alice] Oh yes I can. In fact, I can tell you with the utmost certainty that in the last game you lied to me at least *** times. So, how many times at least did Johnny lie to Alice? Try to determine this, knowing only the hints Johnny gave to Alice. -----Input----- The first line of input contains t, the number of test cases (about 20). Exactly t test cases follow. Each test case starts with a line containing a single integer k, denoting the number of hints given by Johnny (1<=k<=100000). Each of the next k lines contains exactly one hint. The i-th hint is of the form: operator li logical_value where operator denotes one of the symbols < , > , or =; li is an integer (1<=li<=109), while logical_value is one of the words: Yes or No. The hint is considered correct if logical_value is the correct reply to the question: "Does the relation: n operator li hold?", and is considered to be false (a lie) otherwise. -----Output----- For each test case output a line containing a single integer, equal to the minimal possible number of Johnny's lies during the game. -----Example----- Input: 3 2 < 100 No > 100 No 3 < 2 Yes > 4 Yes = 3 No 6 < 2 Yes > 1 Yes = 1 Yes = 1 Yes > 1 Yes = 1 Yes Output: 0 1 2 Explanation: for the respective test cases, the number picked by Johnny could have been e.g. n=100, n=5, and n=1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def guessingGame (l): a = [] m = 1000000001 for i in range (len(l)): k=int(l[i][1]) if (l[i][0]=='<' and l[i][2]=='Yes'): a.append((1,1)) a.append((k,-1)) if (l[i][0]=='<' and l[i][2]=='No'): a.append((k,1)) a.append((m,-1)) if (l[i][0]=='=' and l[i][2]=='Yes'): a.append((k,1)) a.append((k+1,-1)) if (l[i][0]=='=' and l[i][2]=='No'): a.append((1,1)) a.append((k,-1)) a.append((k+1,1)) a.append((m,-1)) if (l[i][0]=='>' and l[i][2]=='Yes'): a.append((k+1,1)) a.append((m,-1)) if (l[i][0]=='>' and l[i][2]=='No'): a.append((1,1)) a.append((k+1,-1)) a.sort() w=0 r=0 for i in range (len(a)): w+=a[i][1] r=max(w,r) return len(l)-r def __starting_point(): T = int(input()) answer = [] for _ in range (T): e = int(input()) temp = [] for q_t in range (e): q = list(map(str,input().rstrip().split())) temp.append(q) result = guessingGame(temp) print(result) __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree. The depth of a vertex is the number of edges on the simple path from the vertex to the root. In particular, the depth of the root is $0$. Let's call a binary search tree perfectly balanced if there doesn't exist a binary search tree with the same number of vertices that has a strictly smaller sum of depths of its vertices. Let's call a binary search tree with integer keys striped if both of the following conditions are satisfied for every vertex $v$: If $v$ has a left subtree whose root is $u$, then the parity of the key of $v$ is different from the parity of the key of $u$. If $v$ has a right subtree whose root is $w$, then the parity of the key of $v$ is the same as the parity of the key of $w$. You are given a single integer $n$. Find the number of perfectly balanced striped binary search trees with $n$ vertices that have distinct integer keys between $1$ and $n$, inclusive. Output this number modulo $998\,244\,353$. -----Input----- The only line contains a single integer $n$ ($1 \le n \le 10^6$), denoting the required number of vertices. -----Output----- Output the number of perfectly balanced striped binary search trees with $n$ vertices and distinct integer keys between $1$ and $n$, inclusive, modulo $998\,244\,353$. -----Examples----- Input 4 Output 1 Input 3 Output 0 -----Note----- In the first example, this is the only tree that satisfies the conditions: $\left. \begin{array}{l}{\text{perfectly balanced}} \\{\text{striped}} \\{\text{binary search tree}} \end{array} \right.$ In the second example, here are various trees that don't satisfy some condition: [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python N = int(input()) if N in [1, 2, 4, 5, 9, 10, 20, 21, 41, 42, 84, 85, 169, 170, 340, 341, 681, 682, 1364, 1365, 2729, 2730, 5460, 5461, 10921, 10922, 21844, 21845, 43689, 43690, 87380, 87381, 174761, 174762, 349524, 349525, 699049, 699050]: print(1) else: print(0) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Rakesh has built a model rocket and wants to test how stable it is. He usually uses a magic box which runs some tests on the rocket and tells if it is stable or not, but his friend broke it by trying to find out how stable he is (very delicate magic indeed). The box only gives a polynomial equation now which can help Rakesh find the stability (a failsafe by the manufacturers). Rakesh reads the manual for the magic box and understands that in order to determine stability, he needs to take every other term and put them in two rows. Eg. If the polynomial is: 10 x^4 + 12 x^3 + 4 x^2 + 5 x + 3, the first two rows will be: Row 1: 10 4 3 Row 2: 12 5 0 For all other rows, the nth element of the rth row is found recursively by multiplying the 1st element of the (r-1)th row and (n+1)th element of the (r-2)th row and subtracting it with 1st element of the (r-2)th row multiplied by (n+1)th element of the (r-1)th row. So Row 3 will be (12 * 4 - 10 * 5) (12 * 3 - 10 * 0) Row 3: -2 36 0 Row 4: -442 0 0 Row 5: -15912 0 0 There will not be any row six (number of rows = maximum power of x + 1) The rocket is stable if there are no sign changes in the first column. If all the elements of the rth row are 0, replace the nth element of the rth row by the nth element of the (r-1)th row multiplied by (maximum power of x + 4 - r - 2n). If the first element of any row is 0 and some of the other elements are non zero, the rocket is unstable. Can you help Rakesh check if his rocket is stable? Input Format: 1. First row with number of test cases (T). 2. Next T rows with the coefficients of the polynomials for each case (10 12 4 5 3 for the case above). Output Format: 1. "1" if stable (without "") 2. "0" if unstable (without "") Sample Input: 1 10 12 4 5 3 Sample Output: 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import random def sign(i): if i>0: return 1 elif i<=0: return 0 bleh = [] for _ in range(int(input())): p = list(map(int,input().rstrip().split())) max_rows = len(p) if all([x==0 for x in p]): print(1) continue if max_rows <= 1: bleh.append(max_rows) continue max_pow = max_rows-1 if len(p)%2 !=0 and len(p)>0: p.append(0) max_col = len(p)//2 rows = [[0 for _ in range(max_col)] for _ in range(max_rows)] rows[0] = p[::2] rows[1] = p[1::2] if sign(rows[0][0]) != sign(rows[1][0]): print(0) continue for r in range(2,max_rows): for n in range(max_col-1): rows[r][n] = rows[r-1][0]*rows[r-2][n+1]-rows[r-2][0]*rows[r-1][n+1] last = sign(rows[0][0]) flag = 1 for i in range(1,len(rows)): curr = sign(rows[i][0]) if rows[r] == [0 for _ in range(max_col)]: for n in range(max_col): rows[r][n] = rows[r-1][n]*(max_pow+4-(r+1)-2*(n+1)) elif rows[i][0] == 0: if any([x != 0 for x in rows[i]]): flag = 0 break else: curr = last if curr != last: flag = 0 break last = curr print(flag) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef likes toys. His favourite toy is an array of length N. This array contains only integers. He plays with this array every day. His favourite game with this array is Segment Multiplication. In this game, the second player tells the left and right side of a segment and some modulo. The first player should find the multiplication of all the integers in this segment of the array modulo the given modulus. Chef is playing this game. Of course, he is the first player and wants to win all the games. To win any game he should write the correct answer for each segment. Although Chef is very clever, he has no time to play games. Hence he asks you to help him. Write the program that solves this problem. -----Input----- The first line of the input contains an integer N denoting the number of elements in the given array. Next line contains N integers Ai separated with spaces. The third line contains the number of games T. Each of the next T lines contain 3 integers Li, Ri and Mi, the left side of the segment, the right side of segment and the modulo. -----Output----- For each game, output a single line containing the answer for the respective segment. -----Constrdaints----- - 1 ≤ N ≤ 100,000 - 1 ≤ Ai ≤ 100 - 1 ≤ T ≤ 100,000 - 1 ≤ Li ≤ Ri ≤ N - 1 ≤ Mi ≤ 109 -----Example----- Input: 5 1 2 3 4 5 4 1 2 3 2 3 4 1 1 1 1 5 1000000000 Output: 2 2 0 120 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # # # # n = int(input()) # # # # arr = list(map(int , input().split())) # # # # for _ in range(int(input())): # # # # l,r,mod = map(int , input().split()) # # # # pro = 1 # # # # for i in range(l - 1,r): # # # # pro *= arr[i] # # # # print(pro % mod) #sample testcases passed #TLE # # # import numpy #or use math # # # n = int(input()) # # # arr = list(map(int , input().split())) # # # for _ in range(int(input())): # # # l,r,mod = map(int , input().split()) # # # print(numpy.prod(arr[l - 1:r]) % mod) #sample cases passed, WA # # import math # # primes,dic,t = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97],{},0 # # for i in primes: # # dic[i] = t # # t += 1 # # def primeFactors(n,arr): # # for i in range(2,int(math.sqrt(n)) + 1,2): # # while(n % i == 0): # # arr[dic[i]] += 1 # # n /= i # # if(n > 2): # # arr[dic[n]] += 1 # # return arr # # n = int(input()) # # A = list(map(int , input().split())) # # dp = [0]*len(primes) # # for i in range(1,n + 1): # # r = [dp[i - 1]].copy() # # dp.append(primeFactors(A[i - 1],r)) # # for _ in range(int(input())): # # li,ri,m=list(map(int,input().split())) # # ans = 1 # # for i in range(len(primes)): # # ans *= (pow(primes[i],dp[ri][i] - dp[li - 1][i],m)) % m # # print(ans % m) #NZEC # import math # primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] # dic={} # t=0 # for i in primes: # dic[i]=t # t+=1 # def primeFactors(n,arr): # while(n % 2 == 0): # arr[dic[2]] += 1 # n /= 2 # for i in range(3,int(math.sqrt(n))+1,2): # while(n % i == 0): # arr[dic[i]] += 1 # n /= i # if(n > 2): # arr[dic[n]] += 1 # return arr # N = int(input()) # A = list(map(int , input().split())) # dp = [[0]*len(primes)] # for i in range(1,N + 1): # r = dp[i - 1].copy() # dp.append(primeFactors(A[i - 1],r)) # for _ in range(int(input())): # l,r,m = list(map(int , input().split())) # ans = 1 # for i in range(len(primes)): # ans *= (pow(primes[i],dp[r][i] - dp[l - 1][i],m)) % m # print(ans % m) import sys import math input = sys.stdin.readline primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] dic={} t=0 for i in primes: dic[i]=t t+=1 def primeFactors(n,arr): while n % 2 == 0: arr[dic[2]]+=1 n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: arr[dic[i]]+=1 n = n / i if n > 2: arr[dic[n]]+=1 return arr def main(): N=int(input()) A=list(map(int,input().split())) tp=[0]*len(primes) dp=[] dp.append(tp) for i in range(1,N+1): # print(i) r=dp[i-1].copy() t=primeFactors(A[i-1],r) dp.append(t) t=int(input()) for _ in range(t): l,r,m=list(map(int,input().split())) if(m==1): print(0) else: ans=1 for i in range(len(primes)): ans=ans*(pow(primes[i],dp[r][i]-dp[l-1][i],m))%m print(ans%m) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Given n words w[1..n], which originate from the same stem (e.g. grace, graceful, disgraceful, gracefully), we are interested in the original stem. To simplify the problem, we define the stem as the longest consecutive substring that occurs in all the n words. If there are ties, we will choose the smallest one in the alphabetical (lexicographic) order. -----Input----- The first line contains an integer T denoting the total number of test cases. In each test cases, the first line contains an integer n denoting the number of words. In the second line, n words w[1..n] consisting of lower case characters are given as a single space-spearated list. -----Output----- For each test case, output the stem in a new line. -----Constraints----- - 1 <= T <= 10 - 1 <= n <= 10 - 1 <= |w[i]| <= 20 -----Example----- Input: 1 4 grace graceful disgraceful gracefully Output: grace -----Explanation----- The stem is grace. 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()) for _ in range(t): n = eval(input()) a = input().strip().split() cb, cs = 0, "" for i in range(len(a[0])): for j in range(i+1,len(a[0])+1): al = True s = a[0][i:j] for k in a[1:]: if s not in k: al = False break if al: if j-i>=cb: cb = max(cb, j-i) if len(cs) < cb: cs = a[0][i:j] elif len(cs) == cb: cs = min(cs,a[0][i:j]) print(cs) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef likes problems which using some math. Now he asks you to solve next one. You have 4 integers, Chef wondering is there non-empty subset which has sum equals 0. -----Input----- The first line of input contains T - number of test cases. Each of the next T lines containing four pairwise distinct integer numbers - a, b, c, d. -----Output----- For each test case output "Yes", if possible to get 0 by choosing non-empty subset of {a, b, c, d} with sum equal 0, or "No" in another case. -----Constraints----- - 1 ≤ T ≤ 103 - -106 ≤ a, b, c, d ≤ 106 -----Example----- Input: 3 1 2 0 3 1 2 4 -1 1 2 3 4 Output: Yes Yes No -----Explanation----- Example case 1. We can choose subset {0} Example case 2. We can choose subset {-1, 1} The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here t = int(input()) while t: t-=1 c=0 ar=[int(i) for i in input().strip().split()] for i in range(1,16): b=bin(i)[2:].zfill(4) s=0 for i in range(4): if b[i]=='1': s+=ar[i] if(s==0): c=1 break print("Yes" if c==1 else "No") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There were $N$ students (numbered $1$ through $N$) participating in the Indian Programming Camp (IPC) and they watched a total of $K$ lectures (numbered $1$ through $K$). For each student $i$ and each lecture $j$, the $i$-th student watched the $j$-th lecture for $T_{i, j}$ minutes. Additionally, for each student $i$, we know that this student asked the question, "What is the criteria for getting a certificate?" $Q_i$ times. The criteria for getting a certificate is that a student must have watched at least $M$ minutes of lectures in total and they must have asked the question no more than $10$ times. Find out how many participants are eligible for a certificate. -----Input----- - The first line of the input contains three space-separated integers $N$, $M$ and $K$. - $N$ lines follow. For each valid $i$, the $i$-th of these lines contains $K+1$ space-separated integers $T_{i, 1}, T_{i, 2}, \ldots, T_{i, K}, Q_i$. -----Output----- Print a single line containing one integer — the number of participants eligible for a certificate. -----Constraints----- - $1 \le N, K \le 1,000$ - $1 \le M \le 10^6$ - $1 \le Q_i \le 10^6$ for each valid $i$ - $1 \le T_{i, j} \le 1,000$ for each valid $i$ and $j$ -----Example Input----- 4 8 4 1 2 1 2 5 3 5 1 3 4 1 2 4 5 11 1 1 1 3 12 -----Example Output----- 1 -----Explanation----- - Participant $1$ watched $1 + 2 + 1 + 2 = 6$ minutes of lectures and asked the question $5$ times. Since $6 < M$, this participant does not receive a certificate. - Participant $2$ watched $3 + 5 + 1 + 3 = 12$ minutes of lectures and asked the question $4$ times. Since $12 \ge M$ and $4 \le 10$, this participant receives a certificate. - Participant $3$ watched $1 + 2 + 4 + 5 = 12$ minutes of lectures and asked the question $11$ times. Since $12 \ge M$ but $11 > 10$, this participant does not receive a certificate. - Participant $4$ watched $1 + 1 + 1 + 3 = 6$ minutes of lectures and asked the question $12$ times. Since $6 < M$ and $12 > 10$, this participant does not receive a certificate. Only participant $2$ receives a certificate. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python N,M,K=map(int,input().split()) c=0 for i in range(N): T=list(map(int,input().split())) Q=T[-1] T.pop(-1) if Q<=10 and sum(T)>=M: c+=1 print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Suppose there is a X x Y x Z 3D matrix A of numbers having coordinates (i, j, k) where 0 ≤ i < X, 0 ≤ j < Y, 0 ≤ k < Z. Now another X x Y x Z matrix B is defined from A such that the (i, j, k) element of B is the sum of all the the numbers in A in the cuboid defined by the (0, 0, 0) and (i, j, k) elements as the diagonally opposite vertices. In other word (i, j, k) in B is the sum of numbers of A having coordinates (a, b, c) such that 0 ≤ a ≤ i, 0 ≤ b ≤ j, 0 ≤ c ≤ k. The problem is that given B, you have to find out A. -----Input----- The first line of input will contain the number of test cases ( ≤ 10). That many test cases will follow in subsequent lines. The first line of each test case will contain the numbers X Y Z (0 ≤ X, Y, Z ≤ 100). After that there will be X x Y lines each containing Z numbers of B. The first line contains the numbers (0, 0, 0), (0, 0, 1)..., (0, 0, Z-1). The second line has the numbers (0, 1, 0), (0, 1, 1)..., (0, 1, Z-1) and so on. The (Y+1)th line will have the numbers (1, 0, 0), (1, 0, 1)..., (1, 0, Z-1) and so on. -----Output----- For each test case print the numbers of A in exactly the same fashion as the input. -----Example----- Input: 2 3 1 1 1 8 22 1 2 3 0 9 13 18 45 51 Output: 1 7 14 0 9 4 18 18 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Problem: http://www.codechef.com/JULY09/submit/CUBESUM/ # Author: Susam Pal def computeA(): X, Y, Z = [int(x) for x in input().split()] B = [] for x in range(X): B.append([]) for y in range(Y): B[-1].append([int(t) for t in input().split()]) for z in range(Z): result = B[x][y][z] if x: result -= B[x - 1][y][z] if y: result += B[x - 1][y - 1][z] if z: result -= B[x - 1][y - 1][z - 1] if y: result -= B[x][y - 1][z] if z: result += B[x][y - 1][z - 1] if z: result -= B[x][y][z - 1] if x: result += B[x - 1][y][z - 1] print(result, end=' ') print() test_cases = int(input()) for i in range(test_cases): computeA() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is an automatic door at the entrance of a factory. The door works in the following way: when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside, when one or several people come to the door and it is open, all people immediately come inside, opened door immediately closes in d seconds after its opening, if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close. For example, if d = 3 and four people are coming at four different moments of time t_1 = 4, t_2 = 7, t_3 = 9 and t_4 = 13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12. It is known that n employees will enter at moments a, 2·a, 3·a, ..., n·a (the value a is positive integer). Also m clients will enter at moments t_1, t_2, ..., t_{m}. Write program to find the number of times the automatic door will open. Assume that the door is initially closed. -----Input----- The first line contains four integers n, m, a and d (1 ≤ n, a ≤ 10^9, 1 ≤ m ≤ 10^5, 1 ≤ d ≤ 10^18) — the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes. The second line contains integer sequence t_1, t_2, ..., t_{m} (1 ≤ t_{i} ≤ 10^18) — moments of time when clients will come. The values t_{i} are given in non-decreasing order. -----Output----- Print the number of times the door will open. -----Examples----- Input 1 1 3 4 7 Output 1 Input 4 3 4 2 7 9 11 Output 4 -----Note----- In the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def solve(): n1, m, a, d = list(map(int, input().split())) t = list(map(int, input().split())) from bisect import insort from math import floor insort(t, a * n1) pred = 0 k = 0 kpred = 0 n = 0 step = d // a + 1 sol = 0 fl = 0 for i in t: if (i > pred): if fl == 0: n = (i - pred + (pred % a)) // a if n != 0: k += (n // step) * step - step * (n % step == 0) + 1 if k > n1: k = n1 fl = 1 # print(k) if (k * a + d >= i) and (n != 0): pred = k * a + d else: pred = i + d k = floor(pred // a) sol += 1 # if n==0: k = min(floor(pred // a), n1) sol += n // step + (n % step != 0) else: sol += 1 pred = i + d if i == a * n1: fl = 1 # print(i,pred,sol,n,step,k, fl) print(sol) solve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Reminder: the median of the array $[a_1, a_2, \dots, a_{2k+1}]$ of odd number of elements is defined as follows: let $[b_1, b_2, \dots, b_{2k+1}]$ be the elements of the array in the sorted order. Then median of this array is equal to $b_{k+1}$. There are $2n$ students, the $i$-th student has skill level $a_i$. It's not guaranteed that all skill levels are distinct. Let's define skill level of a class as the median of skill levels of students of the class. As a principal of the school, you would like to assign each student to one of the $2$ classes such that each class has odd number of students (not divisible by $2$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized. What is the minimum possible absolute difference you can achieve? -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of students halved. The second line of each test case contains $2n$ integers $a_1, a_2, \dots, a_{2 n}$ ($1 \le a_i \le 10^9$) — skill levels of students. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes. -----Example----- Input 3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 Output 0 1 5 -----Note----- In the first test, there is only one way to partition students — one in each class. The absolute difference of the skill levels will be $|1 - 1| = 0$. In the second test, one of the possible partitions is to make the first class of students with skill levels $[6, 4, 2]$, so that the skill level of the first class will be $4$, and second with $[5, 1, 3]$, so that the skill level of the second class will be $3$. Absolute difference will be $|4 - 3| = 1$. Note that you can't assign like $[2, 3]$, $[6, 5, 4, 1]$ or $[]$, $[6, 5, 4, 1, 2, 3]$ because classes have even number of students. $[2]$, $[1, 3, 4]$ is also not possible because students with skills $5$ and $6$ aren't assigned to a class. In the third test you can assign the students in the following way: $[3, 4, 13, 13, 20], [2, 5, 8, 16, 17]$ or $[3, 8, 17], [2, 4, 5, 13, 13, 16, 20]$. Both divisions give minimal possible absolute difference. 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()) ar = list(map(int, input().split())) ar.sort() print(abs(ar[n] - ar[n - 1])) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to choose at most $\lfloor\frac{n}{2}\rfloor$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices. It is guaranteed that the answer exists. If there are multiple answers, you can print any. You will be given multiple independent queries to answer. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of queries. Then $t$ queries follow. The first line of each query contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$) — the number of vertices and the number of edges, respectively. The following $m$ lines denote edges: edge $i$ is represented by a pair of integers $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$), which are the indices of vertices connected by the edge. There are no self-loops or multiple edges in the given graph, i. e. for each pair ($v_i, u_i$) there are no other pairs ($v_i, u_i$) or ($u_i, v_i$) in the list of edges, and for each pair ($v_i, u_i$) the condition $v_i \ne u_i$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that $\sum m \le 2 \cdot 10^5$ over all queries. -----Output----- For each query print two lines. In the first line print $k$ ($1 \le \lfloor\frac{n}{2}\rfloor$) — the number of chosen vertices. In the second line print $k$ distinct integers $c_1, c_2, \dots, c_k$ in any order, where $c_i$ is the index of the $i$-th chosen vertex. It is guaranteed that the answer exists. If there are multiple answers, you can print any. -----Example----- Input 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 6 8 2 5 5 4 4 3 4 1 1 3 2 3 2 6 5 6 Output 2 1 3 3 4 3 6 -----Note----- In the first query any vertex or any pair of vertices will suffice. [Image] Note that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices $2$ and $4$) but three is also ok. [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline T = int(input()) for _ in range(T): N, M = list(map(int, input().split())) E = [[] for aa in range(N)] for __ in range(M): a, b = list(map(int, input().split())) E[a-1].append(b-1) E[b-1].append(a-1) D = [-1] * N D[0] = 0 d = 0 post = [0] EVEN = [1] ODD = [] while post: d += 1 pre = post post = [] for i in pre: for e in E[i]: if D[e] < 0: D[e] = d post.append(e) if d % 2: ODD.append(e+1) else: EVEN.append(e+1) if len(ODD) < len(EVEN): print(len(ODD)) print(*ODD) else: print(len(EVEN)) print(*EVEN) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You came across this story while reading a book. Long a ago when the modern entertainment systems did not exist people used to go to watch plays in theaters, where people would perform live in front of an audience. There was a beautiful actress who had a disability she could not pronounce the character $'r'$. To win her favours which many have been denied in past, you decide to write a whole play without the character $'r'$. Now you have to get the script reviewed by the editor before presenting it to her. The editor was flattered by the script and agreed to you to proceed. The editor will edit the script in this way to suit her style. For each word replace it with a sub-sequence of itself such that it contains the character 'a'. 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 Wikipedia Now given a script with $N$ words, for each word in the script you wish to know the number of subsequences with which it can be replaced. -----Input:----- - First-line will contain $N$, the number of words in the script. Then next $N$ line with one test case each. - Each test case contains a single word $W_i$ -----Output:----- For each test case, output in a single line number of subsequences with which it can be replaced. -----Constraints----- - $1 \leq N \leq 1000$ - $1 \leq$ length of $W_i$ $\leq 20$ - $W_i$ on contains lowercase english alphabets and does not have the character 'r' -----Sample Input 1:----- 2 abc aba -----Sample Output 1:----- 4 6 -----EXPLANATION:----- This subsequences with which $abc$ can be replaed : ${a,ab,ac,abc}$. This subsequences with which $aba$ can be replaed : ${a,ab,aba,a,ba,a}$. -----Sample Input 2:----- 3 abcde abcdea xyz -----Sample Output 2:----- 16 48 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): S = input() n = len(S) a = n - S.count('a') print(2 ** n - 2 ** a) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is placing the laddus on the large square plat. The plat has the side of length N. Each laddu takes unit sq.unit area. Cheffina comes and asks the chef one puzzle to the chef as, how many squares can be formed in this pattern with all sides of new square are parallel to the original edges of the plate. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $N$. -----Output:----- For each test case, output in a single line answer as maximum squares on plate satisfying the condition. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^5$ -----Sample Input:----- 2 1 2 -----Sample Output:----- 1 5 -----EXPLANATION:----- For 1) Only 1 Square For 2) 4 squares with area 1 sq.unit 1 square with area 4 sq.unit The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t = int(input()) while t: m = int(input()) print(int(m * (m + 1) * (2 * m + 1) / 6)) t -= 1 ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given two arithmetic progressions: a_1k + b_1 and a_2l + b_2. Find the number of integers x such that L ≤ x ≤ R and x = a_1k' + b_1 = a_2l' + b_2, for some integers k', l' ≥ 0. -----Input----- The only line contains six integers a_1, b_1, a_2, b_2, L, R (0 < a_1, a_2 ≤ 2·10^9, - 2·10^9 ≤ b_1, b_2, L, R ≤ 2·10^9, L ≤ R). -----Output----- Print the desired number of integers x. -----Examples----- Input 2 0 3 3 5 21 Output 3 Input 2 4 3 0 6 17 Output 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys, collections def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return a // gcd(a, b) * b def extgcd(a, b): if b == 0: return 1, 0 x, y = extgcd(b, a % b) return y, x - a // b * y def prime_factor(n): res = collections.defaultdict(int) i = 2 while i * i <= n: cnt = 0 while n % i == 0: n //= i cnt += 1 if cnt > 0: res[i] = cnt i += 1 if n != 1: res[n] = 1 return res def modinv(a, mod): if a == 0: return -1 if gcd(a, mod) != 1: return -1 return extgcd(a, mod)[0] % mod def normalize(a1, a2): p1 = prime_factor(a1) p2 = prime_factor(a2) keys = list(set(p1.keys()) | set(p2.keys())) r1 = 1 r2 = 1 for k in keys: if p1[k] >= p2[k]: r1 *= k ** p1[k] else: r2 *= k ** p2[k] return r1, r2 def solve(a1, b1, a2, b2): g = gcd(a1, a2) if (b1 - b2) % g != 0: return -1 a1, a2 = normalize(a1, a2) u = b1 % a1 inv = modinv(a1, a2) v = (b2 - u) * inv % a2 return u + v * a1 def f(x0, T, v): ok = 10 ** 36 ng = -1 while ok - ng > 1: mid = (ok + ng) // 2 if x0 + T * mid >= v: ok = mid else: ng = mid return ok a1, b1, a2, b2, L, R = map(int, input().split()) T = lcm(a1, a2) x0 = solve(a1, b1, a2, b2) if x0 == -1: print(0) return x0 -= T * 10 ** 36 ok = 10 ** 60 ng = -1 while ok - ng > 1: mid = (ok + ng) // 2 val = x0 + T * mid k = (val - b1) // a1 l = (val - b2) // a2 if k >= 0 and l >= 0: ok = mid else: ng = mid x0 += ok * T # L <= x0 + kT < R + 1 ans = f(x0, T, R + 1) - f(x0, T, L) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef's younger brother is in town. He's a big football fan and has a very important match to watch tonight. But the Chef wants to watch the season finale of MasterChef which will be aired at the same time. Now they don't want to fight over it like they used to when they were little kids. They want to decide it in a fair way. So they agree to play a game to make a decision. Their favourite childhood game! The game consists of C boards. Each board i is a grid of dimension ni x mi. Rules of the game: - A coin is placed at (1,1) on every board initially. - Each one takes a turn alternatively. - In one turn, a player can choose any one board and move a coin from a cell (i,j) to one of the following cells: (i+1,j) OR (i+2,j) OR (i,j+1) OR (i,j+2) OR (i+1,j+1) OR (i+2,j+2). - A coin cannot be moved out of the board at any point during the game. - A coin cannot be moved once it reaches the cell (n,m) where n and m are the dimensions of the board of that coin. - A player MUST make one valid move. - The player who makes the last move gets to watch TV. Both of them are passionate about their interests and want to watch their respective shows. So they will obviously make optimal moves in every turn. The Chef, being the elder brother, takes the first turn. Your task is to predict which show they will be watching tonight. -----Input:----- The first line of input contains a single integer T, the number of test cases. T tests follow.Each test case starts with a single line containing C, the number of boards in the game. Then follow C lines: each containing 2 integers ni and mi, the dimensions of the ith board. -----Output:----- Given the number and dimensions of boards, for each test case, output in a single line: "MasterChef" if the Chef wins or "Football" if his brother wins. -----Constraints:----- 1<=T<=10000 1<=C<=20 2<=ni,mi<=1000 -----Example:-----Input: 1 1 2 2 Output: MasterChef Explanation: The Chef can move the coin on the board from (1,1)->(2,2). This coin cannot be moved any further. And so, the Chef wins. Notice that if the Chef moves it to any other valid position, i.e. either to (1,2) or (2,1) he will lose! The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python res="" for _ in range(int(input())): ans=0 c=int(input()) for i in range(c): n,m=list(map(int,input().split( ))) ans^=(n+m-2)%3 if ans: res+="MasterChef\n" else: res+="Football\n" print(res) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Abhi Ram analyses london stock exchange and invests in a software company C-.gate . He wants to sell his shares after 5 weeks. Given the investment m, increase or decrease of share prices of 5 weeks(+/- pi) , help him to calculate his net profit or loss percentage(n%) of his investment to establish his own company KMC. -----Input:----- - The first line contains an integer T which denotes the number of test cases. - Each test case comprises of two lines: the first line contains the integer m which denotes the amount invested. The second line consists of five space separated integers(p1, p2, p3, p4, p5) each preceeded by + (increase) or - (decrease) which give the percentage of change in share prices over 5 weeks. . -----Output:----- The output contains a single number n which gives the percentage of profit or loss preceeded by + (profit) or - (loss). -----Constraints:----- - 1 ≤ T ≤ 100 - 1 ≤ m ≤ 105 - -100 ≤ pi ≤ 100 -----Example:----- Input: 2 10000 +5 -3 -2 +10 +15 6256250 -24 +22 +4 -16 +20 Output: +26.2634 -2.79977 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()) P = list(map(float, input().split())) pr = 1 for p in P: a = 100+p pr = (pr*a)/100 pr = (pr-1)*100 x = 6-len(str(int(abs(pr)))) if (x==1): if (pr==0): print(0) elif (pr>0): print("+"+str("%.1f" % round(pr,x))) else: print(str("%.1f" % round(pr,x))) elif (x==2): if (pr==0): print(0) elif (pr>0): print("+"+str("%.2f" % round(pr,x))) else: print(str("%.2f" % round(pr,x))) elif (x==3): if (pr==0): print(0) elif (pr>0): print("+"+str("%.3f" % round(pr,x))) else: print(str("%.3f" % round(pr,x))) elif (x==4): if (pr==0): print(0) elif (pr>0): print("+"+str("%.4f" % round(pr,x))) else: print(str("%.4f" % round(pr,x))) elif (x==5): if (pr==0): print(0) elif (pr>0): print("+"+str("%.5f" % round(pr,x))) else: print(str("%.5f" % round(pr,x))) elif (x==6): if (pr==0): print(0) elif (pr>0): print("+"+str("%.6f" % round(pr,x))) else: print(str("%.6f" % round(pr,x))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Alice's school is planning to take some students from her class on a field trip. Alice is really excited about it. There are a total of S students in her class. But due to budget constraints, the school is planning to take only N students for the trip. These students will be picked randomly. And each student has equal chance of being picked. Alice's friend circle has M students including her. Though she is excited about the field trip, she will enjoy it only if there are atleast K of her friends with her on the trip. She is wondering what are the chances of that happening. She needs your help. Tell her the probability that she will enjoy given that she goes on the trip. -----Input:----- First line of input contains a single integer T, the number of test cases. Each test starts with a single line having 4 space separated integers, S, N, M and K. -----Output:----- For each test case, output a line containing the required probability. The answer will be accepted if the relative error is not more than 10-6. -----Constraints:----- 1 ≤ T ≤ 100 1 ≤ S ≤ 1000 1 ≤ N ≤ S 1 ≤ M ≤ S 0 ≤ K < M -----Example:-----Input: 3 10 10 5 3 10 4 6 4 3 2 2 1 Output: 1.000000 0.000000 0.500000 -----Explanation:-----Case #1: Every student will be taken to the trip. So all her 4 friends will accompany her to the trip no matter what. Case #2: Alice wants 4 out of her 5 friends to come along with her which isn't possible because the school is willing to pick only 4 students for the trip. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python nCr = [[0 for x in range(1001)] for x in range(1001)] for i in range (0,1001): nCr[i][0]=1 nCr[i][i]=1 for i in range (1,1001): for j in range (1,1001): if i!=j: nCr[i][j] = nCr[i-1][j] + nCr[i-1][j-1] t=eval(input()) for rajarshisarkar in range(0,t): s,n,m,k=list(map(int,input().split(' '))) foo=0.000000 tot = float(nCr[s-1][n-1]) if s==n: print("1.000000\n") continue if k>n: print("0.000000\n") continue if m>n: wola=n else: wola=m for i in range(k,wola): foo+= ((nCr[m-1][i])*(nCr[s-m][n-i-1])) print("%f\n"% (float(foo/tot))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In africa jungle , there were zebra's who liked to spit. There owner watched them for whole day and noted in his sheet where each zebra spitted. Now he's in a confusion and wants to know if in the jungle there are two zebra's which spitted at each other. Help him solve this task. If the zebra is present in position a spits b metres right , he can hit only zebra in position a+b , if such a zebra exists. -----Input:----- - The first line contains integer t(1<=t<100)- amount of zebras in jungle. - Each of following t lines contains two integers a(i) and b(i)(-10^4<=x(i)<=10^4,1<|d(i)|<=2.10^4) - records in owner sheet. - a(i) is the position of i-th zebra and b(i) is distance at which the i-th camel spitted. Positive values of d(i) correspond to spits right, negative values correspond to spit left.No two zebras may stand in the same position. -----Output:----- If there are two zebras , which spitted at each other , output YES, otherwise , output NO. -----Sample Input:----- 2 0 1 1 -1 -----Sample Output:----- YES 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()) i=0 a=0 d=dict() while i<t: l=input().split() d[int(l[0])]=int(l[0])+int(l[1]) i+=1 for k in d: if d[k] in d: if d[d[k]]==k: a=1 break if a==1: print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Limak is a little polar bear. He is playing a video game and he needs your help. There is a row with N cells, each either empty or occupied by a soldier, denoted by '0' and '1' respectively. The goal of the game is to move all soldiers to the right (they should occupy some number of rightmost cells). The only possible command is choosing a soldier and telling him to move to the right as far as possible. Choosing a soldier takes 1 second, and a soldier moves with the speed of a cell per second. The soldier stops immediately if he is in the last cell of the row or the next cell is already occupied. Limak isn't allowed to choose a soldier that can't move at all (the chosen soldier must move at least one cell to the right). Limak enjoys this game very much and wants to play as long as possible. In particular, he doesn't start a new command while the previously chosen soldier moves. Can you tell him, how many seconds he can play at most? -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a string S describing the row with N cells. Each character is either '0' or '1', denoting an empty cell or a cell with a soldier respectively. -----Output----- For each test case, output a single line containing one integer — the maximum possible number of seconds Limak will play the game. -----Constraints----- - 1 ≤ T ≤ 5 - 1 ≤ N ≤ 105 (N denotes the length of the string S) -----Subtasks----- - Subtask #1 (25 points): 1 ≤ N ≤ 10 - Subtask #2 (25 points): 1 ≤ N ≤ 2000 - Subtask #3 (50 points): Original constraints. -----Example----- Input: 4 10100 1100001 000000000111 001110100011010 Output: 8 10 0 48 -----Explanation----- Test case 1. The initial string is 10100. There are N = 5 cells. There is one soldier in the first cell, and one soldier in the third cell. The following scenario maximizes the total time: - Limak chooses the soldier in the first cell. This soldier can move only one cell to the right. It takes 1 second to choose a soldier and 1 second for a soldier to move to the next cell (2 seconds in total). The string is 01100 now. - Limak has only one choice. He must choose the soldier in the third cell because the other soldier can't move at all (the soldier in the second cell can't move to the right because the next cell is already occupied). Choosing a soldier takes 1 second. The chosen soldier moves from the third cell to the fifth cell, which takes 2 seconds. This operation takes 1 + 2 = 3 seconds in total. The string is 01001 now. - Limak has only one choice again. Since the soldier in the last row can't move further to the right, the soldier in the second cell must be chosen. He will move 2 cells to the right. This operation takes 1 + 2 = 3 seconds in total. The string become 00011 and the game is over. The total time is 2 + 3 + 3 = 8. Test case 2. The initial string is 1100001. There is only one possible scenario: - 1100001 is changed to 1000011 in 5 seconds (1 second to choose a soldier and 4 seconds for the soldier to move 4 cells to the right). - 1000011 is changed to 0000111 in 5 seconds. The total time is 5 + 5 = 10 seconds. Test case 3. The game is over immediately because all soldiers occupy rightmost cells already. The answer is 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): l=list(map(int,input().strip())) for j in range(len(l)-1,-1,-1): if l[j]==1: l.pop() else: break if l.count(1): time,prev,z,c=0,0,0,0 for j in range(len(l)-1,-1,-1): if l[j]==0: z+=1 continue if prev!=z: prev=z c+=1 time+=c+z print(time) else: print(0) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today is Chocolate day and Kabir and Tara are visiting a Valentine fair. Upon arriving, they find a stall with an interesting game. There are N$N$ jars having some chocolates in them. To win the game, one has to select the maximum number of consecutive jars such that the sum of count of chocolates in maximum and second maximum jar is less than or equal to k$k$ in that range. Kabir wants to win the game so that he can gift the chocolates to Tara. You are a friend of Kabiir, help him win the game. There will be at least one possible answer. Note$Note$ : - You have to select at least two jars. - Count of chocolates in maximum and second maximum jar among selected consecutive jars may be equal. -----Input:----- - First line will contain T$T$, number of test cases. - First line of each test case contains two space separated integers N,k$N, k$. - Second line of each test case contains N$N$ space separated integer ai$a_i$ denotes number of chocolates in the jar. -----Output:----- For each test case print maximum number of jars. -----Constraints:----- - 1≤T≤10$1 \leq T \leq 10$ - 2≤N≤105$2 \leq N \leq 10^5$ - 1≤ai≤105$1 \leq a_i \leq 10^5$ -----Sample Input:----- 1 6 5 1 3 3 1 1 5 -----Sample Output:----- 3 -----EXPLANATION:----- You can select 3rd$3^{rd}$, 4th$4^{th}$, and 5th$5^{th}$ jar as the sum of max and second max is equal to 4 which is less then 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 for u in range(int(input())): n,r=list(map(int,input().split())) l=list(map(int,input().split())) m=0 for i in range(n-1): d=[] d.append(l[i]) c=1 while(i+c<n): d.append(l[i+c]) d.sort(reverse=True) if(d[0]+d[1]<=r): c=c+1 else: break if(c>m): m=c print(m) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are fed up with your messy room, so you decided to clean it up. Your room is a bracket sequence $s=s_{1}s_{2}\dots s_{n}$ of length $n$. Each character of this string is either an opening bracket '(' or a closing bracket ')'. In one operation you can choose any consecutive substring of $s$ and reverse it. In other words, you can choose any substring $s[l \dots r]=s_l, s_{l+1}, \dots, s_r$ and change the order of elements in it into $s_r, s_{r-1}, \dots, s_{l}$. For example, if you will decide to reverse substring $s[2 \dots 4]$ of string $s=$"((()))" it will be equal to $s=$"()(())". A regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not. A prefix of a string $s$ is a substring that starts at position $1$. For example, for $s=$"(())()" there are $6$ prefixes: "(", "((", "(()", "(())", "(())(" and "(())()". In your opinion, a neat and clean room $s$ is a bracket sequence that: the whole string $s$ is a regular bracket sequence; and there are exactly $k$ prefixes of this sequence which are regular (including whole $s$ itself). For example, if $k = 2$, then "(())()" is a neat and clean room. You want to use at most $n$ operations to make your room neat and clean. Operations are applied one after another sequentially. It is guaranteed that the answer exists. Note that you do not need to minimize the number of operations: find any way to achieve the desired configuration in $n$ or less operations. -----Input----- The first line contains integer number $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then $t$ test cases follow. The first line of a test case contains two integers $n$ and $k$ ($1 \le k \le \frac{n}{2}, 2 \le n \le 2000$, $n$ is even) — length of $s$ and required number of regular prefixes. The second line of a test case contains $s$ of length $n$ — the given bracket sequence. It contains only '(' and ')'. It is guaranteed that there are exactly $\frac{n}{2}$ characters '(' and exactly $\frac{n}{2}$ characters ')' in the given string. The sum of all values $n$ over all the test cases in the input doesn't exceed $2000$. -----Output----- For each test case print an answer. In the first line print integer $m$ ($0 \le m \le n$) — the number of operations. You do not need to minimize $m$, any value is suitable. In the following $m$ lines print description of the operations, each line should contain two integers $l,r$ ($1 \le l \le r \le n$), representing single reverse operation of $s[l \dots r]=s_{l}s_{l+1}\dots s_{r}$. Operations are applied one after another sequentially. The final $s$ after all operations should be a regular, also it should be exactly $k$ prefixes (including $s$) which are regular. It is guaranteed that the answer exists. If there are several possible answers you can print any. -----Example----- Input 4 8 2 ()(())() 10 3 ))()()()(( 2 1 () 2 1 )( Output 4 3 4 1 1 5 8 2 2 3 4 10 1 4 6 7 0 1 1 2 -----Note----- In the first example, the final sequence is "()(()())", where two prefixes are regular, "()" and "()(()())". Note, that all the operations except "5 8" in the example output are useless (they do not change $s$). 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 tt in range(t): n,k=list(map(int,input().split())) s = input() ans = [] if s[0] == ')': for i in range(n): if s[i] == '(': ans.append([1,i+1]) s = s[i::-1] + s[i+1:] break for i in range(1,(k-1)*2): if i%2==0: if s[i]!='(': for j in range(i+1,n): if s[j] == '(': ans.append([i+1,j+1]) s = s[:i] + s[j:i-1:-1] + s[j+1:] break else: if s[i]!=')': for j in range(i+1,n): if s[j] == ')': ans.append([i+1,j+1]) s = s[:i] + s[j:i-1:-1] + s[j+1:] break for i in range((k-1)*2,(n+(2*(k-1)))//2+1): if s[i]!='(': for j in range(i+1,n): if s[j] == '(': ans.append([i+1,j+1]) s = s[:i] + s[j:i-1:-1] + s[j+1:] break print(len(ans)) for i in ans: print(*i) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degrees. -----Input----- The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains three angles A, B and C, of the triangle separated by space. -----Output----- For each test case, display 'YES' if the triangle is valid, and 'NO', if it is not, in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A,B,C ≤ 180 -----Example----- Input 3 40 40 100 45 45 90 180 1 1 Output YES YES NO The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n=int(input()) for i in range(n): a,b,c=map(int,input().split()) if a>0 and b>0 and c>0 and a+b+c==180: print("YES") else: print("NO") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Roger recently built a circular race track with length K$K$. After hosting a few races, he realised that people do not come there to see the race itself, they come to see racers crash into each other (what's wrong with our generation…). After this realisation, Roger decided to hold a different kind of "races": he hired N$N$ racers (numbered 1$1$ through N$N$) whose task is to crash into each other. At the beginning, for each valid i$i$, the i$i$-th racer is Xi$X_i$ metres away from the starting point of the track (measured in the clockwise direction) and driving in the direction Di$D_i$ (clockwise or counterclockwise). All racers move with the constant speed 1$1$ metre per second. The lengths of cars are negligible, but the track is only wide enough for one car, so whenever two cars have the same position along the track, they crash into each other and the direction of movement of each of these cars changes (from clockwise to counterclockwise and vice versa). The cars do not change the directions of their movement otherwise. Since crashes reduce the lifetime of the racing cars, Roger sometimes wonders how many crashes happen. You should answer Q$Q$ queries. In each query, you are given an integer T$T$ and you should find the number of crashes that happen until T$T$ seconds have passed (inclusive). -----Input----- - The first line of the input contains three space-separated integers N$N$, Q$Q$ and K$K$. - N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains two space-separated integers Di$D_i$ and Xi$X_i$, where Di=1$D_i = 1$ and Di=2$D_i = 2$ denote the clockwise and counterclockwise directions respectively. - Each of the next Q$Q$ lines contain a single integer T$T$ describing a query. -----Output----- For each query, print a single line containing one integer — the number of crashes. -----Constraints----- - 1≤N≤105$1 \le N \le 10^5$ - 1≤Q≤1,000$1 \le Q \le 1,000$ - 1≤K≤1012$1 \le K \le 10^{12}$ - 1≤Di≤2$1 \le D_i \le 2$ for each valid i$i$ - 0≤Xi≤K−1$0 \le X_i \le K - 1$ for each valid i$i$ - X1,X2,…,XN$X_1, X_2, \ldots, X_N$ are pairwise distinct - 0≤T≤1012$0 \le T \le 10^{12}$ -----Example Input----- 5 3 11 1 3 1 10 2 4 2 7 2 0 3 8 100 -----Example Output----- 4 10 110 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import numpy as np from numba import njit i8 = np.int64 @njit def solve(a, b, t, K, N): t1 = t // K d = t % K * 2 # b が a から a + d の位置にあれば衝突する x = 0 y = 0 ans = 0 for c in a: while b[x] < c: x += 1 while b[y] <= c + d: y += 1 ans += y - x ans += t1 * len(a) * (N - len(a)) * 2 return ans def set_ini(DX, K): a = DX[1][DX[0] == 1] a = np.sort(a) b = DX[1][DX[0] == 2] b = np.sort(b) b = np.hstack((b, b + K, b + 2 * K, [3 * K])) return a, b def main(): f = open('/dev/stdin', 'rb') vin = np.fromstring(f.read(), i8, sep=' ') N, Q, K = vin[0:3] head = 3 DX = vin[head:head + 2*N].reshape(-1, 2).T a, b = set_ini(DX, K) head += 2 * N T = vin[head: head + Q] for t in T: print(solve(a, b, t, K, N)) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It's winter and taking a bath is a delicate matter. Chef has two buckets of water. The first bucket has $v_1$ volume of cold water at temperature $t_1$. The second has $v_2$ volume of hot water at temperature $t_2$. Chef wants to take a bath with at least $v_3$ volume of water which is at exactly $t_3$ temperature. To get the required amount of water, Chef can mix some water obtained from the first and second buckets. Mixing $v_x$ volume of water at temperature $t_x$ with $v_y$ volume of water at temperature $t_y$ yields $v_x + v_y$ volume of water at temperature calculated as vxtx+vytyvx+vyvxtx+vytyvx+vy\frac{v_x t_x + v_y t_y}{v_x + v_y} Help Chef figure out if it is possible for him to take a bath with at least $v_3$ volume of water at temperature $t_3$. Assume that Chef has no other source of water and that no heat is lost by the water in the buckets with time, so Chef cannot simply wait for the water to cool. -----Input----- - The first line contains $n$, the number of test cases. $n$ cases follow. - Each testcase contains of a single line containing 6 integers $v_1, t_1, v_2, t_2, v_3, t_3$. -----Output----- - For each test case, print a single line containing "YES" if Chef can take a bath the way he wants and "NO" otherwise. -----Constraints----- - $1 \leq n \leq 10^5$ - $1 \leq v_1, v_2, v_3 \leq 10^6$ - $1 \leq t_1 < t_2 \leq 10^6$ - $1 \leq t_3 \leq 10^6$ -----Sample Input----- 3 5 10 5 20 8 15 5 10 5 20 1 30 5 10 5 20 5 20 -----Sample Output----- YES NO YES -----Explanation----- - Case 1: Mixing all the water in both buckets yields 10 volume of water at temperature 15, which is more than the required 8. - Case 2: It is not possible to get water at 30 temperature. - Case 3: Chef can take a bath using only the water in the second bucket. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: for i in range(int(input())): v1,t1,v2,t2,v3,t3=map(int,input().split()) ok = 0 if t1 <= t3 <= t2: x, y = t2 - t3, t3 - t1 ok = x * v3 <= (x + y) * v1 and y * v3 <= (x + y) * v2 print('YES' if ok else 'NO') except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a dataset consisting of $N$ items. Each item is a pair of a word and a boolean denoting whether the given word is a spam word or not. We want to use this dataset for training our latest machine learning model. Thus we want to choose some subset of this dataset as training dataset. We want to make sure that there are no contradictions in our training set, i.e. there shouldn't be a word included in the training set that's marked both as spam and not-spam. For example item {"fck", 1}, and item {"fck, 0"} can't be present in the training set, because first item says the word "fck" is a spam, whereas the second item says it is not, which is a contradiction. Your task is to select the maximum number of items in the training set. Note that same pair of {word, bool} can appear multiple times in input. The training set can also contain the same pair multiple times. -----Input----- - First line will contain $T$, number of test cases. Then the test cases follow. - 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 a string $w_i$, followed by a space and an integer(boolean) $s_i$, denoting the $i$-th item. -----Output----- For each test case, output an integer corresponding to the maximum number of items that can be included in the training set in a single line. -----Constraints----- - $1 \le T \le 10$ - $1 \le N \le 25,000$ - $1 \le |w_i| \le 5$ for each valid $i$ - $0 \le s_i \le 1$ for each valid $i$ - $w_1, w_2, \ldots, w_N$ contain only lowercase English letters -----Example Input----- 3 3 abc 0 abc 1 efg 1 7 fck 1 fck 0 fck 1 body 0 body 0 body 0 ram 0 5 vv 1 vv 0 vv 0 vv 1 vv 1 -----Example Output----- 2 6 3 -----Explanation----- Example case 1: You can include either of the first and the second item, but not both. The third item can also be taken. This way the training set can contain at the very max 2 items. Example case 2: You can include all the items except the second item in the training set. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) a = {} for i in range(n): l = input() if l not in a: a[l] = 1 else: a[l] += 1 done = [] ans = 0 for i in a: if a[i] != 0: temp = [x for x in i.split()] v = temp[0] v0 = v + " 0" v1 = v + " 1" if(v0 in a and v1 in a): if a[v0] > a[v1]: ans += a[v0] else: ans += a[v1] a[v0] = a[v1] = 0 elif(v0 in a): ans += a[v0] a[v0] = 0 elif(v1 in a): ans += a[v1] a[v1] = 0 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This time minions are celebrating Diwali Festival. There are N minions in total. Each of them owns a house. On this Festival, Each of them wants to decorate their house. But none of them have enough money to do that. One of the minion, Kevin, requested Gru for money. Gru agreed for money distribution but he will be giving money to a minion if and only if demanded money is less than or equal to the money Gru have. Now Gru wonders if he can spend all the money or not. -----Input----- First line have number of test cases T. Each test case consist of Two Lines. First line contains two space separated integers N and K i.e. Number of minions and Amount of Money Gru have. Next line contains N space separated integers A1,A2,A3,.....,AN representing amount of money demanded by ith minion. -----Output----- Output YES if Gru can spend his all of the money on minions i.e. after distribution Gru have zero amount of money else NO. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ N ≤ 102 - 1 ≤ K,Ai ≤ 109 -----Example----- Input: 2 4 9 5 2 2 4 4 9 5 2 18 3 Output: YES NO -----Explanation----- Example case 1.At first Gru is having 9 Rs. If he gives 5 Rs. to first minion then remaining 4 Rs. can be given to 2nd and 3rd minion or to the 4th minion. Which will leave zero amount of money in the hands of Gru. Example case 2.At first Gru is having 9 Rs. If he gives 5 Rs. to the first minion then from remaining 4 Rs. either he can give 2 Rs. to the 2nd minion or 3 Rs. to the fourth minion. Which will leave either 2 Rs. or 1 Rs. in the hands of Gru. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def find_combinations(list, sum): if not list: if sum == 0: return [[]] return [] return find_combinations(list[1:], sum) + \ [[list[0]] + tail for tail in find_combinations(list[1:], sum - list[0])] for tc in range(int(input())): n,k=list(map(int,input().split())) a=list(map(int,input().split())) a.sort() if len(find_combinations(a,k))==0: print("NO") else: print("YES") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The sequence of $m$ integers is called the permutation if it contains all integers from $1$ to $m$ exactly once. The number $m$ is called the length of the permutation. Dreamoon has two permutations $p_1$ and $p_2$ of non-zero lengths $l_1$ and $l_2$. Now Dreamoon concatenates these two permutations into another sequence $a$ of length $l_1 + l_2$. First $l_1$ elements of $a$ is the permutation $p_1$ and next $l_2$ elements of $a$ is the permutation $p_2$. You are given the sequence $a$, and you need to find two permutations $p_1$ and $p_2$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.) -----Input----- The first line contains an integer $t$ ($1 \le t \le 10\,000$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains one integer $n$ ($2 \leq n \leq 200\,000$): the length of $a$. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq n-1$). The total sum of $n$ is less than $200\,000$. -----Output----- For each test case, the first line of output should contain one integer $k$: the number of ways to divide $a$ into permutations $p_1$ and $p_2$. Each of the next $k$ lines should contain two integers $l_1$ and $l_2$ ($1 \leq l_1, l_2 \leq n, l_1 + l_2 = n$), denoting, that it is possible to divide $a$ into two permutations of length $l_1$ and $l_2$ ($p_1$ is the first $l_1$ elements of $a$, and $p_2$ is the last $l_2$ elements of $a$). You can print solutions in any order. -----Example----- Input 6 5 1 4 3 2 1 6 2 4 1 3 2 1 4 2 1 1 3 4 1 3 3 1 12 2 1 3 4 5 6 7 8 9 1 10 2 3 1 1 1 Output 2 1 4 4 1 1 4 2 0 0 1 2 10 0 -----Note----- In the first example, two possible ways to divide $a$ into permutations are $\{1\} + \{4, 3, 2, 1\}$ and $\{1,4,3,2\} + \{1\}$. In the second example, the only way to divide $a$ into permutations is $\{2,4,1,3\} + \{2,1\}$. In the third example, there are no possible ways. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def possible(a): ans = set() s = set() lmax = 0 for i in range(len(a)): lmax = max(lmax, a[i]) s.add(a[i]) if lmax == i + 1 and len(s) == i + 1: ans.add(i + 1) return ans t = int(input()) for case_num in range(t): n = int(input()) a = list(map(int, input().split(' '))) left = possible(a) a.reverse() right = possible(a) ans = [] for l in left: if n - l in right: ans.append(l) print(len(ans)) for l in ans: print(l, n - l) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. -----Input----- A single line contains an integer k (1 ≤ k ≤ 10^5) — the number of cycles of length 3 in the required graph. -----Output----- In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. -----Examples----- Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python k = int(input()) p = [['0'] * 100 for j in range(100)] g = lambda n: n * (n * n - 1) // 6 i = n = 0 while g(n + 1) <= k: n += 1 while i < n + 1: for j in range(i): p[i][j] = p[j][i] = '1' i += 1 k -= g(n) g = lambda n: n * n - n >> 1 while k: n = 0 while g(n + 1) <= k: n += 1 for j in range(n): p[i][j] = p[j][i] = '1' k -= g(n) i += 1 print(i) for j in range(i): print(''.join(p[j][:i])) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: An agent called Cypher is decrypting a message, that contains a composite number $n$. All divisors of $n$, which are greater than $1$, are placed in a circle. Cypher can choose the initial order of numbers in the circle. In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed. A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message. Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that. -----Input----- The first line contains an integer $t$ $(1 \le t \le 100)$ — the number of test cases. Next $t$ lines describe each test case. In a single line of each test case description, there is a single composite number $n$ $(4 \le n \le 10^9)$ — the number from the message. It's guaranteed that the total number of divisors of $n$ for all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case in the first line output the initial order of divisors, which are greater than $1$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them. -----Example----- Input 3 6 4 30 Output 2 3 6 1 2 4 0 2 30 6 3 15 5 10 0 -----Note----- In the first test case $6$ has three divisors, which are greater than $1$: $2, 3, 6$. Regardless of the initial order, numbers $2$ and $3$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $2, 6, 3, 6$, and every two adjacent numbers are not coprime. In the second test case $4$ has two divisors greater than $1$: $2, 4$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples. In the third test case all divisors of $30$ greater than $1$ can be placed in some order so that there are no two adjacent numbers that are coprime. 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 t = int(input()) for _ in range(t): n = int(input()) pf = [] for i in range(2, ceil(n**0.5)+1): while n % i == 0: pf.append(i) n //= i if n > 1: pf.append(n) if len(pf) == 2 and pf[0] != pf[1]: print(pf[0], pf[1], pf[0]*pf[1]) print(1) else: pg = [] fac = [] nfac = [] while len(pf) > 0: p = pf[-1] mul = 0 while len(pf) > 0 and pf[-1] == p: pf.pop() mul += 1 pg.append([mul, p]) pg.sort() pg = pg[::-1] # print(pg) cur = 0 if pg[0][0] == 1: a = pg[0][1] b = pg[1][1] c = pg[2][1] fac = [a, a*b*c, a*b, b, b*c, c, a*c] cur = 3 else: fac = [pg[0][1]**i for i in range(1, pg[0][0]+1)] cur = 1 while cur < len(pg): mul = pg[cur][0] p = pg[cur][1] nfac = [] for i in range(len(fac)): if i == 0: nfac += [fac[i]*(p**j) for j in range(mul, -1, -1)] else: nfac += [fac[i]*(p**j) for j in range(mul+1)] nfac += [p**i for i in range(1, mul+1)] fac = nfac cur += 1 print(" ".join([str(i) for i in fac])) print(0) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq K \leq 50$ -----Sample Input:----- 5 1 2 3 4 5 -----Sample Output:----- 1 1 23 1 23 456 1 23 4 5 6789 1 23 4 5 6 7 89101112 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n = int(input()) count = 1 l = 3*(n-1) i = 0 if n==1: print(1) continue while count<=l-n: for j in range(i+1): if j==i: print(count) count += 1 elif j==0: print(count,end="") count += 1 else: print(" ",end="") i+=1 while count<=l: print(count,end="") count += 1 print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: For a string $S$ let the unique set of characters that occur in it one or more times be $C$. Consider a permutation of the elements of $C$ as $(c_1, c_2, c_3 ... )$. Let $f(c)$ be the number of times $c$ occurs in $S$. If any such permutation of the elements of $C$ satisfies $f(c_i) = f(c_{i-1}) + f(c_{i-2})$ for all $i \ge 3$, the string is said to be a dynamic string. Mr Bancroft is given the task to check if the string is dynamic, but he is busy playing with sandpaper. Would you help him in such a state? Note that if the number of distinct characters in the string is less than 3, i.e. if $|C| < 3$, then the string is always dynamic. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, a string $S$. -----Output:----- For each testcase, output in a single line "Dynamic" if the given string is dynamic, otherwise print "Not". (Note that the judge is case sensitive) -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq |S| \leq 10^5$ - $S$ contains only lower case alphabets: $a$, $b$, …, $z$ -----Sample Input:----- 3 aaaabccc aabbcc ppppmmnnoooopp -----Sample Output:----- Dynamic Not Dynamic -----Explanation:----- - Testase 1: For the given string, $C = \{a, b, c\}$ and $f(a)=4, f(b)=1, f(c)=3$. $f(a) = f(c) + f(b)$ so the permutation $(b, c, a)$ satisfies the requirement. - Testcase 2: Here too $C = \{a, b, c\}$ but no permutation satisfies the requirement of a dynamic string. - Testcase 3: Here $C = \{m, n, o, p\}$ and $(m, n, o, p)$ is a permutation that makes it a dynamic string. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t=int(input()) for _ in range(t): st=input() s=set(st) a=[] f1=f2=0 for i in s: a.append(st.count(i)) a.sort() if len(a)>=3: for i in range(2,len(a)): if a[i]!=a[i-1]+a[i-2]: f1=1 break x=a[0] a[0]=a[1] a[1]=x for i in range(2,len(a)): if a[i]!=a[i-1]+a[i-2]: f2=1 break if f1==1 and f2==1: print("Not") else: print("Dynamic") else: print("Dynamic") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are given a sequence a consisting of n integers. Find the maximum possible value of $a_{i} \operatorname{mod} a_{j}$ (integer remainder of a_{i} divided by a_{j}), where 1 ≤ i, j ≤ n and a_{i} ≥ a_{j}. -----Input----- The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·10^5). The second line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 10^6). -----Output----- Print the answer to the problem. -----Examples----- Input 3 3 4 5 Output 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(): input() aa = sorted(map(int, input().split())) maxa = max(aa) m = [False] * (maxa + 1) x = [] b = 0 for a in aa: if b != a: m[a] = True for i in range(b, a): x.append(b) b = a x.append(b) ans = 0 for i in range(maxa - 1, 1, -1): if i < ans: break if m[i]: for j in range(1, maxa // i + 1): ans = max(ans, x[min(i * (j + 1) - 1, maxa)] % i) print(ans) def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are playing a Billiards-like game on an $N \times N$ table, which has its four corners at the points $\{(0, 0), (0, N), (N, 0),$ and $(N, N)\}$. You start from a coordinate $(x,y)$, $(0 < x < N, 0 < y < N)$ and shoot the ball at an angle $45^{\circ}$ with the horizontal. On hitting the sides, the ball continues to move with the same velocity and ensuring that the angle of incidence is equal to the angle of reflection with the normal, i.e, it is reflected with zero frictional loss. On hitting either of the four corners, the ball stops there and doesn’t move any further. Find the coordinates of the point of collision, when the ball hits the sides for the $K^{th}$ time. If the ball stops before hitting the sides $K$ times, find the coordinates of the corner point where the ball stopped instead. -----Input:----- - The first line of the input contains an integer $T$, the number of testcases. - Each testcase contains a single line of input, which has four space separated integers - $N$, $K$, $x$, $y$, denoting the size of the board, the number of collisions to report the answer for, and the starting coordinates. -----Output:----- For each testcase, print the coordinates of the ball when it hits the sides for the $K^{th}$ time, or the coordinates of the corner point if it stopped earlier. -----Constraints----- - $1 \leq T \leq 10^5$ - $2 \leq N \leq 10^9$ - $1 \leq K \leq 10^9$ -----Subtasks----- - $30$ points : Sum of $K$ over all test cases $\le 10^7$ - $70$ points : Original constraints. -----Sample Input:----- 2 5 5 4 4 5 2 3 1 -----Sample Output:----- 5 5 3 5 -----Explanation:----- - Sample Case $1$ : We are given a $5$ by $5$ board. We shoot the ball from coordinates $(4,4)$, and we need to find its coordinates after it has collided with sides $5$ times. However, after shooting, the ball goes directly to the corner $(5,5)$, and stops there. So we report the coordinates $(5,5)$. - Sample Case $2$ : We are given a $5$ by $5$ board. We shoot the ball from the coordinates $(3,1)$, and we need to find its coordinates after it has collided with the sides twice. After shooting, it first hits the right side at $(5,3)$, and then the top side at $(3,5)$. So, we report $(3,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()) for i in range(t): a=0 b=0 N,K,x,y=map(int,input().split()) if x==y: a=N b=N elif x>y: if K%4==1: a=N b=y-x+N elif K%4==2: a=y-x+N b=N elif K%4==3: a=0 b=x-y else: a=x-y b=0 else: if K%4==1: a=x-y+N b=N elif K%4==2: a=N b=x-y+N elif K%4==3: a=y-x b=0 else: a=0 b=y-x print(a,b) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The Little Elephant loves lucky strings. Everybody knows that the lucky string is a string of digits that contains only the lucky digits 4 and 7. For example, strings "47", "744", "4" are lucky while "5", "17", "467" are not. The Little Elephant has the strings A and B of digits. These strings are of equal lengths, that is |A| = |B|. He wants to get some lucky string from them. For this he performs the following operations. At first he arbitrary reorders digits of A. Then he arbitrary reorders digits of B. After that he creates the string C such that its i-th digit is the maximum between the i-th digit of A and the i-th digit of B. In other words, C[i] = max{A[i], B[i]} for i from 1 to |A|. After that he removes from C all non-lucky digits saving the order of the remaining (lucky) digits. So C now becomes a lucky string. For example, if after reordering A = "754" and B = "873", then C is at first "874" and then it becomes "74". The Little Elephant wants the resulting string to be as lucky as possible. The formal definition of this is that the resulting string should be the lexicographically greatest possible string among all the strings that can be obtained from the given strings A and B by the described process. Notes - |A| denotes the length of the string A. - A[i] denotes the i-th digit of the string A. Here we numerate the digits starting from 1. So 1 ≤ i ≤ |A|. - The string A is called lexicographically greater than the string B if either there exists some index i such that A[i] > B[i] and for each j < i we have A[j] = B[j], or B is a proper prefix of A, that is, |A| > |B| and first |B| digits of A coincide with the corresponding digits of B. -----Input----- The first line of the input contains a single integer T, the number of test cases. T test cases follow. Each test case consists of two lines. The first line contains the string A. The second line contains the string B. -----Output----- For each test case output a single line containing the answer for the corresponding test case. Note, that the answer can be an empty string. In this case you should print an empty line for the corresponding test case. -----Constraints----- 1 ≤ T ≤ 10000 1 ≤ |A| ≤ 20000 |A| = |B| Each character of A and B is a digit. Sum of |A| across all the tests in the input does not exceed 200000. -----Example----- Input: 4 4 7 435 479 7 8 1675475 9756417 Output: 7 74 777744 -----Explanation----- Case 1. In this case the only possible string C we can get is "7" and it is the lucky string. Case 2. If we reorder A and B as A = "543" and B = "749" the string C will be at first "749" and then becomes "74". It can be shown that this is the lexicographically greatest string for the given A and B. Case 3. In this case the only possible string C we can get is "8" and it becomes and empty string after removing of non-lucky digits. Case 4. If we reorder A and B as A = "7765541" and B = "5697714" the string C will be at first "7797744" and then becomes "777744". Note that we can construct any lexicographically greater string for the given A and B since we have only four "sevens" and two "fours" among digits of both strings A and B as well the constructed string "777744". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for i in range(0,t): a = input() b = input() agts=bgts=afour=bfour=aseven=bseven=altf=bltf=afts=bfts=0; for j in a: if j >= '7': if j > '7': agts += 1 else: aseven += 1 elif j >= '4': if j > '4': afts += 1 else: afour += 1 else: altf += 1 for j in b: if j >= '7': if j > '7': bgts += 1 else: bseven += 1 elif j >= '4': if j > '4': bfts += 1 else: bfour += 1 else: bltf += 1 nseven = 0 nfour = 0 if aseven > bfts: aseven -= bfts; nseven += bfts; bfts = 0; else: bfts -= aseven; nseven += aseven; aseven = 0; if bseven > afts: bseven -= afts; nseven += afts; afts = 0; else: afts -= bseven; nseven += bseven; bseven = 0; if aseven > bltf: aseven -= bltf; nseven += bltf; bltf = 0; else: bltf -= aseven; nseven += aseven; aseven = 0; if bseven > altf: bseven -= altf; nseven += altf; altf = 0; else: altf -= bseven; nseven += bseven; bseven = 0; if aseven > bfour: aseven -= bfour; nseven += bfour; bfour = 0; else: bfour -= aseven; nseven += aseven; aseven = 0; if bseven > afour: bseven -= afour; nseven += afour; afour = 0; else: afour -= bseven; nseven += bseven; bseven = 0; nseven += min(aseven,bseven) if afour > bltf: afour -= bltf; nfour += bltf; bltf = 0 else: bltf -= afour; nfour += afour; afour = 0; if bfour > altf: bfour -= altf; nfour += altf; altf = 0 else: altf -= bfour; nfour += bfour; bfour = 0; nfour += min(afour,bfour) print('7'*nseven + '4'*nfour) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime. -----Input----- The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each. -----Output----- Write a single integer to output, denoting how many integers ti are divisible by k. -----Example----- Input: 7 3 1 51 966369 7 9 999996 11 Output: 4 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. (n, k) = list(map(int, input().split(' '))) ans = 0 for i in range(n): x = int(input()) if x % k == 0: ans += 1 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: In this problem we are concerned with words constructed using the lowercase letters of the English alphabet - that is, a,b,c,…,z. These words need not necessarily be meaningful: any sequence of letters forms a word. For example, abbca is a word. We say that we can "hop" from the word $w_1$ to the word $w_2$ if they are "sufficiently close". We define $w_2$ to be sufficiently close to $w_1$ if one of the following holds: - $w_2$ is obtained from $w_1$ by deleting one letter. - $w_2$ is obtained from $w_1$ by replacing one of the letters in $w_1$ by some letter that appears to its right in $w_1$ and which is also to its right in alphabetical order. For example, we can hop from abbca to abca by deleting the second (or third letter). We can hop from aabca to abbca by replacing the a in the second position by the letter b that appears to the right of the a in aabca and which is also to its right in alphabetical order. On the other hand we cannot hop from abbca to aabca since we would need to replace the b in the second position by a, but a is to the left of b in alphabetical order. You will be given a collection of words $W$. Your task is to find the length of the longest sequence $w_1, w_2, \ldots $ of distinct words from $W$ such that we may hop from $w_1$ to $w_2$, $w_2$ to $w_3$ and so on. We call this the hopping number for this set. For example, if $W$ = {abacd, bcdada, dd, abcd,bcdd, adcd, addd, aa, ccd, add, ad} then, the hopping number is 7 corresponding to the sequence abacd, abcd, adcd, addd, add, ad, dd -----Input Format:----- - The first line of the input contains one integer $N$ indicating the number of words in the input. - This is followed by $N$ lines of input, lines 2, 3,…, $N$+1, each containing one word over the letters {a,b,…, z}. -----Output Format:----- The output should be a single integer, indicating the hopping number of the given set of words. -----Test Data:----- - $N \leq 100$ - You may assume that each word has at most 10 letters. -----Sample Input:----- 11 abacd bcdada dd abcd bcdd adcd addd aa ccd add ad -----Sample Output:----- 7 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def codn1(s1,s2,p): c=0 ind=0 for i in range(len(s1)): if s1[i]!=s2[i]: c+=1 ind=i if c>1 or ind==len(s1)-1: return 0 if s1[ind]>s2[ind] and s1[ind] in s2[ind+1:]: p[0]=True if s1[ind]<s2[ind] and s2[ind] in s1[ind+1:]: p[1]=True return 1 def codn2(s1,s2): if len(s1)<len(s2): for i in range(len(s2)): if s2[:i]+s2[i+1:]==s1: return 1 else: for i in range(len(s1)): if s1[:i]+s1[i+1:]==s2: return 2 def longest(k): if cost[k]>0: return cost[k] for i in list(d[k]): cost[k]=max(cost[k],longest(i)+1) return cost[k] n=int(input()) l=[] #parent=[0]*n d={} cost={} for i in range(n): l.append(input()) d[i]=[] cost[i]=0 for i in range(n): for j in range(n): if i!=j: p=[False,False] if len(l[i])==len(l[j]): if codn1(l[i],l[j],p): if p[0]==True: d[j].append(i) if p[1]==True: d[i].append(j) elif abs(len(l[i])-len(l[j]))==1: y=codn2(l[i],l[j]) if y==1: d[j].append(i) if y==2: d[i].append(j) ans=0 #print(d) for i in range(n): ans=max(ans,longest(i)) print(ans+1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Lyra Belacqua is a very gifted girl. She is one of a very small set of people capable of reading an alethiometer, more commonly known as The Golden Compass. It has one specific use: to tell the truth. The name in fact, is derived from "Aletheia" meaning truth, and "-ometer", meaning "measuring device". The alethiometer had four needles, out of which the user would direct three of them to lie over symbols on the face of the device to ask a question. The fourth needle then swung into action and pointed to various symbols one after another, thus telling the answer. For this problem, consider the alethiometer consisting of symbols : digits '0'-'9' and letters 'A'-'Z'. Learned scholars were debating the age of the Universe, and they requested Lyra to find out the age from the alethiometer. Having asked the question, the fourth needle started spouting out symbols, which Lyra quickly recorded. In that long string of characters, she knows that some substring corresponds to the age of the Universe. She also knows that the alethiometer could have wrongly pointed out atmost one digit (0-9) as a letter (A-Z). She then wonders what is the maximum possible age of the Universe. Given the set of symbols the alethiometer pointed out, help her find the maximum age of the Universe, which could correspond to a substring of the original string with atmost one letter changed. Note: We consider a substring to be a contiguous part of the string S Also, the alethiometer wrongly reports only a letter. All the digits remain as they are. -----Input----- Each input consists of a single string S which is what Lyra recorded from the fourth needle's pointing. -----Output----- Output one number, the maximum possible answer. -----Constraints----- - 1 ≤ |S| ≤ 1,000 - S will only contain digits 0-9 and uppercase Latin letters. -----Example----- Input1: 06454 Input2: C0D3C43F Output1: 6454 Output2: 3943 -----Explanation----- In the first example, there is no choice as to what the number can be. It has to be 6,454. In the second example, there are a total of 41 possible strings (one for the original, and 10 for changing each letter). You can verify that the maximum number as a substring is got by making the string "C0D3943F". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python string=input() max_no=0 for i in range(len(string)): var_occur=0 check_no=str() j=i while(j<len(string) and var_occur<2 ): if(string[j].isalpha()): if(var_occur==0): check_no+='9' var_occur+=1 else: var_occur+=1 else: check_no+=string[j] j+=1 #print(check_no) max_no=max(max_no,int(check_no)) print(max_no) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Zonal Computing Olympiad 2012, 26 Nov 2011 A sequence of opening and closing brackets is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense. For instance, the sequences (), (()) and ()(()) are well-bracketed, while (, ()), (()(), and )( are not well-bracketed. The nesting depth of a well-bracketed sequence tells us the maximum number of levels of inner matched brackets enclosed within outer matched brackets. For instance, the nesting depth of () and ()()() is 1, the nesting depth of (()) and ()(()) is 2, the nesting depth of ((())) is 3, and so on. Given a well-bracketed sequence, we are interested in computing the following: - The nesting depth, and the first position where it occurs–this will be the position of the first opening bracket at this nesting depth, where the positions are numbered starting with 1. - The maximum number of symbols between any pair of matched brackets, including both the outer brackets, and the first position where this occurs–that is, the position of the first opening bracket of this segment For instance, the nesting depth of ()(())()(()())(()()) is 2 and the first position where this occurs is 4. The opening bracket at position 10 is also at nesting depth 2 but we have to report the first position where this occurs, which is 4. In this sequence, the maximum number of symbols between a pair of matched bracket is 6, starting at position 9. There is another such sequence of length 6 starting at position 15, but this is not the first such position. -----Input format----- The input consists of two lines. The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket ( and 2 denotes a closing bracket ). Nothing other than 1 or 2 appears in the second line of input and the corresponding expression is guaranteed to be well-bracketed. -----Output format----- Your program should print 4 space-separated integers in a line, denoting the four quantities asked for in the following order: nesting depth, first position that achieves the nesting depth, length of the maximum sequence between matching brackets and the first position where such a maximum length sequence occurs. -----Testdata----- You may assume that 2 ≤ N ≤ 105. In 30% of the test cases, 2 ≤ N ≤ 103. - Subtask 1 (30 marks) - Subtask 2 (70 marks) -----Sample Input----- 20 1 2 1 1 2 2 1 2 1 1 2 1 2 2 1 1 2 1 2 2 -----Sample Output----- 2 4 6 9 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here T = int(input()) l = list(map(int, input().strip().split(" "))) depth = 0 max_depth = 0 max_depth_index = 0 max_l=0 max_l_index=0 last_zero=-1 for i in range(T): if l[i] == 1: depth += 1 if depth > max_depth: max_depth = depth max_depth_index = i + 1 else: depth-=1 if depth == 0: length = i - last_zero if length > max_l: max_l = length max_l_index = last_zero + 2 last_zero = i print(max_depth, max_depth_index, max_l, max_l_index) """ 2 4 6 9 """ ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has arrived in Dagobah to meet with Yoda to study cooking. Yoda is a very busy cook and he doesn't want to spend time with losers. So he challenges the Chef to a series of games, and agrees to teach the Chef if Chef can win at least P of the games. The total number of games is K. The games will be played on a chessboard of size N*M. That is, it has N rows, each of which has M squares. At the beginning of the game, a coin is on square (1, 1), which corresponds to the top-left corner, and every other square is empty. At every step, Yoda and Chef have to move the coin on the chessboard. The player who cannot make a move loses. Chef makes the first move. They can't move the coin to a square where it had been placed sometime before in the game, and they can't move outside chessboard. In this game, there are two different sets of rules according to which the game can be played: -from (x, y) player can move coin to (x+1, y), (x-1, y), (x, y+1), (x, y-1) in his turn, if they are valid squares. -from (x, y) player can move coin to (x+1, y+1), (x-1, y-1), (x-1, y+1), (x+1, y-1) in his turn, if they are valid squares. Before every game, the Power of the kitchen chooses one among the two sets of rules with equal probability of 0.5, and the game will be played according to those rules. Chef and Yoda are very wise, therefore they play optimally. You have to calculate the probability that Yoda will teach Chef. -----Input----- Input begins with an integer T, the number of test cases Each test case begins with 4 integers N, M, P, K. -----Output----- For each test case, output a line containing the answer for task. The output must have an absolute error at most 0.000001 (10-6). -----Constraints and Subtasks----- - 1 ≤ T ≤ 50 - 1 ≤ K Subtask 1 : 10 points - 2 ≤ N, M ≤ 5 - 0 ≤ P ≤ K ≤ 5 Subtusk 2 : 10 points - 2 ≤ N, M ≤ 10 - 0 ≤ P ≤ K ≤ 10^3 Subtusk 3 : 20 points - 2 ≤ N, M ≤ 100 - 0 ≤ P ≤ K ≤ 10^3 Subtusk 4 : 60 points - 2 ≤ N, M ≤ 100 - 0 ≤ P ≤ K ≤ 10^6 -----Example----- Input: 2 2 3 2 3 2 2 5 5 Output: 0.500000 1.000000 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math dp = [] dp.append(0) for i in range(1,1000005): dp.append(math.log(i) + dp[i-1]) t = int(input()) for i in range(t): n,m,p,k = input().split() n = int(n) m = int(m) p = int(p) k = int(k) if p==0 or (n%2==0 and m%2==0): ans = 1.0 print(ans) elif n%2==1 and m%2==1: ans=0.0 print(ans*100) else: P = 0 kln2 = k*math.log(2) for i in range(p, k+1): lnPi = dp[k] - dp[i] - dp[k-i] - kln2 Pi = pow(math.e, lnPi) P += Pi print(P) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$. Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on. The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal. Count the number of different legal paths you can take from the start to the goal modulo $10^9 + 7$. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other. -----Input----- The first line contains two integers $n, m$ — dimensions of the labyrinth ($1 \leq n, m \leq 2000$). Next $n$ lines describe the labyrinth. Each of these lines contains $m$ characters. The $j$-th character of the $i$-th of these lines is equal to "R" if the cell $(i, j)$ contains a rock, or "." if the cell $(i, j)$ is empty. It is guaranteed that the starting cell $(1, 1)$ is empty. -----Output----- Print a single integer — the number of different legal paths from $(1, 1)$ to $(n, m)$ modulo $10^9 + 7$. -----Examples----- Input 1 1 . Output 1 Input 2 3 ... ..R Output 0 Input 4 4 ...R .RR. .RR. R... Output 4 -----Note----- In the first sample case we can't (and don't have to) move, hence the only path consists of a single cell $(1, 1)$. In the second sample case the goal is blocked and is unreachable. Illustrations for the third sample case can be found here: https://assets.codeforces.com/rounds/1225/index.html The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def getSum(dp, pos, s, e, type_): if e < s: return 0 if type_=='D': if e==m-1: return dp[pos][s] return dp[pos][s]-dp[pos][e+1] else: if e==n-1: return dp[s][pos] return dp[s][pos]-dp[e+1][pos] mod = 10**9+7 n, m = map(int, input().split()) a = [list(list(map(lambda x: 1 if x=='R' else 0, input()))) for _ in range(n)] SD = [[0]*m for _ in range(n)] SN = [[0]*m for _ in range(n)] dpD = [[0]*m for _ in range(n)] dpN = [[0]*m for _ in range(n)] for i in range(n-1, -1, -1): for j in range(m-1, -1, -1): if i == n-1: SD[i][j]=a[i][j] else: SD[i][j]=SD[i+1][j]+a[i][j] if j == m-1: SN[i][j]=a[i][j] else: SN[i][j]=SN[i][j+1]+a[i][j] for j in range(m-1,-1,-1): if a[n-1][j]==1: break dpD[n-1][j]=1 dpN[n-1][j]=1 for i in range(n-1,-1,-1): if a[i][m-1]==1: break dpD[i][m-1]=1 dpN[i][m-1]=1 for j in range(m-2, -1, -1): if i==n-1: break dpD[n-1][j]+=dpD[n-1][j+1] for i in range(n-2,-1,-1): if j==m-1: break dpN[i][m-1]+=dpN[i+1][m-1] for i in range(n-2,-1,-1): for j in range(m-2,-1,-1): s, e = j, m-SN[i][j]-1 #print(i, j, s, e, 'N') dpN[i][j] = getSum(dpD, i+1, s, e, 'D') dpN[i][j] = (dpN[i][j] + dpN[i+1][j]) % mod s, e = i, n-SD[i][j]-1 #print(i, j, s, e, 'D') dpD[i][j] = getSum(dpN, j+1, s, e, 'N') if i != 0: for j in range(m-2,-1,-1): dpD[i][j] = (dpD[i][j] + dpD[i][j+1]) % mod print(dpD[0][0] % mod) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Navnit is a college student and there are $N$ students in his college .Students are numbered from $1$ to $N$. You are given $M$ facts that "Student $A_i$ and $B_i$".The same fact can be given multiple times .If $A_i$ is a friend of $B_i$ ,then $B_i$ is also a friend of $A_i$ . If $A_i$ is a friend of $B_i$ and $B_i$ is a friend of $C_i$ then $A_i$ is also a friend of $C_i$. Find number of ways in which two students can be selected in such a way that they are not friends. -----Input:----- - First line will contain two integers $N$ and $M$. - Then $M$ lines follow. Each line contains two integers $A_i$ and $B_i$ denoting the students who are friends. -----Output:----- For each testcase, output the number of ways in which two students can be selected in such a way that they are friends. -----Constraints----- - $2 \leq N \leq 200000$ - $0 \leq M \leq 200000$ - $1 \leq A_i,B_i \leq N$ -----Sample Input:----- 5 3 1 2 3 4 1 5 -----Sample Output:----- 6 -----EXPLANATION:----- Groups of friend are $[1,2,5]$ and $[3,4]$.Hence the answer is 3 X 2 =6. 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 defaultdict d=defaultdict(list) def dfs(i): p=0 nonlocal v e=[i] while(e!=[]): p+=1 x=e.pop(0) v[x]=1 for i in d[x]: if v[i]==-1: v[i]=1 e.append(i) return p n,m=list(map(int,input().split())) for i in range(n+1): d[i]=[] for _ in range(m): a,b=list(map(int,input().split())) d[a].append(b) d[b].append(a) v=[] for i in range(n+1): v.append(-1) c=0 p=[] for i in range(1,n+1): if v[i]==-1: c+=1 p.append(dfs(i)) an=0 s=0 for i in range(c): s+=p[i] an+=p[i]*(n-s) print(an) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is having one array of N natural numbers(numbers may be repeated). i.e. All natural numbers must be less than N. Chef wants to rearrange the array and try to place a natural number on its index of the array, i.e array[i]=i. If multiple natural numbers are found for given index place one natural number to its index and ignore others.i.e. arr[i]=i and multiple i found in array ignore all remaining i's If any index in the array is empty place 0 at that place. i.e. if for arr[i], i is not present do arr[i]=0. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains two lines of input. - First-line has $N$ denoting the size of an array. - Second-line has $N$ space-separated natural numbers. -----Output:----- For each test case, output in a single line with the new rearranged array. -----Constraints----- - $1 \leq T \leq 10^3$ - $2 \leq N \leq 10^3$ - $arr[i] \leq N-1$ -----Sample Input:----- 2 2 1 1 4 1 1 2 1 -----Sample Output:----- 0 1 0 1 2 0 -----EXPLANATION:----- For 1) $1$ occurs twice in the array hence print 0 at 0th index and 1 at 1st index For 2) $1$ occurs thrice and 2 once in the array hence print 0 at 0th index and 1 at 1st index, 2 at 2nd index and 0 at 3rd index. 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()) arr=list(map(int,input().split())) d=set() for i in arr: d.add(i) for i in range(n): if i in d: print(i,end=" ") else: print(0,end=" ") print() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This problem is different from the easy version. In this version Ujan makes at most $2n$ swaps. In addition, $k \le 1000, n \le 50$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two distinct strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $2n$ times: he takes two positions $i$ and $j$ ($1 \le i,j \le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$. Ujan's goal is to make the strings $s$ and $t$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $2n$ or shorter is suitable. -----Input----- The first line contains a single integer $k$ ($1 \leq k \leq 1000$), the number of test cases. For each of the test cases, the first line contains a single integer $n$ ($2 \leq n \leq 50$), the length of the strings $s$ and $t$. Each of the next two lines contains the strings $s$ and $t$, each having length exactly $n$. The strings consist only of lowercase English letters. It is guaranteed that strings are different. -----Output----- For each test case, output "Yes" if Ujan can make the two strings equal with at most $2n$ operations and "No" otherwise. You can print each letter in any case (upper or lower). In the case of "Yes" print $m$ ($1 \le m \le 2n$) on the next line, where $m$ is the number of swap operations to make the strings equal. Then print $m$ lines, each line should contain two integers $i, j$ ($1 \le i, j \le n$) meaning that Ujan swaps $s_i$ and $t_j$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $2n$ is suitable. -----Example----- Input 4 5 souse houhe 3 cat dog 2 aa az 3 abc bca Output Yes 1 1 4 No No Yes 3 1 2 3 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 for _ in range(int(input())): n = int(input()) s = input() t = input() d = {} for i in range(ord('a'), ord('z') + 1): d[chr(i)] = 0 for cs in s: d[cs] += 1 for ct in t: d[ct] += 1 ok = True for e in d: if d[e] % 2 == 1: ok = False if not ok: print("No") else: print("Yes") changes = [] s, t = list(s), list(t) for i in range(n-1): if s[i] != t[i]: r = (0, -1) for j in range(i+1, n): if s[j] == t[i]: r = (j, 0) for j in range(i+1, n): if t[j] == t[i]: r = (j, 1) if r[1] == 0: changes += [(r[0], i+1), (i, i+1)] s[r[0]], t[i+1] = t[i+1], s[r[0]] s[i], t[i+1] = t[i+1], s[i] elif r[1] == 1: changes += [(i, r[0])] s[i], t[r[0]] = t[r[0]], s[i] print(len(changes)) for change in changes: x, y = change print(x+1, y+1) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Koa the Koala has a binary string $s$ of length $n$. Koa can perform no more than $n-1$ (possibly zero) operations of the following form: In one operation Koa selects positions $i$ and $i+1$ for some $i$ with $1 \le i < |s|$ and sets $s_i$ to $max(s_i, s_{i+1})$. Then Koa deletes position $i+1$ from $s$ (after the removal, the remaining parts are concatenated). Note that after every operation the length of $s$ decreases by $1$. How many different binary strings can Koa obtain by doing no more than $n-1$ (possibly zero) operations modulo $10^9+7$ ($1000000007$)? -----Input----- The only line of input contains binary string $s$ ($1 \le |s| \le 10^6$). For all $i$ ($1 \le i \le |s|$) $s_i = 0$ or $s_i = 1$. -----Output----- On a single line print the answer to the problem modulo $10^9+7$ ($1000000007$). -----Examples----- Input 000 Output 3 Input 0101 Output 6 Input 0001111 Output 16 Input 00101100011100 Output 477 -----Note----- In the first sample Koa can obtain binary strings: $0$, $00$ and $000$. In the second sample Koa can obtain binary strings: $1$, $01$, $11$, $011$, $101$ and $0101$. For example: to obtain $01$ from $0101$ Koa can operate as follows: $0101 \rightarrow 0(10)1 \rightarrow 011 \rightarrow 0(11) \rightarrow 01$. to obtain $11$ from $0101$ Koa can operate as follows: $0101 \rightarrow (01)01 \rightarrow 101 \rightarrow 1(01) \rightarrow 11$. Parentheses denote the two positions Koa selected in each operation. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline MOD = 10**9+7 S = readline().strip().split('1') if len(S) == 1: print(len(S[0])) else: S = [len(s)+1 for s in S] ans = S[0]*S[-1] S = S[1:-1] dp = [0]*(max(S)+2) dp[0] = 1 for ai in S: res = 0 rz = 0 for i in range(ai+1): res = (res + dp[i])%MOD rz = (rz + (ai-i)*dp[i])%MOD dp[i] = 0 dp[0] = rz dp[ai] = res aaa = 0 for d in dp: aaa = (aaa+d)%MOD print(aaa*ans%MOD) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You are in charge of controlling a dam. The dam can store at most L liters of water. Initially, the dam is empty. Some amount of water flows into the dam every morning, and any amount of water may be discharged every night, but this amount needs to be set so that no water overflows the dam the next morning. It is known that v_i liters of water at t_i degrees Celsius will flow into the dam on the morning of the i-th day. You are wondering about the maximum possible temperature of water in the dam at noon of each day, under the condition that there needs to be exactly L liters of water in the dam at that time. For each i, find the maximum possible temperature of water in the dam at noon of the i-th day. Here, consider each maximization separately, that is, the amount of water discharged for the maximization of the temperature on the i-th day, may be different from the amount of water discharged for the maximization of the temperature on the j-th day (j≠i). Also, assume that the temperature of water is not affected by anything but new water that flows into the dam. That is, when V_1 liters of water at T_1 degrees Celsius and V_2 liters of water at T_2 degrees Celsius are mixed together, they will become V_1+V_2 liters of water at \frac{T_1*V_1+T_2*V_2}{V_1+V_2} degrees Celsius, and the volume and temperature of water are not affected by any other factors. -----Constraints----- - 1≤ N ≤ 5*10^5 - 1≤ L ≤ 10^9 - 0≤ t_i ≤ 10^9(1≤i≤N) - 1≤ v_i ≤ L(1≤i≤N) - v_1 = L - L, each t_i and v_i are integers. -----Input----- Input is given from Standard Input in the following format: N L t_1 v_1 t_2 v_2 : t_N v_N -----Output----- Print N lines. The i-th line should contain the maximum temperature such that it is possible to store L liters of water at that temperature in the dam at noon of the i-th day. Each of these values is accepted if the absolute or relative error is at most 10^{-6}. -----Sample Input----- 3 10 10 10 20 5 4 3 -----Sample Output----- 10.0000000 15.0000000 13.2000000 - On the first day, the temperature of water in the dam is always 10 degrees: the temperature of the only water that flows into the dam on the first day. - 10 liters of water at 15 degrees of Celsius can be stored on the second day, by discharging 5 liters of water on the night of the first day, and mix the remaining water with the water that flows into the dam on the second day. - 10 liters of water at 13.2 degrees of Celsius can be stored on the third day, by discharging 8 liters of water on the night of the first day, and mix the remaining water with the water that flows into the dam on the second and third days. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # なんだか釈然としていないが解説の通りに from collections import deque import sys def MI(): return list(map(int, sys.stdin.readline().split())) class water: def __init__(self, t, v): self.v = v self.tv = v * t def __le__(self, other): return self.v * other.tv - self.tv * other.v >= 0 def __isub__(self, other): t = self.tv / self.v self.v -= other self.tv = t * self.v return self def __iadd__(self, other): self.v+=other.v self.tv+=other.tv return self def main(): n, l = MI() dam = deque() t, v = MI() print(t) dam.append(water(t, v)) # stvはtvの合計(vがlのときのvt) stv = t * v for _ in range(n-1): t, v = MI() # 朝に水をもらう dam.appendleft(water(t, v)) over = v stv += t * v # 増えた分の水を古い方から捨てる # ベクトルごと削除できるもの while dam[-1].v <= over: w = dam.pop() over -= w.v stv -= w.tv # 最後のはみ出しているベクトルは縮める stv -= dam[-1].tv # 一度合計から取り出して dam[-1] -= over # 縮めて stv += dam[-1].tv # 元に戻す # その日の水温を出力 print((stv / l)) # グラフの左側が凹んでいたらベクトルを合成して凸に直す while len(dam)>1 and dam[0] <= dam[1]: w = dam.popleft() dam[0] += w main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs. Visitors are more likely to buy a pair of shovels if their total cost ends with several 9s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs 12345 and 37454, their total cost is 49799, it ends with two nines. You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 10^9) — the number of shovels in Polycarp's shop. -----Output----- Print the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Note that it is possible that the largest number of 9s at the end is 0, then you should count all such ways. It is guaranteed that for every n ≤ 10^9 the answer doesn't exceed 2·10^9. -----Examples----- Input 7 Output 3 Input 14 Output 9 Input 50 Output 1 -----Note----- In the first example the maximum possible number of nines at the end is one. Polycarp cah choose the following pairs of shovels for that purpose: 2 and 7; 3 and 6; 4 and 5. In the second example the maximum number of nines at the end of total cost of two shovels is one. The following pairs of shovels suit Polycarp: 1 and 8; 2 and 7; 3 and 6; 4 and 5; 5 and 14; 6 and 13; 7 and 12; 8 and 11; 9 and 10. In the third example it is necessary to choose shovels 49 and 50, because the sum of their cost is 99, that means that the total number of nines is equal to two, which is maximum possible for n = 50. 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 as cin from sys import stdout as cout def main(): n = int(cin.readline()) o = 0 for x in range(9, 0, -1): if 10 ** x // 2 <= n: ##print(x) for i in range(9): q = 10 ** x * (i + 1) // 2 - 1 if q <= n: o += min(q, n - q) print(o) return print(n * (n - 1) // 2) main() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are total $N$ cars in a sequence with $ith$ car being assigned with an alphabet equivalent to the $ith$ alphabet of string $S$ . Chef has been assigned a task to calculate the total number of cars with alphabet having a unique even value in the given range X to Y (both inclusive) . The value of an alphabet is simply its position in alphabetical order e.g.: a=1, b=2, c=3… The chef will be given $Q$ such tasks having varying values of $X$ and $Y$ Note: string $S$ contains only lowercase alphabets -----Input----- First line of input contains a string $S$ of length $N$. Second line contains an integer denoting no. of queries $Q$. Next q lines contain two integers denoting values of $X$ and $Y$. -----Output----- For each query print a single integer denoting total number of cars with alphabet having a unique even value in the given range $X$ to $Y$. -----Constraints----- - $1 \leq n \leq 10^5$ - $1 \leq q \leq 10^5$ -----Example Input----- bbccdd 5 1 2 3 4 5 6 1 6 2 5 -----Example Output----- 1 0 1 2 2 -----Explanation:----- Example case 1: Query 1: range 1 to 2 contains the substring $"bb"$ where each character has a value of 2. Since we will only be considering unique even values, the output will be 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python arr = list(input()) n = len(arr) ans = list() #for i in arr: #ans.append(ord(i)-96) li = ['b','d','f','h','j','l','n','p','r','t','v','x','z'] s = set(arr) temp = s.intersection(li) for _ in range(int(input())): x,y = list(map(int,input().split())) li = list(temp) #s = set() c=0 for i in range(x-1,y): if arr[i] in li: c+=1 li.remove(arr[i]) if len(li)==0: break print(c) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Nature photographing may be fun for tourists, but it is one of the most complicated things for photographers. To capture all the facets of a bird, you might need more than one cameras. You recently encountered such a situation. There are $n$ photographers, so there are $n$ cameras in a line on the x-axis. All the cameras are at distinct coordinates. You want to pair up these cameras ($n$ is even) in such a way that the sum of angles subtended on the bird by the pair of cameras is maximized. Formally, let A, B be two cameras, and let P be the bird to be captured by these two cameras. The angle will APB. Note: All angles are in radians. -----Input----- - The first line of the input contains an integer $T$ denoting the number of test cases. The description of the test cases follows. - The first line of each test case contains an integer $n$. - The second line of each test case contains $n$ space-separated integers denoting the $x_i$ coordinates of the cameras. - The third line of each test case contains two space-separated integers $P, Q$ denoting the x and y coordinates of the bird respectively. -----Output----- For each test case, output your answer in a single line. Your answer would be considered correct if its absolute error is less than or equal to 1e-6 of the actual answer. -----Constraints----- - $1 \le T \le 10$ - $2 \le n \leq 100$ - $1 \le x_i \leq 300$ - $0 \le P \leq 300$ - $1 \le Q \leq 300$ -----Example Input----- 2 2 0 1 0 1 2 0 1 100 1 -----Example Output----- 0.785398163397 0.000100999899 -----Explanation----- Note: $1 \leq x_i$ is not being satisfied by the sample input, but will be satisfied in the actual test data. Testcase 1: There are only 2 cameras, so they have to paired up with each other. And the angle subtended by then is 45 degrees. Converting this to radians gives the output. 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 * from collections import * import sys input=sys.stdin.readline t=int(input()) while(t): t-=1 n=int(input()) a=list(map(int,input().split())) p,q=map(int,input().split()) s=0 a.sort() for i in range(n//2): x=a[i] x1=a[n-i-1] if(x==p or x1==p): s1=abs(x-x1) s2=q s+=abs(atan2(s1,s2)) elif(x<p and x1>p): s1=abs(p-x) ex=atan2(s1,q) s1=abs(p-x1) ex1=atan2(s1,q) ex+=ex1 s+=abs(ex) else: if(p<x): s1=abs(p-x) ex=atan2(s1,q) s1=abs(p-x1) ex1=atan2(s1,q) ex=ex1-ex s+=abs(ex) else: s1=abs(p-x) ex=atan2(s1,q) s1=abs(p-x1) ex1=atan2(s1,q) ex=ex-ex1 s+=abs(ex) print(s) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Today is the planned day tor Thik and Ayvak's wedding. Kark is infatuated with Ayvak. He offers to play a game with Thik. Whosoever wins, will get to marry Ayvak. Ayvak, who values games of chance over all the other things in life, agrees to this. Kark sets up an N by M grid (N rows, M columns), labelled from left to right and top to bottom consecutively with numbers from 1 to M*N, with 1 at the top left corner and M*N at the bottom right corner. For example, a labelled 3 by 6 grid looks as follows: Kark has already painted K unit squares of the grid with a heart each. Next, Thik randomly picks a rectangle with sides on the grid lines, and having a positive area, with each valid rectangle having an equal probability of being chosen. Three distinct possibilities for Thik's rectangle in the 3 by 6 grid are shown below: The nine different rectangles in a 2 by 2 grid are shown below: If Thik's rectangle contains at least half of the hearts, Thik gets to marry Ayvak. Otherwise, Kark will marry Ayvak. Kark wants to know whether or not he has an advantage here, so he wants to know the expected value of the number of hearts a randomly chosen rectangle will cover. I'm sure that you have a good heart, so please, cover this job for him. -----Input----- The first line of input contains one integer T, the number of test cases. For each test case, the first line contains 3 space-separated integers N, M, K, as described in the problem statement. The next line contains K space-separated integers, each a single number from 1 to M*N, representing a square that is painted with a heart. It is guaranteed that all K integers are distinct. -----Output----- Output T lines, each containing a single real number, containing the expected number of hearts that a randomly chosen rectangle will contain. The answer will be considered correct if its relative or absolute error does not exceed 10-6. -----Constraints----- - 1 ≤ T ≤ 5 - 1 ≤ N, M ≤ 107 - 1 ≤ K ≤ 105 - Each of the K integers representing a heart are between 1 and N*M, inclusive. All K integers are distinct. -----Subtasks-----Subtask 1 (15 points) : - 1 ≤ N, M ≤ 10 - 1 ≤ K ≤ N * M Subtask 2 (85 points) : no additional constraints -----Example----- Input: 1 2 2 2 1 2 Output: 0.8888888888888888 -----Explanation----- There are a total of 9 possible rectangles Thik could draw, shown in the figure above, and grid squares 1 and 2 are painted with a heart. The top row of possible selections (shown in the figure) contain 1, 0, 1, 2, and 2 hearts (from left to right), and the bottom row of possible selections (in the figure) contain 1, 0, 1, and 0 hearts. Therefore, 3/9 of the time 0 hearts are contained in the rectangle, 4/9 of the times 1 heart is contained in the rectangle, and 2/9 of the time 2 hearts are contained in the rectangle. The expected value is then 0 * 3/9 + 1 * 4/9 + 2 * 2/9 = 8/9. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here for i in range(int(input())): n,m,k=map(int,input().split()) l,ans = list(map(int,input().split())),0 for i in l: r=i//m + 1;c=i%m if(c==0):c=m;r-=1 ans+=r*(n+1-r)*c*(m+1-c) ans/=((n+1)*(m+1)*n*m)//4 print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: ----- RANJANA QUIZ ----- Prof. Ranjana decided to conduct a quiz in her class. She divided all the students of her class into groups of three. Consider that no student was left out after the division. She gave different sets of questions to every group. A set is said to be unique if there is no other team that received the same number of maths, science and english questions. In every set, maximum questions for each group were related to maths, then science, and the least number of questions were related to English. Total number of questions given to each team can be different. After the test, the CR of the class asked every team to report the number of questions they got on each subject. The CR wants to know the number of unique sets of questions that were given to the teams, the problem is that all the students have just submitted the number of questions of each subject but in no particular order. Help the CR to find the number of unique sets -----Input Format----- Line 1 contains the number of teams ‘n’. In the next n lines, each line contains three space separated integers,i.e, the number of questions of each subject(in no particular order). employee -----Output----- Print the number of unique sets -----Example Text Case----- Input: 5 6 5 4 2 3 7 4 6 5 7 2 3 5 3 1 Output: 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n=int(input()) l=[] count=0 while n: n-=1 a,b,c=sorted(map(int,input().split())) if (a,b,c) in l: count-=1 else: l.append((a,b,c)) count+=1 print(count) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base b_{x} and a number Y represented in base b_{y}. Compare those two numbers. -----Input----- The first line of the input contains two space-separated integers n and b_{x} (1 ≤ n ≤ 10, 2 ≤ b_{x} ≤ 40), where n is the number of digits in the b_{x}-based representation of X. The second line contains n space-separated integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} < b_{x}) — the digits of X. They are given in the order from the most significant digit to the least significant one. The following two lines describe Y in the same way: the third line contains two space-separated integers m and b_{y} (1 ≤ m ≤ 10, 2 ≤ b_{y} ≤ 40, b_{x} ≠ b_{y}), where m is the number of digits in the b_{y}-based representation of Y, and the fourth line contains m space-separated integers y_1, y_2, ..., y_{m} (0 ≤ y_{i} < b_{y}) — the digits of Y. There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system. -----Output----- Output a single character (quotes for clarity): '<' if X < Y '>' if X > Y '=' if X = Y -----Examples----- Input 6 2 1 0 1 1 1 1 2 10 4 7 Output = Input 3 3 1 0 2 2 5 2 4 Output < Input 7 16 15 15 4 0 0 7 10 7 9 4 8 0 3 1 5 0 Output > -----Note----- In the first sample, X = 101111_2 = 47_10 = Y. In the second sample, X = 102_3 = 21_5 and Y = 24_5 = 112_3, thus X < Y. In the third sample, $X = FF 4007 A_{16}$ and Y = 4803150_9. We may notice that X starts with much larger digits and b_{x} is much larger than b_{y}, so X is clearly larger than Y. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, bx = list(map(int, input().split())) x1 = list(map(int, input().split())) x = 0 for i in range(n): x *= bx x += x1[i] n, by = list(map(int, input().split())) y1 = list(map(int, input().split())) y = 0 for i in range(n): y *= by y += y1[i] if x == y: print('=') elif x < y: print('<') else: print('>') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef and his friends are playing the game AMONG US. They all have chosen their names as numbers. There are N people in Chef’s group including him, and each swears that he is not the imposter. However, it turns out there were N+1 people in the game. Now all that Chef needs to know is the name of the imposter, which is a number. Also remember that numbers can be duplicate. Can you help out Chef in finding the imposter? Input : First line contains the value of N. Second line contains the N numbers that Chef’s friends used as their names. Third line contains the N+1 numbers that people in the game have used as their names. Output : Print the extra number in new line. Constraints : 1 ≤ Numbers used as names ≤ 1,000 1 ≤ N ≤ 1,000,000 Sample Input : 3 4 2 5 4 2 3 5 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 try: n=int(input()) x=[*list(map(int, input().split()))] y=[*list(map(int, input().split()))] for i in y: d=x.count(i)-y.count(i) if d!=0: print(i) break except: pass ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has an old machine if the chef enters any natural number, the machine will display 1, 2, …n, n-1, n-2, n-3,…1 series and in next line prints sum of cubes of each number in the series. Chef wants to create a computer program which can replicate the functionality of the machine. Help the chef to code. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, $N$. -----Output:----- For each test case, output in a single line answer. -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq N \leq 50$ -----Sample Input:----- 2 1 3 -----Sample Output:----- 1 45 -----EXPLANATION:----- For 2) series will be 1, 2, 3, 2, 1 and the sum will be = 1 + 8 + 27 + 8+ 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) while(t!=0): t=t-1 n=int(input()) ans=0 for i in range(1,n+1,1): sum=0; for j in range(1,i+1,1): sum=sum+j s=sum-i sum=sum+s if(i!=n): ans=ans+2*sum*i else: ans=ans+sum*i print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef wants to make a feast. In order to do that, he needs a lot of different ingredients. Each ingredient has a certain tastiness; the tastiness of each ingredient may be any positive integer. Initially, for each tastiness between $K$ and $K+N-1$ (inclusive), Chef has an infinite supply of ingredients with this tastiness. The ingredients have a special property: any two of them can be mixed to create a new ingredient. If the original ingredients had tastiness $x$ and $y$ (possibly $x = y$), the new ingredient has tastiness $x+y$. The ingredients created this way may be used to mix other ingredients as well. Chef is free to mix ingredients in any way he chooses any number of times. Let's call a tastiness $v$ ($v > 0$) unreachable if there is no way to obtain an ingredient with tastiness $v$; otherwise, tastiness $v$ is reachable. Chef wants to make ingredients with all reachable values of tastiness and he would like to know the number of unreachable values. Help him solve this problem. Since the answer may be large, compute it modulo $1,000,000,007$ ($10^9+7$). Note that there is an infinite number of reachable values of tastiness, but it can be proven that the number of unreachable values is always finite for $N \ge 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 two space-separated integers $N$ and $K$. -----Output----- For each test case, print a single line containing one integer — the number of unreachable values of tastiness, modulo $1,000,000,007$. -----Constraints----- - $1 \le T \le 10^5$ - $2 \le N \le 10^{18}$ - $1 \le K \le 10^{18}$ -----Subtasks----- Subtask #1 (20 points): $N = 2$ Subtask #2 (80 points): original constraints -----Example Input----- 2 2 1 3 3 -----Example Output----- 0 2 -----Explanation----- Example case 1: It is possible to obtain ingredients with all values of tastiness. Example case 2: Ingredients with tastiness $1$ and $2$ cannot be made. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python __author__ = 'Prateek' MOD = int(10**9+7) def test(): n,k=list(map(int,input().split())) l = k d =n-1 ans = l-1 ans = ans%MOD a = k-n term = (d+a)//d ll = (a%MOD - (((term-1)%MOD)*(d%MOD))%MOD)%MOD if ll < 0: ll = (ll +MOD)%MOD m = ((term%MOD)*((a%MOD+ll%MOD)%MOD))%MOD m = (m*pow(2,MOD-2,MOD))%MOD ans += m ans = ans%MOD print(ans) if __author__ == 'Prateek': t = int(input()) for _ in range(t): test() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $y$ Koa selects must be strictly greater alphabetically than $x$ (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings $A$ and $B$ of the same length $n$ ($|A|=|B|=n$) consisting of the first $20$ lowercase English alphabet letters (ie. from a to t). In one move Koa: selects some subset of positions $p_1, p_2, \ldots, p_k$ ($k \ge 1; 1 \le p_i \le n; p_i \neq p_j$ if $i \neq j$) of $A$ such that $A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$ (ie. all letters on this positions are equal to some letter $x$). selects a letter $y$ (from the first $20$ lowercase letters in English alphabet) such that $y>x$ (ie. letter $y$ is strictly greater alphabetically than $x$). sets each letter in positions $p_1, p_2, \ldots, p_k$ to letter $y$. More formally: for each $i$ ($1 \le i \le k$) Koa sets $A_{p_i} = y$. Note that you can only modify letters in string $A$. Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($A = B$) or to determine that there is no way to make them equal. Help her! -----Input----- Each test contains multiple test cases. The first line contains $t$ ($1 \le t \le 10$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $n$ ($1 \le n \le 10^5$) — the length of strings $A$ and $B$. The second line of each test case contains string $A$ ($|A|=n$). The third line of each test case contains string $B$ ($|B|=n$). Both strings consists of the first $20$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($A = B$) or $-1$ if there is no way to make them equal. -----Example----- Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 -----Note----- In the $1$-st test case Koa: selects positions $1$ and $2$ and sets $A_1 = A_2 = $ b ($\color{red}{aa}b \rightarrow \color{blue}{bb}b$). selects positions $2$ and $3$ and sets $A_2 = A_3 = $ c ($b\color{red}{bb} \rightarrow b\color{blue}{cc}$). In the $2$-nd test case Koa has no way to make string $A$ equal $B$. In the $3$-rd test case Koa: selects position $1$ and sets $A_1 = $ t ($\color{red}{a}bc \rightarrow \color{blue}{t}bc$). selects position $2$ and sets $A_2 = $ s ($t\color{red}{b}c \rightarrow t\color{blue}{s}c$). selects position $3$ and sets $A_3 = $ r ($ts\color{red}{c} \rightarrow ts\color{blue}{r}$). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = lambda: sys.stdin.readline().rstrip() T = int(input()) for _ in range(T): N = int(input()) A = [ord(a) - 97 for a in input()] B = [ord(a) - 97 for a in input()] X = [[0] * 20 for _ in range(20)] for a, b in zip(A, B): X[a][b] = 1 if a > b: print(-1) break else: ans = 0 for i in range(20): for j in range(i+1, 20): if X[i][j]: ans += 1 for jj in range(j+1, 20): if X[i][jj]: X[j][jj] = 1 break print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Snuke loves constructing integer sequences. There are N piles of stones, numbered 1 through N. The pile numbered i consists of a_i stones. Snuke will construct an integer sequence s of length Σa_i, as follows: - Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s. - Select a pile with one or more stones remaining, and remove a stone from that pile. - If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process. We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence? -----Constraints----- - 1 ≤ N ≤ 10^{5} - 1 ≤ a_i ≤ 10^{9} -----Input----- The input is given from Standard Input in the following format: N a_1 a_2 ... a_{N} -----Output----- Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed. -----Sample Input----- 2 1 2 -----Sample Output----- 2 1 The lexicographically smallest sequence is constructed as follows: - Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2. - Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2. - Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1. The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once. 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()) a = [int(i) for i in input().split()] b = defaultdict(lambda : [float('inf'), 0]) for i in range(N) : b[a[i]][0] = min(b[a[i]][0], i) b[a[i]][1] += 1 # [value, first_appearance, count] c = [(0, 0, 0)] for k, v in b.items() : c.append((k, v[0], v[1])) c.sort() ret = [0] * N pre_v, pre_i, pre_c = c.pop() while c : cur_v, cur_i, cur_c = c.pop() ret[pre_i] += (pre_v - cur_v) * pre_c cur_c += pre_c pre_v, pre_i, pre_c = cur_v, min(pre_i, cur_i), cur_c for r in ret : print(r) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Snuke has decided to play a game, where the player runs a railway company. There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train. For example, if d = 3, the train stops at station 0, 3, 6, 9, and so forth. There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind of souvenirs can be purchased when the train stops at one of the following stations: stations l_i, l_i+1, l_i+2, ..., r_i. There are M values of d, the interval between two stops, for trains on Snuke Line: 1, 2, 3, ..., M. For each of these M values, find the number of the kinds of souvenirs that can be purchased if one takes a train with that value of d at station 0. Here, assume that it is not allowed to change trains. -----Constraints----- - 1 ≦ N ≦ 3 × 10^{5} - 1 ≦ M ≦ 10^{5} - 1 ≦ l_i ≦ r_i ≦ M -----Input----- The input is given from Standard Input in the following format: N M l_1 r_1 : l_{N} r_{N} -----Output----- Print the answer in M lines. The i-th line should contain the maximum number of the kinds of souvenirs that can be purchased if one takes a train stopping every i-th station. -----Sample Input----- 3 3 1 2 2 3 3 3 -----Sample Output----- 3 2 2 - If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3. - If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2. - If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline def main(): n, m = map(int, input().split()) LR = [list(map(int, input().split())) for _ in range(n)] BIT = [0]*(m+2) def add(i, a): while i <= m+1: BIT[i] += a i += i&(-i) def bit_sum(i): res = 0 while i > 0: res += BIT[i] i -= i&(-i) return res for l, r in LR: add(l, 1) add(r+1, -1) S = sorted([(r-l+1, l, r) for l, r in LR]) cnt = 0 L = [] for i in range(m, 0, -1): while S and S[-1][0] == i: c, l, r = S.pop() cnt += 1 add(l, -1) add(r+1, 1) res = cnt for j in range(0, m+1, i): res += bit_sum(j) L.append(res) print(*L[::-1], sep="\n") def __starting_point(): main() __starting_point() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It's Diwali time and you are on a tour of Codepur, a city consisting of buildings of equal length and breadth because they were designed by a computer architect with a bit of OCD. The ruling party of Codepur wants to have a blockbuster Diwali celebration but lack enough funds and decided to open a donation channel called Codepur Cares Fund (CCF). So they decided to run a survey. Each building eihter has permanent donors, whose impact value is represented as a positive integer, or potential donors, whose impact value is represented by negative integers. Overwhelmed by the response, and sticking to their resource optimized philosophy, they decided to hire you to determine the contiguous buildings which are allowed to donate to CCF with the following rule: The contiguous buildings / areas with the maximum sum impact shall be allowed for donating to Codepur Cares Fund (CCF). Help them out to get a stunning Diwali bonus and rest of your trip sponsered! -----Input:----- The first line consists of two tab spaced integers m and n, indicating number of rows and columns respectively in the Codepur's city plan (which is a 2-D Matrix). The next $m$ lines consist of $n$ tab spaced integers $ti$ indicating rows in the matrix. -----Output:----- Print the bulidings (represented by their donors numbers) which are eligible to donate to CCF (i.e, have the largest sum contiguously) as a 2-D matrix with the elements being tab-spaced. -----Constraints----- - $0 \leq m,n \leq 10^{15}$ - $-10^{15} \leq ti \leq 10^5$ -----Sample Input:----- 6 5 0 -2 -7 0 -1 9 2 -6 2 0 -4 1 -4 1 0 -1 8 0 -2 1 -10 1 1 -5 6 -15 -1 1 5 -4 -----Sample Output:----- 9 2 -4 1 -1 8 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 kadane(arr, start, finish, n): Sum = 0 maxSum = float('-inf') i = None finish[0] = -1 local_start = 0 for i in range(n): Sum += arr[i] if Sum < 0: Sum = 0 local_start = i + 1 elif Sum > maxSum: maxSum = Sum start[0] = local_start finish[0] = i if finish[0] != -1: return maxSum maxSum = arr[0] start[0] = finish[0] = 0 for i in range(1, n): if arr[i] > maxSum: maxSum = arr[i] start[0] = finish[0] = i return maxSum def findMaxSum(M): nonlocal ROW, COL maxSum, finalLeft = float('-inf'), None finalRight, finalTop, finalBottom = None, None, None left, right, i = None, None, None temp = [None] * ROW Sum = 0 start = [0] finish = [0] for left in range(COL): temp = [0] * ROW for right in range(left, COL): for i in range(ROW): temp[i] += M[i][right] Sum = kadane(temp, start, finish, ROW) if Sum > maxSum: maxSum = Sum finalLeft = left finalRight = right finalTop = start[0] finalBottom = finish[0] for i in range(finalTop,finalBottom+1): print(*M[i][finalLeft:finalRight+1]) ROW,COL = ip() M = [ip() for i in range(ROW)] findMaxSum(M) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef bought an electronic board and pen. He wants to use them to record his clients' signatures. The board is a grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$) of pixels. Initially, all pixels are white. A client uses the electronic pen to sign on the board; whenever the pen touches a pixel, this pixel becomes black. Note that a signature may be non-continuous (a client may lift the pen while signing). Chef stores a typical signature of his current client as a matrix of characters $A_{i, j}$, where for each valid $i$ and $j$, $A_{i, j}$ is either '1' (if the cell in the $i$-th row and $j$-th column is black) or '0' (if this cell is white). The client just signed on the board; this signature is stored in the same form as a matrix $B_{i, j}$. Chef wants to know how close this signature is to this client's typical signature. Two signatures are considered the same if it is possible to choose (possibly negative) integers $dr$ and $dc$ such that for each $1 \le i \le N$ and $1 \le j \le M$, $A_{i, j} = B_{i + dr, j + dc}$. Here, if $B_{i + dr, j + dc}$ does not correspond to a valid cell, it is considered to be '0'. To compare the signatures, the colours of zero or more cells must be flipped in such a way that the signatures become the same (each flipped cell may be in any matrix). The error in the client's current signature is the minimum number of cells whose colours must be flipped. Find the error in the signature. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $M$. - $N$ lines follow. For each valid $i$, the $i$-th of these lines contains a string with length $M$ describing the $i$-th row of the matrix $A$. - $N$ more lines follow. For each valid $i$, the $i$-th of these lines contains a string with length $M$ describing the $i$-th row of the matrix $B$. -----Output----- For each test case, print a single line containing one integer — the error in the current signature. -----Constraints----- - $1 \le T \le 50$ - $2 \le N, M \le 25$ -----Example Input----- 5 3 3 100 010 000 000 010 001 4 4 0000 0110 0000 0011 1100 0000 1100 0000 3 3 100 000 001 000 010 000 3 3 000 010 000 100 000 001 3 3 111 000 000 001 001 001 -----Example Output----- 0 2 1 0 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import numpy as np for _ in range(int(input())): ans = np.float('inf') n, m = (int(x) for x in input().split()) sig = np.zeros((n,m)) img = np.zeros((3*n,3*m)) for row in range(n): sig[row,:] = np.array([int(x) for x in input()]) for row in range(n): img[row+n,m:2*m] = np.array([int(x) for x in input()]) for i in range(2*n): for j in range(2*m): ans = min(ans, np.abs(np.sum(img[i:n+i, j:m+j] != sig))) print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form new pattern. Help the chef to code this pattern problem. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, one integer $K$. -----Output:----- For each testcase, output as pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 2 2 4 -----Sample Output:----- 2 12 012 12 2 4 34 234 1234 01234 1234 234 34 4 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import copy for _ in range(int(input())): k=int(input()) c=[] d=[] start=0 while True: c=[] for i in range(start): c.append(" ") for i in range(start,k+1): c.append(str(i)) start+=1 d.append(c) if start>k: break e=copy.copy(d[1:]) d.reverse() d=d+e ##print(d) for i in range(len(d)): print(''.join(d[i])) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Firdavs is living on planet F. There are $N$ cities (numbered $1$ through $N$) on this planet; let's denote the value of city $i$ by $v_i$. Firdavs can travel directly from each city to any other city. When he travels directly from city $x$ to city $y$, he needs to pay $f(x, y) = |v_y-v_x|+y-x$ coins (this number can be negative, in which case he receives $-f(x, y)$ coins). Let's define a simple path from city $x$ to city $y$ with length $k \ge 1$ as a sequence of cities $a_1, a_2, \ldots, a_k$ such that all cities in this sequence are different, $a_1 = x$ and $a_k = y$. The cost of such a path is $\sum_{i=1}^{k-1} f(a_i, a_{i+1})$. You need to answer some queries for Firdavs. In each query, you are given two cities $x$ and $y$, and you need to find the minimum cost of a simple path from city $x$ to city $y$. Then, you need to find the length of the longest simple path from $x$ to $y$ with this cost. -----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 $v_1, v_2, \ldots, v_N$. - The following $Q$ lines describe queries. Each of these lines contains two space-separated integers $x$ and $y$. -----Output----- For each query, print a single line containing two space-separated integers ― the minimum cost and the maximum length. -----Constraints----- - $1 \le T \le 100$ - $1 \le N, Q \le 2 \cdot 10^5$ - $0 \le v_i \le 10^9$ for each valid $i$ - $1 \le x, y \le N$ - the sum of $N$ in all test cases does not exceed $5 \cdot 10^5$ - the sum of $Q$ in all test cases does not exceed $5 \cdot 10^5$ -----Subtasks----- Subtask #1 (30 points): - $1 \le N, Q \le 1,000$ - $v_1 < v_2 < \ldots < v_N$ - the sum of $N$ in all test cases does not exceed $5,000$ - the sum of $Q$ in all test cases does not exceed $5,000$ Subtask #2 (70 points): original constraints -----Example Input----- 2 4 2 4 2 5 7 2 3 3 4 2 1 1 1 2 1 -----Example Output----- 4 3 3 2 -1 2 -----Explanation----- Example case 1: For the first query, there are two paths with cost $4$ from city $2$ to city $3$: - $2 \rightarrow 1 \rightarrow 3$: cost $(|4-2|+1-2)+(|5-4|+3-1) = 4$, length $3$ - $2 \rightarrow 3$: cost $|5-2|+3-2 = 4$, length $2$ All other paths have greater costs, so the minimum cost is $4$. Among these two paths, we want the one with greater length, which is $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 import bisect for _ in range(int(input())): N,Q=list(map(int,input().strip().split(' '))) V=list(map(int,input().strip().split(' '))) VV=sorted(V) for ___ in range(Q): x,y=list(map(int,input().strip().split(' '))) x-=1 y-=1 ans1=abs(V[x]-V[y])+(y-x) post1=bisect.bisect_left(VV,min(V[x],V[y])) post2=bisect.bisect_right(VV,max(V[x],V[y])) ans2=post2-post1 print(ans1,ans2) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j. Snuke can repeatedly perform the following two kinds of operations in any order to move all the robots simultaneously: - Increment the coordinates of all the robots on the number line by 1. - Decrement the coordinates of all the robots on the number line by 1. Each robot will disappear from the number line when its position coincides with that of an exit, going through that exit. Snuke will continue performing operations until all the robots disappear. When all the robots disappear, how many combinations of exits can be used by the robots? Find the count modulo 10^9 + 7. Here, two combinations of exits are considered different when there is a robot that used different exits in those two combinations. -----Constraints----- - 1 \leq N, M \leq 10^5 - 1 \leq x_1 < x_2 < ... < x_N \leq 10^9 - 1 \leq y_1 < y_2 < ... < y_M \leq 10^9 - All given coordinates are integers. - All given coordinates are distinct. -----Input----- Input is given from Standard Input in the following format: N M x_1 x_2 ... x_N y_1 y_2 ... y_M -----Output----- Print the number of the combinations of exits that can be used by the robots when all the robots disappear, modulo 10^9 + 7. -----Sample Input----- 2 2 2 3 1 4 -----Sample Output----- 3 The i-th robot from the left will be called Robot i, and the j-th exit from the left will be called Exit j. There are three possible combinations of exits (the exit used by Robot 1, the exit used by Robot 2) as follows: - (Exit 1, Exit 1) - (Exit 1, Exit 2) - (Exit 2, Exit 2) The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from bisect import bisect from collections import defaultdict class Bit: def __init__(self, n, MOD): self.size = n self.tree = [0] * (n + 1) self.depth = n.bit_length() self.mod = MOD def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s % self.mod def add(self, i, x): while i <= self.size: self.tree[i] = (self.tree[i] + x) % self.mod i += i & -i def debug_print(self): for i in range(1, self.size + 1): j = (i & -i).bit_length() print((' ' * j, self.tree[i])) def lower_bound(self, x): sum_ = 0 pos = 0 for i in range(self.depth, -1, -1): k = pos + (1 << i) if k <= self.size and sum_ + self.tree[k] < x: sum_ += self.tree[k] pos += 1 << i return pos + 1, sum_ n, m = list(map(int, input().split())) xxx = list(map(int, input().split())) yyy = list(map(int, input().split())) ab = defaultdict(set) coordinates = set() for x in xxx: if x < yyy[0] or yyy[-1] < x: continue i = bisect(yyy, x) a = x - yyy[i - 1] b = yyy[i] - x ab[a].add(b) coordinates.add(b) # Bitのindexは1から始まるように作っているが、"0"を取れるようにするため、全体を1ずらす cor_dict = {b: i for i, b in enumerate(sorted(coordinates), start=2)} cdg = cor_dict.get MOD = 10 ** 9 + 7 bit = Bit(len(coordinates) + 1, MOD) bit.add(1, 1) for a in sorted(ab): bbb = sorted(map(cdg, ab[a]), reverse=True) for b in bbb: bit.add(b, bit.sum(b - 1)) print((bit.sum(bit.size))) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There are $N$ robots who work for $Y$ days and on each day they produce some toys .on some days a few robots are given rest. So depending on the availability of robots owner has made a time table which decides which robots will work on the particular day. Only contiguous robots must be selected as they can form a link of communication among themselves. Initially, all robots have the capacity of one toy. On each day capacity for the chosen robot is updated i.e capacity = capacity $+$$ ($minimum capacity of given range % $1000000007)$ . After calculating the minimum capacity of a given range, compute it as modulo 1000000007 ($10^9 + 7$). After $Y$ days find the minimum capacity of the $N$ robots and compute it as modulo 1000000007 ($10^9 + 7$). -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Next Line contains a single integer N. - Next Line contains a single integer Y. - Next $Y$ lines contains l and r range of chosen robots . -----Output:----- For each testcase, output in a single line answer , the minimum capacity of the $N$ robots after $Y$ days and compute it as modulo 1000000007 ($10^9 + 7$) . -----Constraints----- - $1 \leq T \leq 100$ - $100 \leq N \leq 10^4$ - $200 \leq Y \leq 1000$ - $0<=l , r<=N-1$ , $l<=r$ -----Sample Input:----- 1 5 4 0 3 1 2 4 4 0 4 -----Sample Output:----- 4 -----EXPLANATION:----- Initial capacity of the $5$ robots 1 1 1 1 1 Minimum in range [0,3] = 1 Update the capacity in the range [0,3] Now capacity becomes, Day 1 - 2 2 2 2 1 Similarly capacities changes for each day Day 2 - 2 4 4 2 1 Day 3 - 2 4 4 2 2 Day 4 - 4 6 6 4 4 so after 4 days minimum capacity is $4$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python MAX = 100005 tree = [0] * MAX; lazy = [0] * MAX; def updateRangeUtil(si, ss, se, us, ue, diff) : if (lazy[si] != 0) : tree[si] += lazy[si]; if (ss != se) : lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; lazy[si] = 0; if (ss > se or ss > ue or se < us) : return; if (ss >= us and se <= ue) : tree[si] += diff; if (ss != se) : lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; return; mid = (ss + se) // 2; updateRangeUtil(si * 2 + 1, ss,mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1,se, us, ue, diff); tree[si] = min(tree[si * 2 + 1],tree[si * 2 + 2]); def updateRange(n, us, ue, diff) : updateRangeUtil(0, 0, n - 1, us, ue, diff); def getSumUtil(ss, se, qs, qe, si) : if (lazy[si] != 0) : tree[si] += lazy[si]; if (ss != se) : lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; lazy[si] = 0; if (ss > se or ss > qe or se < qs) : return 10e9; if (ss >= qs and se <= qe) : return tree[si]; mid = (ss + se) // 2; return min(getSumUtil(ss, mid, qs, qe, 2 * si + 1),getSumUtil(mid + 1, se, qs, qe, 2 * si + 2)); def getSum(n, qs, qe) : if (qs < 0 or qe > n - 1 or qs > qe) : #print("Invalid Input", end = ""); return -1; return getSumUtil(0, n - 1, qs, qe, 0); def constructSTUtil(arr, ss, se, si) : if (ss > se) : return; if (ss == se) : tree[si] = arr[ss]; return; mid = (ss + se) // 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = min(tree[si * 2 + 1], tree[si * 2 + 2]); def constructST(arr, n) : constructSTUtil(arr, 0, n - 1, 0); # Driver code for _ in range(int(input())): tree = [0] * MAX; lazy = [0] * MAX; n=int(input()); y=int(input()); arr=[1]*n; constructST(arr, n); for xyz in range(y): l,r=list(map(int,input().split())); updateRange(n, l, r, getSum(n, l, r)%1000000007); print((getSum(n, 0, n-1)%1000000007)); ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers — the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5. Formally, Alyona wants to count the number of pairs of integers (x, y) such that 1 ≤ x ≤ n, 1 ≤ y ≤ m and $(x + y) \operatorname{mod} 5$ equals 0. As usual, Alyona has some troubles and asks you to help. -----Input----- The only line of the input contains two integers n and m (1 ≤ n, m ≤ 1 000 000). -----Output----- Print the only integer — the number of pairs of integers (x, y) such that 1 ≤ x ≤ n, 1 ≤ y ≤ m and (x + y) is divisible by 5. -----Examples----- Input 6 12 Output 14 Input 11 14 Output 31 Input 1 5 Output 1 Input 3 8 Output 5 Input 5 7 Output 7 Input 21 21 Output 88 -----Note----- Following pairs are suitable in the first sample case: for x = 1 fits y equal to 4 or 9; for x = 2 fits y equal to 3 or 8; for x = 3 fits y equal to 2, 7 or 12; for x = 4 fits y equal to 1, 6 or 11; for x = 5 fits y equal to 5 or 10; for x = 6 fits y equal to 4 or 9. Only the pair (1, 4) is suitable in the third sample case. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python ct=0 a, b = list(map(int, input().split(' '))) x=[0]*5 for i in range(1, b+1): x[i%5]+=1 for i in range(1, a+1): ct+=x[(0-i)%5] print(ct) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef wants to host some Division-3 contests. Chef has $N$ setters who are busy creating new problems for him. The $i^{th}$ setter has made $A_i$ problems where $1 \leq i \leq N$. A Division-3 contest should have exactly $K$ problems. Chef wants to plan for the next $D$ days using the problems that they have currently. But Chef cannot host more than one Division-3 contest in a day. Given these constraints, can you help Chef find the maximum number of Division-3 contests that can be hosted in these $D$ days? -----Input:----- - The first line of input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains three space-separated integers - $N$, $K$ and $D$ respectively. - The second line of each test case contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$ respectively. -----Output:----- For each test case, print a single line containing one integer ― the maximum number of Division-3 contests Chef can host in these $D$ days. -----Constraints----- - $1 \leq T \leq 10^3$ - $1 \leq N \leq 10^2$ - $1 \le K \le 10^9$ - $1 \le D \le 10^9$ - $1 \le A_i \le 10^7$ for each valid $i$ -----Subtasks----- Subtask #1 (40 points): - $N = 1$ - $1 \le A_1 \le 10^5$ Subtask #2 (60 points): Original constraints -----Sample Input:----- 5 1 5 31 4 1 10 3 23 2 5 7 20 36 2 5 10 19 2 3 3 300 1 1 1 -----Sample Output:----- 0 2 7 4 1 -----Explanation:----- - Example case 1: Chef only has $A_1 = 4$ problems and he needs $K = 5$ problems for a Division-3 contest. So Chef won't be able to host any Division-3 contest in these 31 days. Hence the first output is $0$. - Example case 2: Chef has $A_1 = 23$ problems and he needs $K = 10$ problems for a Division-3 contest. Chef can choose any $10+10 = 20$ problems and host $2$ Division-3 contests in these 3 days. Hence the second output is $2$. - Example case 3: Chef has $A_1 = 20$ problems from setter-1 and $A_2 = 36$ problems from setter-2, and so has a total of $56$ problems. Chef needs $K = 5$ problems for each Division-3 contest. Hence Chef can prepare $11$ Division-3 contests. But since we are planning only for the next $D = 7$ days and Chef cannot host more than $1$ contest in a day, Chef cannot host more than $7$ contests. Hence the third output is $7$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for T in range(int (eval(input()))): N,K,D=list(map(int,input().split())) A=list(map(int,input().split())) P=sum(A)//K print(min(P,D)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Try guessing the statement from this picture: $3$ You are given a non-negative integer $d$. You have to find two non-negative real numbers $a$ and $b$ such that $a + b = d$ and $a \cdot b = d$. -----Input----- The first line contains $t$ ($1 \le t \le 10^3$) — the number of test cases. Each test case contains one integer $d$ $(0 \le d \le 10^3)$. -----Output----- For each test print one line. If there is an answer for the $i$-th test, print "Y", and then the numbers $a$ and $b$. If there is no answer for the $i$-th test, print "N". Your answer will be considered correct if $|(a + b) - a \cdot b| \le 10^{-6}$ and $|(a + b) - d| \le 10^{-6}$. -----Example----- Input 7 69 0 1 4 5 999 1000 Output Y 67.985071301 1.014928699 Y 0.000000000 0.000000000 N Y 2.000000000 2.000000000 Y 3.618033989 1.381966011 Y 997.998996990 1.001003010 Y 998.998997995 1.001002005 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())): d=int(input()) anws=False if d**2>=4*d: root=(d**2-4*d)**0.5 a=(d+root)/2 b=(d-root)/2 anws=True if anws: print("Y {:.9f} {:.9f}".format(a,b)) else: print("N") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let F(X) equals to the number of lucky digits in decimal representation of X. Chef wants to know the number of such integers X, that L ≤ X ≤ R and F(X) is a lucky number. Help him and calculate that number modulo 109+7. -----Input----- First line contains one integer T, the number of test cases. Each of the following T lines contains two space separated positive integers L and R. -----Output----- For each of the T test cases print one integer, the number of such X, that L ≤ X ≤ R and F(X) is a lucky number, modulo 1000000007. -----Constraints----- 1 ≤ T ≤ 10 1 ≤ L ≤ R ≤ 101000 -----Example----- Input: 4 1 100 1 10000 1 100000 4444 4447 Output: 0 16 640 2 -----Notes----- First test case: of course, any number of less than 4 digits can't contain lucky number of lucky digits, so the answer is 0. Second test case: 16 required numbers are 4444 4447 4474 4477 4744 4747 4774 4777 7444 7447 7474 7477 7744 7747 7774 7777. Third test case: there are 640 required lucky numbers. Some of them are 4474, 14747, 41474, 77277, 44407, 74749. Fourth test case: the only two required numbers are 4444 and 4447. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python lucky = {4, 774, 7, 744, 777, 74, 747, 44, 77, 47, 474, 444, 477, 447} from functools import lru_cache import sys sys.setrecursionlimit(10 ** 6) mod = 10 ** 9 + 7 fact = [1] for i in range(1, 1001): fact.append(fact[-1] * i % mod) inv = [pow(i, mod-2, mod) for i in fact] C = lambda k, n: fact[n] * inv[n-k] * inv[k] % mod def f(n): n = [int(x) for x in n] @lru_cache(None) def dp(pos, cnt, free): if cnt > 777: return 0 diff = len(n) - pos ans = 0 if free: for i in lucky: i -= cnt if 0 <= i <= diff: ans += C(i, diff) * pow(2, i, mod) * pow(8, diff - i, mod) ans %= mod return ans if pos == len(n): return int(cnt in lucky) for i in range(10 if free else n[pos]+1): ans += dp(pos+1, cnt + int(i == 4 or i == 7), free or i < n[pos]) ans %= mod return ans return dp(0, 0, 0) t = int(input()) for _ in range(t): l, r = input().split() l = str(int(l) -1) print((f(r) - f(l)) % mod) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move. There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0). You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well. -----Input----- The first line contains four integers: x_{p}, y_{p}, x_{v}, y_{v} (0 ≤ x_{p}, y_{p}, x_{v}, y_{v} ≤ 10^5) — Polycarp's and Vasiliy's starting coordinates. It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0). -----Output----- Output the name of the winner: "Polycarp" or "Vasiliy". -----Examples----- Input 2 1 2 2 Output Polycarp Input 4 7 7 4 Output Vasiliy -----Note----- In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a, b, x, y = map(int, input().split()) if a >= x: if b >= y: print('Vasiliy') else: z = y - b t = max(x - z, 0) if a - z <= t: print('Polycarp') else: print('Vasiliy') else: if b <= y: print('Polycarp') else: z = x - a t = max(y - z, 0) if b - z <= t: print('Polycarp') else: print('Vasiliy') ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Guddu was participating in a programming contest. He only had one problem left when his mother called him for dinner. Guddu is well aware how angry his mother could get if he was late for dinner and he did not want to sleep on an empty stomach, so he had to leave that last problem to you. Can you solve it on his behalf? For a given sequence of positive integers $A_1, A_2, \ldots, A_N$, you are supposed to find the number of triples $(i, j, k)$ such that $1 \le i < j \le k \le N$ and Ai⊕Ai+1⊕…⊕Aj−1=Aj⊕Aj+1⊕…⊕Ak,Ai⊕Ai+1⊕…⊕Aj−1=Aj⊕Aj+1⊕…⊕Ak,A_i \oplus A_{i+1} \oplus \ldots \oplus A_{j-1} = A_j \oplus A_{j+1} \oplus \ldots \oplus A_k \,, where $\oplus$ denotes bitwise XOR. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing one integer ― the number of triples. -----Constraints----- - $1 \le T \le 10$ - $2 \le N \le 10^5$ - $1 \le A_i \le 10^6$ for each valid $i$ -----Subtasks----- Subtask #1 (20 points): - $1 \le T \le 5$ - $1 \le N \le 100$ Subtask #2 (30 points): - $1 \le T \le 5$ - $1 \le N \le 1,000$ Subtask #3 (50 points): original constraints -----Example Input----- 1 3 5 2 7 -----Example Output----- 2 -----Explanation----- Example case 1: The triples are $(1, 3, 3)$, since $5 \oplus 2 = 7$, and $(1, 2, 3)$, since $5 = 2 \oplus 7$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import itertools from collections import defaultdict as dfd def sumPairs(arr, n): s = 0 for i in range(n-1,-1,-1): s += i*arr[i]-(n-1-i)*arr[i] return s def subarrayXor(arr, n, m): ans = 0 xorArr =[0 for _ in range(n)] mp = dfd(list) xorArr[0] = arr[0] for i in range(1, n): xorArr[i] = xorArr[i - 1] ^ arr[i] for i in range(n): mp[xorArr[i]].append(i) a = sorted(mp.items()) #print(xorArr) #print(a) for i in a: diffs=0 if(i[0]!=0): l = len(i[1])-1 ans += sumPairs(i[1],len(i[1]))-((l*(l+1))//2) else: l = len(i[1])-1 ans += sumPairs(i[1],len(i[1]))-((l*(l+1))//2) ans += sum(i[1]) return ans for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) print(subarrayXor(arr,len(arr),0)) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: -----Problem Statement----- Sereja has a sequence of n integers a[1], a[2], ..., a[n]. Sereja can do following transformation of the array: - create a new sequence of n integers b[1], b[2], ..., b[n]in this way: (1 ≤ i ≤ n) - Replace the sequence a by b, i.e., a[i] = b[i] for all i in [1, n] Sereja decided to use his transformation k times. Then he computed the value of , where r — the sequence obtained after k transformations of sequence a, as described above. Sereja lost sequence a, but he was left with the numbers q(r) and k. Now Sereja is interested in the question : what is the number of the sequences of the integers с[1], с[2], ..., с[n], such that 1 ≤ c[i] ≤ m and q(d) = q(r), where d — the sequence obtained after k transformations of sequence c, as described above. -----Input----- The first lines contains a single integer T, denoting the number of test cases. Each test case consist of four integers : n, m, q(r), k. -----Output----- In a single line print the remainder of division the answer of the problem on number 10^9 + 7. -----Constraints----- - 1 ≤ T ≤ 10000 - 1 ≤ n, m, q(r), k ≤ 10^9 -----Example----- Input: 3 1 1 1 1 2 2 1 1 2 3 1 1 Output: 0 2 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def mod(a,b,c): x = 1 y = a while(b>0): if(b%2==1): x = (x*y)%c y = (y*y)%c b /=2 return x%c t = int(input()) num = 10**9+7 for i in range(t): n,m,q,k = list(map(int,input().split())) if m<=q: print(0) else: a1 = m-q a2 = mod(q+1,n,num) a3 = mod(q-1,n,num) a4 = mod(q,n,num) a5 = a2-2*a4+a3 ans = a1*a5 print(ans%num) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Some programming contest problems are really tricky: not only do they require a different output format from what you might have expected, but also the sample output does not show the difference. For an example, let us look at permutations. A permutation of the integers 1 to n is an ordering of these integers. So the natural way to represent a permutation is to list the integers in this order. With n = 5, a permutation might look like 2, 3, 4, 5, 1. However, there is another possibility of representing a permutation: You create a list of numbers where the i-th number is the position of the integer i in the permutation. Let us call this second possibility an inverse permutation. The inverse permutation for the sequence above is 5, 1, 2, 3, 4. An ambiguous permutation is a permutation which cannot be distinguished from its inverse permutation. The permutation 1, 4, 3, 2 for example is ambiguous, because its inverse permutation is the same. To get rid of such annoying sample test cases, you have to write a program which detects if a given permutation is ambiguous or not. -----Input Specification----- The input contains several test cases. The first line of each test case contains an integer n (1 ≤ n ≤ 100000). Then a permutation of the integers 1 to n follows in the next line. There is exactly one space character between consecutive integers. You can assume that every integer between 1 and n appears exactly once in the permutation. The last test case is followed by a zero. -----Output Specification----- For each test case output whether the permutation is ambiguous or not. Adhere to the format shown in the sample output. -----Sample Input----- 4 1 4 3 2 5 2 3 4 5 1 1 1 0 -----Sample Output----- ambiguous not ambiguous ambiguous The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def invper(ar): ar1=[0]*(len(ar)) for i in range(len(ar)): ar1[ar[i]-1]=i+1 return ar1 t=int(input()) while(t!=0): ar=list(map(int,input().split())) ar1=invper(ar) if(ar==ar1): print("ambiguous") else: print("not ambiguous") t = int(input()) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: A group of rebels travelling on a square hoverboard is ambushed by Imperial Stormtroopers.Their big hoverboard is an easy target, so they decide to split the board into smaller square hoverboards so that they can bolt away easily.But they should also make sure they don't get too spread out.Help the rebels split the craft into minimum number of smaller crafts possible. -----Input----- A single integer N denoting the side length of the big hoverboard. -----Output----- In the first line, output the integer 'k' which is the minimum number of square boards into which the bigger board can be split up. In the second line, output k space separated integers which denote the sizes of the smaller square hoverboards.This must be in increasing order of sizes. -----Constraints----- N ranges from 2 to 50. -----Example----- Input: 3 Output: 6 1 1 1 1 1 2 -----Explanation----- A square of side length 3 can be split into smaller squares in two ways: Either into 9 squares of side1 or 5 squares of side 1 and 1 square of size 2.The second case is the favourable one. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a=int(input()) if(a%2==0): print("4") print(a/2,a/2,a/2,a/2) else: print("6") print((a-1)/2,(a-1)/2,(a-1)/2,(a-1)/2,(a-1)/2,(a+1)/2) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: There is a grass field that stretches infinitely. In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0). There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j). What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print INF instead. -----Constraints----- - All values in input are integers between -10^9 and 10^9 (inclusive). - 1 \leq N, M \leq 1000 - A_i < B_i\ (1 \leq i \leq N) - E_j < F_j\ (1 \leq j \leq M) - The point (0, 0) does not lie on any of the given segments. -----Input----- Input is given from Standard Input in the following format: N M A_1 B_1 C_1 : A_N B_N C_N D_1 E_1 F_1 : D_M E_M F_M -----Output----- If the area of the region the cow can reach is infinite, print INF; otherwise, print an integer representing the area in \mathrm{cm^2}. (Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.) -----Sample Input----- 5 6 1 2 0 0 1 1 0 2 2 -3 4 -1 -2 6 3 1 0 1 0 1 2 2 0 2 -1 -4 5 3 -2 4 1 2 4 -----Sample Output----- 13 The area of the region the cow can reach is 13\ \mathrm{cm^2}. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #写経 #https://atcoder.jp/contests/abc168/submissions/14421546 import sys sys.setrecursionlimit(10**9) input = sys.stdin.readline from bisect import bisect_left, bisect_right INF = 10 **18 def resolve(): n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(n)] b = [list(map(int, input().split())) for i in range(m)] X = {-INF, INF} Y = {-INF, INF} for i in a: Y.add(i[2]) for i in b: X.add(i[0]) X = list(sorted(X)) Y = list(sorted(Y)) n = len(X) - 1 m = len(Y) - 1 wallx = [[False] * m for i in range(n)] wally = [[False] * m for i in range(n)] for x1, x2, y1 in a: x1 = bisect_left(X, x1) y1 = bisect_left(Y, y1) x2 = bisect_right(X, x2) - 1 for i in range(x1, x2): wally[i][y1] = True for x1, y1, y2 in b: x1 = bisect_left(X, x1) y1 = bisect_left(Y, y1) y2 = bisect_right(Y, y2) - 1 for i in range(y1, y2): wallx[x1][i] = True cow = [[False] * m for i in range(n)] cx = bisect_right(X, 0) - 1 cy = bisect_right(Y, 0) - 1 cow[cx][cy] = True q = [(cx, cy)] ans = 0 while q: x, y = q.pop() if not x or not y: print("INF") return ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y]) if x and not wallx[x][y] and not cow[x - 1][y]: cow[x - 1][y] = True q.append((x - 1, y)) if y and not wally[x][y] and not cow[x][y - 1]: cow[x][y - 1] = True q.append((x, y - 1)) if x + 1 < n and not wallx[x + 1][y] and not cow[x + 1][y]: cow[x + 1][y] = True q.append((x + 1, y)) if y + 1 < m and not wally[x][y + 1] and not cow[x][y + 1]: cow[x][y + 1] = True q.append((x, y + 1)) print(ans) resolve() ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Its Christmas time and Santa has started his ride to deliver gifts to children waiting for him in a 1-dimentional city. All houses in this city are on a number line numbered as 1, 2, 3… and so on. Santa wants to deliver to houses from n to m, but he found that all the kids living at positions that are divisible by a, a+d, a+2d, a+3d or a+4d are naughty and he does not want to deliver them any gifts. Santa wants to know how many gifts he has to carry before leaving to the city given that there is only one kid in a house. Help him out! Formally, Given $m, n, a, d \in \mathbb{N}$ where $n < m$, find the number of $x \in \{n, n+1, ..., m-1, m\}$ such that $x$ is not divisible by $a$, $a+d$, $a+2d$, $a+3d$ or $a+4d$ -----Input----- The first line is the number $t$, corresponding to number of test cases\ This is followed by $t$ lines of the format: $n$ $m$ $a$ $d$ -----Output----- For each test case, print a single number that is the number of gifts Santa should pack. -----Constraints----- - $1 < m, n, a \leq 2^{32}$ - $1 < d \leq 2^{10}$ -----Sample Input:----- 1 2 20 2 1 -----Sample Output:----- 5 -----Explanation:----- In the range {2, 3, 4, …, 19, 20}, only {7, 11, 13, 17, 19} are not divisible by 2, 3, 4, 5, or 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import gcd from math import ceil from itertools import combinations as c t=int(input()) for _ in range(t): n,m,a,d=list(map(int,input().split())) l=[] for i in range(5): l.append(a+i*d) ans=m-n+1 for i in range(1,6): x=list(c(l,i)) for j in x: e=j[0] for v in j: e=(e*v)//gcd(e,v) #print(e) if i%2: ans-=m//e-(n-1)//e else: ans+=m//e-(n-1)//e print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You're given an array $a_1, \ldots, a_n$ of $n$ non-negative integers. Let's call it sharpened if and only if there exists an integer $1 \le k \le n$ such that $a_1 < a_2 < \ldots < a_k$ and $a_k > a_{k+1} > \ldots > a_n$. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays $[4]$, $[0, 1]$, $[12, 10, 8]$ and $[3, 11, 15, 9, 7, 4]$ are sharpened; The arrays $[2, 8, 2, 8, 6, 5]$, $[0, 1, 1, 0]$ and $[2, 5, 6, 9, 8, 8]$ are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any $i$ ($1 \le i \le n$) such that $a_i>0$ and assign $a_i := a_i - 1$. Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations. -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 15\ 000$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$). The second line of each test case contains a sequence of $n$ non-negative integers $a_1, \ldots, a_n$ ($0 \le a_i \le 10^9$). It is guaranteed that the sum of $n$ over all test cases does not exceed $3 \cdot 10^5$. -----Output----- For each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise. -----Example----- Input 10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 Output Yes Yes Yes No No Yes Yes Yes Yes No -----Note----- In the first and the second test case of the first test, the given array is already sharpened. In the third test case of the first test, we can transform the array into $[3, 11, 15, 9, 7, 4]$ (decrease the first element $97$ times and decrease the last element $4$ times). It is sharpened because $3 < 11 < 15$ and $15 > 9 > 7 > 4$. In the fourth test case of the first test, it's impossible to make the given array sharpened. 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()) li=list(map(int,input().split())) ans=0 for i in range(n): if li[i]>=i: ans+=1 else: break for i in range(n): if li[n-1-i]>=i: ans+=1 else: break if ans>n: print("Yes") else: print("No") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: John was learning mathematics and was very bored. Jane his best friend gave him a problem to solve. The description of the problem was as follows:- You are given a decimal number $N$(1<=$N$<=$10^9$) and three integers $A$, $B$, $C$. Steps to perform: 1) You have to create a $LIST$. 2) You have to initialize the $LIST$ by adding N to the $LIST$ as its first element. 3) Divide$N$ by $A$ and if the first digit of the fractional part is Non-Zero then add this digit to the $LIST$ otherwise add the first digit of the integral part(Leftmost digit). (The integer part or integral part of a decimal is the integer written to the left of the decimal separator. The part from the decimal separator i.e to the right is the fractional part. ) 4) Update $N$ by Last element of the $LIST$. N = Last element of $LIST$ 5) You have to perform the same process from step 3 on $N$ for $B$ and $C$ respectively 6) Repeat from step 3 You have to answer$Q$(1 <= $Q$<= 100 ) queries For each query you are given an integer $i$ (0 <= $i$ <= $10^9$ ). You have to print the element present at the ith position of the $LIST$. Help John solve this problem. -----Input:----- - The First Line of input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The First Line of each test case contains the integer $N$. - The second line of each test case contains three integers $A$, $B$, and $C$ separated by a space - The third line of each test case contains an integer $Q$. - Then the next $Q$ line follows. - An integer $i$ (0 <= $i$ <= 10^9 ) -----Output:----- You have to answer the $Q$ queries in the next $Q$ lines. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 10^9$ - $2 \leq A \leq 10$ - $2 \leq B \leq 10$ - $2 \leq C \leq 10$ - $2 \leq Q \leq 100$ - $0 \leq i \leq 10^9$ -----Sample Input:----- 1 56 3 5 7 4 0 1 2 3 -----Sample Output:----- 56 6 2 2 -----EXPLANATION:----- This list is : $N$ = 56 and $A$ = 3, $B$ = 5, $C$ = 7. Initially $LIST$ = $[ 56 ]$ $N$$/$$A$ = 56/3 = 18.666666666666668 Add 6 to the $LIST$ $LIST$ = $[ 56, 6 ]$ $N$ = 6 $N$$/$$B$ = 6/5 = 1.2 Add 2 to the$LIST$ $LIST$ = $[ 56, 6, 2 ]$ N = 2 $N$$/$$C$ = 2/7 =0. 2857142857142857 Add 2 to the $LIST$. $LIST$ = $[ 56, 6, 2, 2 ]$ $N$ = 2 We have to keep repeating this process. If any of the numbers got by $N$ dividing by either $A$, $B$, $C$ have 0 after the decimal point then we have to take the first digit of the number. for example: if we got 12.005 then here we take 1 and add it to the list and then assign N = 1 Now the queries ask for the elements at index 0, 1, 2, 3 of the $LIST$ which is 56,6, 2, 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Why do we fall ? So we can learn to pick ourselves up. t = int(input()) for _ in range(0,t): n = int(input()) abc = [int(i) for i in input().split()] i = 0 lst = [n] for _ in range(0,100): k = str(lst[-1]/abc[i%3]).split('.') if int(k[1][0]) > 0: lst.append(int(k[1][0])) else: lst.append(int(k[0][0])) i += 1 pattern = [] ind = 0 while len(pattern) == 0: for i in range(ind, len(lst) - 1): check = lst[ind: i + 1] * 50 check = check[:len(lst) - ind] if lst[ind:] == check: pattern = check break if len(pattern): break ind += 1 final_pattern = [] for i in range(0, len(pattern)): couldbe = pattern[:i + 1] check = pattern[:i + 1] * 100 check = check[:len(pattern)] if check == pattern: final_pattern = couldbe break lp = len(final_pattern) q = int(input()) for _ in range(0, q): qq = int(input()) if qq < ind: print(lst[qq]) else: qq -= ind kk = qq % lp print(final_pattern[kk]) """ 1 56 3 5 7 4 0 1 2 3 """ ```