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:
"What do you know about happiness?" — Yoda
Chef is happy only if three conditions hold:
- Chef finished cooking a delicious meal
- Chef got AC for a programming problem with an almost correct code
- Chef got a new problem with a sequence of integers
Today, all three conditions are satisfied. Chef would like you to feel his happiness and provide him with a solution for this new problem with a sequence of integers. The problem is as follows.
You are given a sequence $A_1, A_2, \dots, A_N$. You need to determine if it is possible to choose two indices $i$ and $j$ such that $A_i \neq A_j$, but $A_{A_i}$ = $A_{A_j}$. (If it was possible, Chef would be truly happy.)
-----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 "Truly Happy" if it is possible to choose required indices or "Poor Chef" otherwise.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^5$
- $1 \le A_i \le N$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^5$
-----Subtasks-----
Subtask #1 (27 points): $1 \le N \le 1,000$
Subtask #2 (73 points): original constraints
-----Example Input-----
4
4
1 1 2 3
4
2 1 3 3
5
5 4 4 3 1
5
3 2 1 1 4
-----Example Output-----
Truly Happy
Poor Chef
Poor Chef
Truly Happy
-----Explanation-----
Example case 1: Chef is truly happy because $A_{A_3} = A_{A_1}$ and $A_3 \neq A_1$.
Example case 2: There is no pair of indices which would make Chef truly happy. For instance, $A_{A_3} = A_{A_4}$, but $A_3 = A_4$,
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
d={}
for i in range(n):
if a[i]-1 not in d:
d[a[i]-1]=[i]
else:
d[a[i]-1].append(i)
ans=False
d1={}
for i in d:
if ans==True:
break
for j in d:
if i!=j:
if a[i]==a[j] and i!=j:
ans=True
break
if ans==True:
print('Truly Happy')
else:
print('Poor Chef')
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Bear Limak has a sequence of N non-negative integers A1, A2, ..., AN. He defines the score of a segment (consecutive subsequence) as its sum of elements modulo P (not necessarily prime). Find the maximum score of a non-empty segment, and also find the number of segments with this maximum score.
-----Input-----
First line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
For each test case, the first line of the input contains two space separated integers, N and P.
The second line contains N space separated integers denoting the sequence.
-----Output-----
For each test case, output two space separated integers denoting the maximum score of a segment and the number of segments with the score, respectively.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ P ≤ 109
- 0 ≤ Ai ≤ 109
Subtask #1: (25 points)
- 1 ≤ N ≤ 100
Subtask #2: (25 points)
- 1 ≤ N ≤ 1000
Subtask #3: (50 points)
- original constraints
-----Example-----
Input:
4
2 3
1 2
3 5
2 4 3
3 100
1 3 5
4 3
1 2 3 4
Output:
2 1
4 2
9 1
2 2
-----Explanation-----
Example case 1. There are three segments - [1], [2] and [1, 2]. Sum of these segments are 1, 2 and 3 respectively. Sum of these segments modulo 3 will be 1, 2 and 0. Maximum score among these is 2. There is also only one segment with this score.
Example case 2. There are six segments - [2], [4], [3], [2, 4], [4, 3] and [2, 4, 3]. Sum of these segments are 2, 4, 3, 6, 7, 9 respectively. Sum of these segments modulo 5 will be 2, 4, 3, 1, 2, 4. Maximum score among these is 4. And there are two segments with this score.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for _ in range(int(input())):
n,m=input().split()
n,m=int(n),int(m)
x=y=c=0
l=list(map(int,input().split()))
for i in range(n):
for j in range(i,n):
x=x+l[j]
if (x%m)>y:
y=x%m
c=1
elif y==(x%m):
c+=1
x = 0
print(y,c)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Like all minions Dave also like to eat bananas. So as to his obsession, he is eating banana, but this time in different way. There are N bananas in dish. Dave wants to eat all of them. He starts eating at speed 1 banana/second. He can increase or decrease speed of eating by one only. The condition is that he must end eating at speed 1 banana/second. So, your task is to find minimum time required to finish all bananas in a dish.
-----Input-----
First line contain number of test cases T. Next T lines contain one integer N. Where N is number of bananas in a dish.
-----Output-----
For each test case print minimum time require to eat all N bananas.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 105
-----Example-----
Input:
2
2
4
Output:
2
3
-----Explanation-----
Example case 1.Dave will start to eat with rate of 1 banana/second. Then only one banana will remain. He will eat that banana in 1 second. Thus, Total time is 2 seconds.
Example case 2.Dave starts with rate of 1 banana/second, and then increase it to 2 bananas/second and again decrease it to 1 banana/second. So total time is 3 seconds.
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):
k=1
j=0
n=int(input())
while(n>0):
if(n<=k):
j+=1
n=0
elif n>2*k:
j+=2
n=n-2*k
k+=1
else:
j+=2
n=0
print(j)
t-=1
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You might have heard about our new goodie distribution program aka the "Laddu Accrual System". This problem is designed to give you a glimpse of its rules. You can read the page once before attempting the problem if you wish, nonetheless we will be providing all the information needed here itself.
Laddu Accrual System is our new goodie distribution program. In this program, we will be distributing Laddus in place of goodies for your winnings and various other activities (described below), that you perform on our system. Once you collect enough number of Laddus, you can then redeem them to get yourself anything from a wide range of CodeChef goodies.
Let us know about various activities and amount of laddus you get corresponding to them.
- Contest Win (CodeChef’s Long, Cook-Off, LTIME, or any contest hosted with us) : 300 + Bonus (Bonus = 20 - contest rank). Note that if your rank is > 20, then you won't get any bonus.
- Top Contributor on Discuss : 300
- Bug Finder : 50 - 1000 (depending on the bug severity). It may also fetch you a CodeChef internship!
- Contest Hosting : 50
You can do a checkout for redeeming laddus once a month. The minimum laddus redeemable at Check Out are 200 for Indians and 400 for the rest of the world.
You are given history of various activities of a user. The user has not redeemed any of the its laddus accrued.. Now the user just wants to redeem as less amount of laddus he/she can, so that the laddus can last for as long as possible. Find out for how many maximum number of months he can redeem the laddus.
-----Input-----
- The first line of input contains a single integer T denoting number of test cases
- For each test case:
- First line contains an integer followed by a string denoting activities, origin respectively, where activities denotes number of activities of the user, origin denotes whether the user is Indian or the rest of the world. origin can be "INDIAN" or "NON_INDIAN".
- For each of the next activities lines, each line contains an activity.
An activity can be of four types as defined above.
- Contest Win : Input will be of form of CONTEST_WON rank, where rank denotes the rank of the user.
- Top Contributor : Input will be of form of TOP_CONTRIBUTOR.
- Bug Finder : Input will be of form of BUG_FOUND severity, where severity denotes the severity of the bug.
- Contest Hosting : Input will be of form of CONTEST_HOSTED.
-----Output-----
- For each test case, find out the maximum number of months for which the user can redeem the laddus accrued.
-----Constraints-----
- 1 ≤ T, activities ≤ 100
- 1 ≤ rank ≤ 5000
- 50 ≤ severity ≤ 1000
-----Subtasks-----
There is only a single subtask with 100 points.
-----Example-----
Input:
2
4 INDIAN
CONTEST_WON 1
TOP_CONTRIBUTOR
BUG_FOUND 100
CONTEST_HOSTED
4 NON_INDIAN
CONTEST_WON 1
TOP_CONTRIBUTOR
BUG_FOUND 100
CONTEST_HOSTED
Output:
3
1
-----Explanation-----
In the first example,
- For winning contest with rank 1, user gets 300 + 20 - 1 = 319 laddus.
- For top contributor, user gets 300 laddus.
- For finding a bug with severity of 100, user gets 100 laddus.
- For hosting a contest, user gets 50 laddus.
So, overall user gets 319 + 300 + 100 + 50 = 769 laddus.
Now, the user is an Indian user, he can redeem only 200 laddus per month. So, for first three months, he will redeem 200 * 3 = 600 laddus. The remaining 169 laddus, he can not redeem as he requires at least 200 laddues in a month to redeem.
So, answer is 3.
In the second example, user is a non-Indian user, he can redeem 400 laddues per month. So, in the first month, he will redeem 400 laddus. The remaining 369 laddus, he can not redeem as he requires at least 400 laddues in a month to redeem.
So, answer is 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for i in range(int(input())):
n,k=input().split()
laddus=0
for j in range(int(n)):
t=input().split()
if t[0]=='CONTEST_WON':
if(int(t[1])<=20):
laddus+=300+20-int(t[1])
else:
laddus+=300
elif t[0]=='TOP_CONTRIBUTOR':
laddus+=300
elif t[0]=='BUG_FOUND':
laddus+=int(t[1])
elif t[0]=='CONTEST_HOSTED':
laddus+=50
if(k=='INDIAN'):
print(laddus//200)
else:
print(laddus//400)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Indian National Olympiad in Informatics 2016
There are k types of brackets each with its own opening bracket and closing bracket. We assume that the first pair is denoted by the numbers 1 and k+1, the second by 2 and k+2 and so on. Thus the opening brackets are denoted by 1,2,.., k, and the corresponding closing brackets are denoted by k+1,k+2,..., 2*k respectively.
Some sequences with elements from 1,2, ... 2*k form well-bracketed sequences while others don't. A sequence is well-bracketed, if we can match or pair up opening brackets and closing brackets of the same type in such a way that the following holds:
1) every bracket is paired up
2) in each matched pair, the opening bracket occurs before the closing bracket
3) for a matched pair, any other matched pair lies either completely between them or outside them.
For the examples discussed below, let us assume that k = 2. The sequence 1,1,3 is not well-bracketed as one of the two 1's cannot be paired. The sequence 3,1,3,1 is not well-bracketed as there is no way to match the second 1 to a closing bracket occurring after it. The sequence 1,2,3,4 is not well-bracketed as the matched pair 2,4 is neither completely between the matched pair 1,3 nor completely outside it. That is, the matched pairs cannot overlap. The sequence 1,2,4,3,1,3 is well-bracketed. We match the first 1 with the first 3, the 2 with the 4 and the second 1 with the second 3, satisfying all the 3 conditions. If you rewrite these sequences using [,{,],} instead of 1,2,3,4 respectively, this will be quite clear.
In this problem you are given a sequence of brackets, of length N: B[1], .., B[N], where each B[i] is one of the brackets. You are also given an array of Values: V[1],.., V[N].
Among all the subsequences in the Values array, such that the corresponding bracket subsequence in the B Array is a well-bracketed sequence, you need to find the maximum sum. Suppose N = 6, k = 3 and the values of V and B are as follows:
i 1 2 3 4 5 6
V[i] 4 5 -2 1 1 6
B[i] 1 3 4 2 5 6
Then, the brackets in positions 1,3 form a well-bracketed sequence (1,4) and the sum of the values in these positions is 2 (4 + -2 = 2). The brackets in positions 1,3,4,5 form a well-bracketed sequence (1,4,2,5) and the sum of the values in these positions is 4. Finally, the brackets in positions 2,4,5,6 forms a well-bracketed sequence (3,2,5,6) and the sum of the values in these positions is 13. The sum of the values in positions 1,2,5,6 is 16 but the brackets in these positions (1,3,5,6) do not form a well-bracketed sequence. You can check the best sum from positions whose brackets form a well-bracketed sequence is 13.
-----Input format-----
One line, which contains (2*N + 2) space separate integers. The first integer denotes N. The next integer is k. The next N integers are V[1],..., V[N]. The last N integers are B[1],.., B[N].
-----Output format-----
One integer, which is the maximum sum possible satisfying the requirement mentioned above.
-----Test data-----
1 ≤ k ≤ 7
-106 ≤ V[i] ≤ 106, for all i
1 ≤ B[i] ≤ 2*k, for all i.
Subtask 1 (40 Marks) 1 ≤ n ≤ 10.
Subtask 2 (60 Marks) 1 ≤ n ≤ 700.
-----Sample Input-----
6 3 4 5 -2 1 1 6 1 3 4 2 5 6
-----Sample Output-----
13
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
import bisect
n, k1, *l = map(int, input().split())
v_l, b_l = l[:n], l[n:]
b_inv = {key:[] for key in range(2*k1)}
for i in range(n):
b_l[i] -= 1
b_inv[b_l[i]].append(i)
dp = [[0 for _ in range(n)] for _ in range(n)]
for k in range(1, n):
for j in range(n-2, -1, -1):
if j+k >= n:
continue
dp[j][j+k] = max(dp[j][j+k], dp[j][j+k-1])
if b_l[j+k] >= k1:
left = bisect.bisect_right(b_inv[b_l[j+k]-k1], j)
if b_l[j+k] >= k1:
for i in b_inv[b_l[j+k]-k1][left:]:
if i > j+k:
break
if i > j:
dp[j][j+k] = max(dp[j][j+k], dp[j][i-1]+dp[i][j+k])
if b_l[j+k]-k1 == b_l[j]:
if j+k-1 < n:
dp[j][j+k] = max(dp[j][j+k], v_l[j+k]+v_l[j]+dp[j+1][j+k-1])
else:
dp[j][j+k] = max(dp[j][j+k], v_l[j+k]+v_l[j])
print(dp[0][-1])
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $k$-balanced if every substring of size $k$ of this bitstring has an equal amount of 0 and 1 characters ($\frac{k}{2}$ of each).
You are given an integer $k$ and a string $s$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $k$-balanced bitstring by replacing every ? characters in $s$ with either 0 or 1.
A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
-----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 first line of each test case contains two integers $n$ and $k$ ($2 \le k \le n \le 3 \cdot 10^5$, $k$ is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string $s$ ($|s| = n$). It is given that $s$ consists of only 0, 1, and ?.
It is guaranteed that the sum of $n$ over all test cases does not exceed $3 \cdot 10^5$.
-----Output-----
For each test case, print YES if we can replace every ? in $s$ with 0 or 1 such that the resulting bitstring is $k$-balanced, or NO if it is not possible.
-----Example-----
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
-----Note-----
For the first test case, the string is already a $4$-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
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, k = list(map(int, input().split()))
s = input()
l = ['']*k
works = True
for i in range(n):
c = s[i]
if c != '?':
if l[i%k] == c or l[i%k] == '':
l[i%k] = c
else:
works = False
break
if works:
smol = 0
big = k
for c in l:
if c == '0':
big -= 1
elif c == '1':
smol += 1
goal = k//2
if smol <= goal <= big:
print('YES')
else:
print('NO')
else:
print('NO')
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Dhruvil has always been a studious person and will be completing his Engineering soon. He is always kneen about solving problems and is preparing hard for his next interview at Hackerrank. He has practiced lots of problems and now he came across this problem.
Given a message containing English letters(A-Z), it is being encoded to numbers using the following mapping:
'A' -> 1,'B' -> 2 ……………… 'Z' -> 26.
Now, given a non-empty string containing only digits, help Dhruvil determine the total number of ways to decode it.
While decoding you need to choose a substring of charachters and not a subsequence. Also a chosen substring should not contain any leading "0"s, but can contain trailing "0"s. Since the output can be very large print the answer as modulo 10^9 + 7 i.e 1000000007.
-----Input:-----
The first line of the input consists of single integer T, the number of test cases.
Each test case consists of a string.
-----Output:-----
For each test case print a single integer - the total number of ways to decode the digit string.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq S \leq 10^9$
-----Sample Input:-----
2
12
226
-----Sample Output:-----
2
3
-----EXPLANATION:-----
There are 2 possible ways. It could be decoded as "AB" {1,2} or "L" {12}.
There are 3 possible ways. It could be decoded as "BZ" {2,26}, "VF" {22,6}, or "BBF" {2,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
# cook your dish here
def numDec(s):
if not s:
return 0
dp = [0 for _ in range(len(s) + 1)]
dp[0] = 1
dp[1] = 0 if s[0] == '0' else 1
for i in range(2, len(dp)):
if s[i-1] != '0':
dp[i] += dp[i-1]
two_digit = int(s[i-2 : i])
if two_digit >= 10 and two_digit <= 26:
dp[i] += dp[i-2]
return dp[len(s)]
t = int(input())
while(t):
t-=1
s = input()
print(numDec(s)%1000000007)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: $\left. \begin{array}{|r|r|r|r|r|r|} \hline & {2} & {9} & {16} & {23} & {30} \\ \hline & {3} & {10} & {17} & {24} & {31} \\ \hline & {4} & {11} & {18} & {25} & {} \\ \hline & {5} & {12} & {19} & {26} & {} \\ \hline & {6} & {13} & {20} & {27} & {} \\ \hline & {7} & {14} & {21} & {28} & {} \\ \hline 1 & {8} & {15} & {22} & {29} & {} \\ \hline \end{array} \right.$
Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.
-----Input-----
The only line contain two integers m and d (1 ≤ m ≤ 12, 1 ≤ d ≤ 7) — the number of month (January is the first month, December is the twelfth) and the weekday of the first date of this month (1 is Monday, 7 is Sunday).
-----Output-----
Print single integer: the number of columns the table should have.
-----Examples-----
Input
1 7
Output
6
Input
1 1
Output
5
Input
11 6
Output
5
-----Note-----
The first example corresponds to the January 2017 shown on the picture in the statements.
In the second example 1-st January is Monday, so the whole month fits into 5 columns.
In the third example 1-st November is Saturday and 5 columns is enough.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
arr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
a, b = list(map(int, input().split()))
a -= 1
b -= 1
ctr = 1
for i in range(arr[a] - 1):
b += 1
if (b == 7):
b = 0
ctr += 1
print(ctr)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
For a permutation P = (p1, p2, ..., pN) of numbers [1, 2, ..., N], we define the function f(P) = max(p1, p2) + max(p2, p3) + ... + max(pN-1, pN).
You are given N and an integer K. Find and report a permutation P of [1, 2, ..., N] such that f(P) = K, if such a permutation exists.
Note f([1]) = 0.
-----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 consists of two space-separated integers N, K respectively.
-----Output-----
For each test case, if a permutation satisfying the condition exists, output a single line containing N space-separated integers which denotes any such permutation. If no such permutation exists, output a single integer -1 instead.
Use fast I/O methods since the size of the output is large.
-----Constraints-----
- 1 ≤ T ≤ 40
- 1 ≤ N ≤ 105
- Sum of N over all test cases in each file ≤ 106
- 0 ≤ K ≤ 2 * 1010
-----Example-----
Input:
3
4 12
2 2
5 14
Output:
-1
1 2
5 4 3 2 1
-----Explanation-----
Example 1. There doesn't exist any permutation of numbers [1, 2, 3, 4] that can have its f value equal to 4. Hence answer is -1.
Example 2. The permutations [1, 2] and [2, 1] both have their f values equal to 2. You can print any of these two permutations.
Example 3. The permutation [5, 4, 3, 2, 1]
has f value = max(5, 4) + max(4, 3) + max(3, 2) + max(2, 1) = 5 + 4 + 3 + 2 = 14.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
for i in range(int(input())):
n,k=[int(i) for i in input().split()]
if(n%2==0):
if(k<(n*(n+1))//2 - 1 or k>3*((n//2)**2) - 1):print(-1)
elif(k==(n*(n+1))//2 - 1):
for i in range(1,n+1):print(i,'',end='')
print()
else:
k,count,p,l,x = k-(n*(n+1))//2 + 1,0,0,[0 for i in range(n)],1
while(k>0):p+=2 ;k,count = k-n+p ,count+1
for i in range(n,n-count+1,-1):l[x]=i ;x+=2
k=-k ;l[2*count - 1 +k],p = n-count+1 ,1
for i in range(n):
if(l[i]==0):l[i]=p ; p+=1
for i in l:print(i,'',end='')
print()
else:
if(n==1):print(1) if(k==0) else print(-1)
elif(k<(n*(n+1))//2 - 1 or k>3*(n//2)*(n//2 + 1)):print(-1)
elif(k==(n*(n+1))//2 - 1):
for i in range(1,n+1):print(i,'',end='')
print()
else:
k,count,p,l,x = k-(n*(n+1))//2 + 1,0,0,[0 for i in range(n)],1
while(k>0): p+=2 ; k,count = k-n+p ,count+1
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
This is the hard version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix.
For example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$.
Your task is to transform the string $a$ into $b$ in at most $2n$ operations. It can be proved that it is always possible.
-----Input-----
The first line contains a single integer $t$ ($1\le t\le 1000$) — the number of test cases. Next $3t$ lines contain descriptions of test cases.
The first line of each test case contains a single integer $n$ ($1\le n\le 10^5$) — the length of the binary strings.
The next two lines contain two binary strings $a$ and $b$ of length $n$.
It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$.
-----Output-----
For each test case, output an integer $k$ ($0\le k\le 2n$), followed by $k$ integers $p_1,\ldots,p_k$ ($1\le p_i\le n$). Here $k$ is the number of operations you use and $p_i$ is the length of the prefix you flip in the $i$-th operation.
-----Example-----
Input
5
2
01
10
5
01011
11100
2
01
01
10
0110011011
1000110100
1
0
1
Output
3 1 2 1
6 5 2 5 3 1 2
0
9 4 1 2 10 4 1 2 1 5
1 1
-----Note-----
In the first test case, we have $01\to 11\to 00\to 10$.
In the second test case, we have $01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$.
In the third test case, the strings are already the same. Another solution is to flip the prefix of length $2$, which will leave $a$ unchanged.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
input = sys.stdin.readline
from collections import deque
t=int(input())
for tests in range(t):
n=int(input())
a=input().strip()
b=input().strip()
Q=deque(a)
L=[]
while Q:
L.append(Q.popleft())
if Q:
L.append(Q.pop())
ANS=[]
for i in range(n):
if i%2==0:
if L[i]==b[-1-i]:
ANS.append(1)
else:
if L[i]!=b[-1-i]:
ANS.append(1)
ANS.append(n-i)
print(len(ANS),*ANS)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has N laddus of K sweetness each. Chef wants to eat all laddus, but Chef is restricted with the given condition that he must not eat two adjacent laddus. Chef starts calculating the maximum sweetness that he will get from the laddus. Find the maximum sweetness that chef gets at the end of all calculations.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, two integers $N, K$.
-----Output:-----
For each test case, output in a single line answer as Maximum sweetness the chef will have.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^5$
- $1 \leq K \leq 10^5$
-----Sample Input:-----
2
1 2
4 3
-----Sample Output:-----
2
6
-----EXPLANATION:-----
For 1) Chef will get only 1 laddu with sweetness 2.
For 2) Chef will have multiple ways as
[1,3], [2,4], [1,4] with sweetness 6
[1],[2],[3],[4] with sweetness 3.
Maximum sweetness will be 6.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = int(input())
for _ in range(t):
n,m = map(int,input().split())
if n==1:
print(m)
else:
if n%2==0:
print((n//2)*m)
else:
print(((n//2)+1)*m)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given an array of integers [A1,A2,…,AN]$[A_1, A_2, \ldots, A_N]$. Let's call adding an element to this array at any position (including the beginning and the end) or removing an arbitrary element from it a modification. It is not allowed to remove an element from the array if it is empty.
Find the minimum number of modifications which must be performed so that the resulting array can be partitioned into permutations. Formally, it must be possible to partition elements of the resulting array into zero or more groups (multisets; not necessarily identical) in such a way that each element belongs to exactly one group and for each group, if it contains L$L$ elements, then it must contain only integers 1$1$ through L$L$, each of them exactly once.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains a single integer N$N$.
- The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \ldots, A_N$.
-----Output-----
For each test case, print a single line containing one integer ― the minimum required number of modifications.
-----Constraints-----
- 1≤T≤1,000$1 \le T \le 1,000$
- 1≤N≤106$1 \le N \le 10^6$
- 1≤Ai≤109$1 \le A_i \le 10^9$ for each valid i$i$
- the sum of N$N$ over all test cases does not exceed 106$10^6$
-----Subtasks-----
Subtask #1 (50 points):
- 1≤N≤1,000$1 \le N \le 1,000$
- the sum of N$N$ over all test cases does not exceed 10,000$10,000$
Subtask #2 (50 points): original constraints
-----Example Input-----
2
5
1 4 1 2 2
4
2 3 2 3
-----Example Output-----
1
2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
for _ in range(int(input())):
n=int(input());li=list(map(int,input().split()));dli=dict();modi=0
for i in li:
if i not in dli:dli[i]=1
else:dli[i]+=1
op=sorted(list(dli))
if(len(dli)!=0):
while 1:
tmp=[]
for i in op:
if dli[i]==0:continue
tmp.append(i);dli[i]-=1
l=len(tmp);mn=l
for i in range(l):mn=min(mn,tmp[i]-1-i+l-1-i)
modi+=mn
if(l==0):break
print(modi)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
-----Description-----
The Antique Comedians of India prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACI has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play. A reversed number is a number written in Arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also, note that the reversed number never has any trailing zeros. ACI needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 23 could be 32, 320, or 3200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 23).
-----Input-----
The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add. Numbers will be at most 200 characters long.
-----Output-----
For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.
-----Sample Input-----
3
24 1
4358 754
305 794
-----Sample Output-----
34
1998
1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#include<stdio.h>
int rev(int k)
{
int j,res=0;
while(k)
{
res=res*10+k%10;
k/=10;
}
return res;
}
int main()
{
int j,a,b,m,k;
while(scanf("%d",&m)!=EOF)
{
for(j=1;j<=m;j++)
{
scanf("%d %d",&a,&b);
k=rev(a)+rev(b);
printf("%d\n",rev(k));
}
}
return 0;
}
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Consider the infinite x$x$ axis. There are N$N$ impacts on this X-axis at integral points (X1$X_1$,X2$X_2$,....XN$X_N$) (all distinct) . An impact at a point X$X$i propagates such that at a point X$X$0, the effect of the impact is K|Xi−X0|$K^{|X_i - X_0|}$. Given the point X0$X_0$, N$N$ and K$K$. Assume the total impact on X0$X_0$ is M$M$, find if it is possible to do so.Note: You are not required to find the set X
Formally print "yes" if this is possible and "no" if not possible.
-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, four integers N$N$,K$K$,M$M$,X$X$0
-----Output:-----
- The output of each test case is either "yes" or "no"
-----Constraints -----
- 1≤T≤1000$1\leq T \leq 1000$
- 1≤N≤100$1\leq N \leq 100$
- 1≤K≤1000$1\leq K \leq 1000$
- 1≤M≤1018$1\leq M \leq 10^{18}$
- −109≤X0≤109$-10^9 \leq X_0 \leq 10^9$
-----Sample Input:-----
2
4 3 10 10
2 3 10 10
-----Sample Output:-----
no
yes
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
T = int(input())
for i in range(T):
l = list(map(int, input().split()))
n, k, m, x = l[0], l[1], l[2], l[3]
if k == 1:
if n == m:
print("yes")
else:
print("no")
elif m % k > 1:
print("no")
elif k == 2:
stack = []
var = 0
while m != 0:
var += m % k
stack.append(m % k)
m //= k
if var > n:
print("no")
elif var == n:
print("yes")
else:
for p in range(100):
for q in range(2, len(stack)):
if stack[q - 1] == 0 and stack[q] >= 1:
stack[q-1] = 2
stack[q] -= 1
var += 1
if var == n:
print("yes")
if var < n:
print("no")
else:
temp = 0
rog = 1
while m != 0:
if m % k > 2:
rog = 0
print("no")
temp += m % k
m //= k
if rog:
if temp == n:
print("yes")
else:
print("no")
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $1$. If he manages to finish the level successfully then the number of clears increases by $1$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).
Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.
So he peeked at the stats $n$ times and wrote down $n$ pairs of integers — $(p_1, c_1), (p_2, c_2), \dots, (p_n, c_n)$, where $p_i$ is the number of plays at the $i$-th moment of time and $c_i$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).
Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.
Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.
Help him to check the correctness of his records.
For your convenience you have to answer multiple independent test cases.
-----Input-----
The first line contains a single integer $T$ $(1 \le T \le 500)$ — the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) — the number of moments of time Polycarp peeked at the stats.
Each of the next $n$ lines contains two integers $p_i$ and $c_i$ ($0 \le p_i, c_i \le 1000$) — the number of plays and the number of clears of the level at the $i$-th moment of time.
Note that the stats are given in chronological order.
-----Output-----
For each test case print a single line.
If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES".
Otherwise, print "NO".
You can print each letter in any case (upper or lower).
-----Example-----
Input
6
3
0 0
1 1
1 2
2
1 0
1000 3
4
10 1
15 2
10 2
15 2
1
765 432
2
4 4
4 3
5
0 0
1 0
1 0
1 0
1 0
Output
NO
YES
NO
YES
NO
YES
-----Note-----
In the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.
The second test case is a nice example of a Super Expert level.
In the third test case the number of plays decreased, which is impossible.
The fourth test case is probably an auto level with a single jump over the spike.
In the fifth test case the number of clears decreased, which is also impossible.
Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.
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 = int(input())
lastP = 0
lastC = 0
works = True
for _ in range(n):
p, c = list(map(int, input().split()))
pDiff = p-lastP
cDiff = c-lastC
if 0 <= cDiff <= pDiff:
pass
else:
works = False
lastP = p
lastC = c
if works:
print('YES')
else:
print('NO')
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send a_{i} requests.
Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load.
Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable.
For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp.
Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to n.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the duration of the load testing.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the number of requests from friends in the i-th minute of the load testing.
-----Output-----
Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards.
-----Examples-----
Input
5
1 4 3 2 5
Output
6
Input
5
1 2 2 2 1
Output
1
Input
7
10 20 40 50 70 90 30
Output
0
-----Note-----
In the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests.
In the second example it is enough to make one additional request in the third minute, so the answer is 1.
In the third example the load already satisfies all conditions described in the statement, so the answer is 0.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
lp,rp = [0 for i in range(n)],[0 for i in range(n)]
lnr, rnr = [a[i] for i in range(n)],[a[i] for i in range(n)]
mx = a[0]
for i in range(1,n):
if a[i] > mx:
mx = a[i]
lp[i] = lp[i-1]
else:
mx += 1
lp[i] = lp[i-1] + mx - a[i]
lnr[i] = mx
mx = a[-1]
for i in range(n-2,-1,-1):
if a[i] > mx:
mx = a[i]
rp[i] = rp[i+1]
else:
mx += 1
rp[i] = rp[i+1] + mx - a[i]
rnr[i] = mx
ans = min(rp[0], lp[-1])
for i in range(1,n-1):
ca = lp[i-1] + rp[i+1]
if max(lnr[i-1], rnr[i+1]) + 1 > a[i]:
ca += max(lnr[i-1], rnr[i+1]) + 1 - a[i]
ans = min(ans, ca)
print(ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has invited Alice for his birthday party. Now, Alice is thinking about what to give Chef as a present. She should obviously choose a sequence ― what could possibly be a better birthday gift than a sequence!
After some thinking, Alice chose a sequence of integers $A_1, A_2, \ldots, A_N$. However, she does not want to simply give this sequence to Chef. Instead, she decided to give Chef a sequence $B_1, B_2, \ldots, B_N$, where $B_i = \bigvee_{j=1}^i A_j$ for each valid $i$ and $\bigvee$ denotes the bitwise OR operation. Chef can try to generate a sequence $A$ from $B$, but there could be more than one such possible sequence.
Now, Alice is wondering how many sequences $A$ correspond to the given sequence $B$. Since this number could be very large, compute it modulo $10^9 + 7$. Note that it is not guaranteed that the given sequence $B$ was generated from some sequence $A$.
-----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 $B_1, B_2, \ldots, B_N$.
-----Output-----
For each test case, print a single line containing one integer ― the number of possible sequences $A$ modulo $10^9 + 7$.
-----Constraints-----
- $1 \le T \le 25$
- $1 \le N \le 5 \cdot 10^4$
- $0 \le B_i < 2^{30}$ for each valid $i$
-----Example Input-----
2
2
2 3
4
2 6 7 7
-----Example Output-----
2
64
-----Explanation-----
Example case 1: There are two possible options for $A$: $(2, 1)$ and $(2, 3)$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
mod=10**9+7
def pow2(x):
p,n=1,2
while(x):
if(x & 1): p=((p%mod) * (n%mod))%mod
n=((n%mod) * (n%mod))%mod
x//=2
return p
def count_bit(val):
bit=0
while(val):
bit+=1
val &=(val-1)
return bit
def answer():
val=b[0]
po2=0
for i in range(1,len(b)):
if(val > b[i]):return 0
po2+=count_bit(val & b[i])
val=b[i]
return pow2(po2)%mod
for T in range(int(input())):
n=int(input())
b=list(map(int,input().split()))
print(answer())
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There is a task in Among Us in which $N$ temperature scale with unique readings are given and you have to make all of them equal. In one second you can choose an odd number and add or subtract that number in any one temperature value. Find minimum time (in seconds) required to complete the task.
$Note$: Equal value may or may not belong to array.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains single integer $N$, the number of temperature scales
- Next line contain $A_i$ for $1 \leq i \leq N$, reading of temperature scales
-----Output:-----
For each testcase, output a single line the time (in seconds) required to complete the task.
-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^3$
- $0 \leq A_i \leq 10^9$
-----Sample Input:-----
3
5
1 2 3 4 5
4
5 2 3 8
2
50 53
-----Sample Output:-----
5
4
1
-----EXPLANATION:-----
- In the $2^{nd}$ test case we need $2$ seconds to change $2$ to $8$ , $1$ second to change $3$ and $5$ to $8$ . So total time required is $2+1+1=4$ seconds.
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())
ar=list(map(int,input().split()))
odd=0
even=0
if n==1:
print(0)
continue
for i in range(n):
if ar[i]%2==1:
odd+=1
else:
even+=1
if odd>0:
vo=(odd-1)*2+even
else:
vo=even
if even>0:
ve=(even-1)*2+odd
else:
ve=odd
print(min(vo,ve))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value a_{i}. The root of the tree is node 1.
This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works.
This tree supports two types of queries:
"1 x val" — val is added to the value of node x; "2 x" — print the current value of node x.
In order to help Iahub understand the tree better, you must answer m queries of the preceding type.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000). Each of the next n–1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i}, u_{i} ≤ n), meaning that there is an edge between nodes v_{i} and u_{i}.
Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000.
-----Output-----
For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input.
-----Examples-----
Input
5 5
1 2 1 1 2
1 2
1 3
2 4
2 5
1 2 3
1 1 2
2 1
2 2
2 4
Output
3
3
0
-----Note-----
The values of the nodes are [1, 2, 1, 1, 2] at the beginning.
Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1].
Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1].
You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory)
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
class BIT():
"""区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する
add: 区間[begin, end)にvalを加える
get_val: i番目(0-indexed)の値を求める
"""
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def get_val(self, i):
i = i + 1
s = 0
while i <= self.n:
s += self.bit[i]
i += i & -i
return s
def _add(self, i, val):
while i > 0:
self.bit[i] += val
i -= i & -i
def add(self, i, j, val):
self._add(j, val)
self._add(i, -val)
from collections import deque
import sys
input = sys.stdin.readline
def eular_tour(tree: list, root: int):
"""頂点に対するオイラーツアーを行う
posの部分木に区間[begin[pos], end[pos])が対応する
"""
n = len(tree)
res = []
begin = [-1] * n
end = [-1] * n
visited = [False] * n
visited[root] = True
q = deque([root])
while q:
pos = q.pop()
res.append(pos)
end[pos] = len(res)
if begin[pos] == -1:
begin[pos] = len(res) - 1
for next_pos in tree[pos]:
if visited[next_pos]:
continue
else:
visited[next_pos] = True
q.append(pos)
q.append(next_pos)
return res, begin, end
n, q = map(int, input().split())
init_cost = list(map(int, input().split()))
info = [list(map(int, input().split())) for i in range(n-1)]
query = [list(map(int, input().split())) for i in range(q)]
tree = [[] for i in range(n)]
for i in range(n-1):
a, b = info[i]
a -= 1
b -= 1
tree[a].append(b)
tree[b].append(a)
res, begin, end = eular_tour(tree, 0)
even_res = []
odd_res = []
for i in range(len(res)):
if i % 2 == 0:
even_res.append(res[i])
else:
odd_res.append(res[i])
even_bit = BIT(len(even_res))
odd_bit = BIT(len(odd_res))
for i in range(q):
if query[i][0] == 1:
_, pos, cost = query[i]
pos -= 1
if begin[pos] % 2 == 0:
even_bit.add(begin[pos] // 2, (end[pos] + 1) // 2, cost)
odd_bit.add(begin[pos] // 2, end[pos] // 2, -cost)
else:
odd_bit.add(begin[pos] // 2, end[pos] // 2, cost)
even_bit.add((begin[pos] + 1) // 2, end[pos] // 2, -cost)
else:
_, pos = query[i]
pos -= 1
if begin[pos] % 2 == 0:
ans = even_bit.get_val(begin[pos] // 2)
else:
ans = odd_bit.get_val(begin[pos] // 2)
print(ans + init_cost[pos])
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Fibonacci sequence $F_0, F_1, \ldots$ is a special infinite sequence of non-negative integers, where $F_0 = 0$, $F_1 = 1$ and for each integer $n \ge 2$, $F_n = F_{n-1} + F_{n-2}$.
Consider the sequence $D$ of the last decimal digits of the first $N$ Fibonacci numbers, i.e. $D = (F_0 \% 10, F_1 \% 10, \ldots, F_{N-1} \% 10)$. Now, you should perform the following process:
- Let $D = (D_1, D_2, \ldots, D_l)$.
- If $l = 1$, the process ends.
- Create a new sequence $E = (D_2, D_4, \ldots, D_{2 \lfloor l/2 \rfloor})$. In other words, $E$ is the sequence created by removing all odd-indexed elements from $D$.
- Change $D$ to $E$.
When this process terminates, the sequence $D$ contains only one number. You have to find this number.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer $N$.
-----Output-----
For each test case, print a single line containing one integer ― the last remaining number.
-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le N \le 10^{18}$
-----Subtasks-----
Subtask #1 (20 points):
- $1 \le T \le 10^5$
- $1 \le N \le 10^7$
Subtask #2 (80 points): original constraints
-----Example Input-----
1
9
-----Example Output-----
3
-----Explanation-----
Example case 1: The first $N$ Fibonacci numbers are $(0, 1, 1, 2, 3, 5, 8, 13, 21)$. The sequence $D$ is $(0, 1, 1, 2, 3, 5, 8, 3, 1) \rightarrow (1, 2, 5, 3) \rightarrow (2, 3) \rightarrow (3)$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
t = int(input())
a = [-1, 0, 1]
for i in range(58):
temp = a[-1] + a[-2]
temp = temp%10
a.append(temp)
for _ in range(t):
n = int(input())
temp = len(bin(n)) - 3
temp = 2**temp
temp = temp%60
print(a[temp])
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) — the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer — the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
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()
p = [i for i in s.split("0") if i!=""]
p.sort(reverse=True)
ans = 0
for i in range(0,len(p),2):
ans+=len(p[i])
print(ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a_1 × b_1 segments large and the second one is a_2 × b_2 segments large.
Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares.
To make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following: he either breaks one bar exactly in half (vertically or horizontally) and eats exactly a half of the bar, or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar.
In the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar.
Both variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is 16 × 23, then Polycarpus can chip off a half, but not a third. If the bar is 20 × 18, then Polycarpus can chip off both a half and a third. If the bar is 5 × 7, then Polycarpus cannot chip off a half nor a third.
What is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process.
-----Input-----
The first line of the input contains integers a_1, b_1 (1 ≤ a_1, b_1 ≤ 10^9) — the initial sizes of the first chocolate bar. The second line of the input contains integers a_2, b_2 (1 ≤ a_2, b_2 ≤ 10^9) — the initial sizes of the second bar.
You can use the data of type int64 (in Pascal), long long (in С++), long (in Java) to process large integers (exceeding 2^31 - 1).
-----Output-----
In the first line print m — the sought minimum number of minutes. In the second and third line print the possible sizes of the bars after they are leveled in m minutes. Print the sizes using the format identical to the input format. Print the sizes (the numbers in the printed pairs) in any order. The second line must correspond to the first bar and the third line must correspond to the second bar. If there are multiple solutions, print any of them.
If there is no solution, print a single line with integer -1.
-----Examples-----
Input
2 6
2 3
Output
1
1 6
2 3
Input
36 5
10 16
Output
3
16 5
5 16
Input
3 5
2 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
a,b=list(map(int,input().split()))
c,d=list(map(int,input().split()))
e=a*b
f=c*d
n=0
while e%2==0:e=e//2
while e%3==0:e=e//3
while f%2==0:f=f//2
while f%3==0:f=f//3
if e!=f:print("-1")
else:
i=0
j=0
e=a*b
f=c*d
while e%3==0:
e=e//3
i+=1
while f%3==0:
f=f//3
j+=1
k=i-j
if k>0:
for i in range(k):
n+=1
if a%3==0:a=a*2//3
else:b=b*2//3
else:
for i in range(0-k):
n+=1
if c%3==0:c=c*2//3
else:d=d*2//3
e=a*b
f=c*d
i=0
j=0
while e%2==0:
e=e//2
i+=1
while f%2==0:
f=f//2
j+=1
k=i-j
if k>0:
for i in range(k):
n+=1
if a%2==0:a=a//2
else:b=b//2
else:
for i in range(0-k):
n+=1
if c%2==0:c=c//2
else:d=d//2
print(n)
print(a,b)
print(c,d)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a grid of size N x M consisting of '.' (empty), 'W' (white) or 'B' (black) cells. We follow the convention that the top left corner is the position (1,1) and bottom right corner is (N,M).
From every '.' cell (i, j), a ray is shot towards the right. If the ray reaches a 'B' cell, it loses it's strength fully and stops there. When a ray
reaches a 'W' cell, it's strength drops drastically so that the ray stops when it reaches a second 'W' cell. That is, if there is no 'B'
cell in between, a ray can cross at most one 'W' cell, and it will stop when it reaches the second 'W' cell. It passes unchanged through any '.' cell. If it reaches a boundary cell (ie. (i,M), for some i), it stops there.
Let L(i, j) be length travelled by the ray starting from the cell (i, j). If (i,j) is 'W' or 'B', no ray starts from here, and hence L(i,j) is defined to be 0. If a ray starts from (i,j) and stops at (i,k), then the distance travelled by this ray is k-j+1. i.e, inclusive of both starting and ending cells.
For the given grid your task is to find the sum of L(i, j) over all 1 <= i <= N and 1 <= j <= M.
The description of the grid is given as follows: In addition to N and M, you are given the number of 'W' cells (w) and the number of 'B' cells (b)
and you are given the locations of these w + b cells. (The other cells contain '.')
-----Constraints:-----
For all testcases,
- 1 <= N, M <= 10^6.
- 0 <= w,b <= 10^5
Subtask 1: 15%
It is guaranteed that 1 <= N,M <= 500
Subtask 2: 25%
It is guaranteed that 1 <= N,M <= 2000
Subtask 3: 60%
No additional guarantees.
-----Input format:-----
- There is only one line of input which contains 4 + 2w + 2b space separated integers. The first four integers are N, M, w and b.
- The next 2*w integers denote the cells which contains a 'W': x1 y1 x2 y2 .. xw yw. These denote that (xi,yi) contains 'W'.
- The next 2*b integers denote the cells which contains a 'B': x1 y1 x2 y2 .. xb yb. These denote that (xi,yi) contains 'B'.
- The cells which are not in the input have to be assumed to be '.'
-----Output format:-----
Output a single integer which is the sum of L(i,j) over all 1 <= i <= N and 1 <= j <= M.
-----Sample Input 1:-----
4 4 5 2 1 3 2 1 3 2 3 3 4 3 1 4 2 3
-----Sample Output 1:-----
22
-----Explanation:-----
The grid is:
. . W B
W . B .
. W W .
. . W .
L(i,j) for each cell is:
4 3 0 0
0 2 0 1
3 0 0 1
4 3 0 1
Therefore, the total is 22.
-----Note:-----
As the answer might be large, please use 64 bit integers (long long int in C/C++ and long in Java) instead of 32 bit int.
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 operator import itemgetter
inp=list(map(int, input().split()))
n, m, w, b = inp[:4]
stops=[]
for i in range(w):
stops.append((inp[4+2*i]-1,inp[5+2*i]-1,'w'))
for i in range(b):
stops.append((inp[4+2*w+2*i]-1,inp[5+2*w+2*i]-1,'b'))
stops.sort(key=itemgetter(1))
stops.sort(key=itemgetter(0))
counter=0
stop_rows=[[] for _ in range(n)]
for stop in stops:
stop_rows[stop[0]].append(stop[1:])
for row in stop_rows:
idx=0
for i in range(len(row)):
if idx==row[i][0]:
idx+=1
else:
if row[i][1]=='w':
if i<len(row)-1:
num=row[i+1][0]-idx+1
counter+=((num*(num+1))>>1)-1
idx=row[i][0]+1
num=row[i+1][0]-row[i][0]+1
counter-=((num*(num+1))>>1)-1
else:
num=m-idx
counter+=((num*(num+1))>>1)-1
idx=row[i][0]+1
num=m-row[i][0]
counter-=((num*(num+1))>>1)-1
else:
num=row[i][0]-idx+1
counter+=((num*(num+1))>>1)-1
idx=row[i][0]+1
num=m-idx
counter+=(num*(num+1))>>1
print(counter)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Sebi lives in Chefland where the government is extremely corrupt that usually makes fool out of public by announcing eye catching but non-sustainable schemes. Recently there was a move to increase tourism in the country that was highly lauded. Sebi wants to examine whether the move has some potential or is a hogwash as usual.
The Chefland is a city with very old road infrastructure. The city has N tourist places. All the places are reachable from each other. The corrupt administrators of the city constructed as few roads as possible just ensuring that all the places are reachable from each other, and those too have now gone old with potholes every here and there. Upon this, there is a toll tax for each road too, which you have to pay once for using that road. Once you pay the tax for a road, you can visit it again as many times as possible.
The tourists coming to Chefland usually want to see all the N nice places. They usually have visit in their own vehicle and stay for few days. Also, they are usually not very rich, they want to pay as less toll tax as possible. For promoting tourism, the government offered their citizens a scheme. It was announced that citizens can choose any two places and the government will build a high class road between those two places and that too without any toll tax. Note that citizens may choose to have a high class road between two cities which already have an old road between them.
Sebi is very sceptical of the claims of the announcement. So, he wants to understand the expected toll tax a tourist has to pay to tour the entire city considering that the citizens of Chefland vote for the two cities for constructing high road uniformly randomly. Can you please him in finding this?
-----Input-----
There is a single test case per test file.
The first line of the input contains an integer N denoting the number of tourist spots in Chefland.
Each of the he next N - 1 lines contains three space separated integers u, v, c, denoting that there is a road between tourist spot u and v which has a toll tax of c Rs.
-----Output-----
Output a single line containing the expected toll tax a tourist has to pay for visiting all the N spots after the construction of new road. Your answer will be considered correct if it has an absolute error less than or equal to 1e-2.
-----Constraints-----
- 2 ≤ N ≤ 105
- 1 ≤ u, v ≤ N
- 0 ≤ c ≤ 106
-----Example-----
Input:
3
1 2 3
1 3 2
Output:
2.333333
-----Explanation-----
Assume that the citizens construct the high class road between city 1 and 2. A tourist can visit all the places by just paying a toll tax of 2 Rs.
If the high class road is constructed between city 1 and 3. All the places then can be visited by just paying a toll tax of 3 Rs.
If the cities 2 and 3 are connected by the high class road. All the places can be visited by paying a toll tax of 2Rs.
Hence expected Rs. that a tourist has to pay in toll tax will be (2 + 3 + 2) / 3 = 7 / 3 = 2.333333
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from sys import stdin,stdout
total_cost=0
def find(a):
if par[a]==a:
return a
else:
par[a]=find(par[a])
return par[a]
def union(a,b,c):
a,b=find(a),find(b)
nonlocal total_cost
total_cost+=(rank[a]*rank[b]*c)
if a!=b:
if rank[a]>rank[b]:
par[b]=a
rank[a]+=rank[b]
elif rank[b]>rank[a]:
par[a]=b
rank[b]+=rank[a]
else:
par[a]=b;
rank[b]+=rank[a]
n=int(stdin.readline().strip())
par=[i for i in range(n)]
rank=[1 for i in range(n)]
edges=[]
for i in range(n-1):
u,v,c=stdin.readline().strip().split(' ')
u,v,c=int(u)-1,int(v)-1,int(c)
edges.append((c,u,v))
edges.sort()
tw=0
for i in edges:
union(i[1],i[2],i[0])
tw+=i[0]
stdout.write(str(tw-(total_cost/((n*(n-1))/2))))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ram and Shyam are sitting next to each other, hoping to cheat on an exam. However, the examination board has prepared $p$ different sets of questions (numbered $0$ through $p-1$), which will be distributed to the students in the following way:
- The students are assigned roll numbers — pairwise distinct positive integers.
- If a student's roll number is $r$, this student gets the $((r-1)\%p)$-th set of questions.
Obviously, Ram and Shyam can cheat only if they get the same set of questions.
You are given the roll numbers of Ram and Shyam: $A$ and $B$ respectively. Find the number of values of $p$ for which they can cheat, or determine that there is an infinite number of such values.
-----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 $B$.
-----Output-----
For each test case, print a single line — the number of values of $p$ for which Ram and Shyam can cheat, or $-1$ if there is an infinite number of such values.
-----Constraints-----
- $1 \le T \le 100$
- $1 \le A, B \le 10^8$
-----Example Input-----
1
2 6
-----Example Output-----
3
-----Explanation-----
Example case 1: They can cheat for $p = 1$, $p = 2$ or $p = 4$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
for test in range(0,int(input())):
A,B = map(int,input().split())
diff = abs(A-B)
count=0
if not(A^B):
print(-1)
else:
for i in range(1,int(diff**(1/2))+1):
if diff%i==0:
if diff/i==i:
count+=1
else:
count+=2
print(count)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You may have helped Chef and prevented Doof from destroying the even numbers. But, it has only angered Dr Doof even further. However, for his next plan, he needs some time. Therefore, Doof has built $N$ walls to prevent Chef from interrupting him. You have to help Chef by telling him the number of walls he needs to destroy in order to reach Dr Doof.
Formally, the whole area can be represented as the first quadrant with the origin at the bottom-left corner. Dr. Doof is located at the origin $(0, 0)$. There are $N$ walls, the i-th wall is a straight line segment joining the points $(a_i, 0)$ and $(0, a_i)$. For every initial position of Chef $(x_j, y_j)$, find the number of walls he needs to break before reaching Doof. Obviously, chef can't start from a point on the wall. Therefore, if $(x_j, y_j)$ lies on any of the given walls, print $-1$ in a new line.
-----Input-----
- First line contains $T$, denoting the number of testcases.
- The first line of every test case contains a single integer $N$ denoting the number of walls Dr Doof has built.
- The next line contains $N$ space separated distinct integers each denoting $a_i$.
- The next line contains a single integer $Q$ denoting the number of times Chef asks for your help.
- The next $Q$ lines contains two space separated integers $x_j$ and $y_j$, each denoting the co-ordinates of the starting point of Chef.
-----Output-----
For each query, print the number of walls Chef needs to break in order to reach Dr Doof in a separate line. If Chef tries to start from a point on any of the walls, print $-1$.
-----Constraints-----
- $1 \leq T \leq 2 * 10^2$
- $1 \leq N, Q \leq 2 * 10^5$
- $1 \leq a_i \leq 10^9$
- $0 \leq x_j, y_j \leq 10^9$
- $a_1 < a_2 < a_3 < .... < a_N$
- Sum of $N$ and $Q$ over all testcases for a particular test file does not exceed $2 * 10^5$
-----Sample Input-----
1
2
1 3
5
0 0
2 0
0 4
1 1
1 2
-----Sample Output-----
0
1
2
1
-1
-----Explanation-----
The sample input can be represented by the graph given below:
If Chef starts from $(0, 0)$, he can reach Dr Doof without destroying any wall.
If Chef starts from $(2, 0)$, he has to destroy the $1st$ wall.
If Chef starts from $(0, 4)$, he has to destroy both the walls.
If Chef starts from $(1, 1)$, he has to destroy the $1st$ wall.
As $(1, 2)$ lies on the second wall, the answer is $-1$ for the last query.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def posSearch(arr, num):
l = 0
r = len(arr)
if num < arr[l]:
return 0
elif num > arr[r-1]:
return r
while l < r:
m = (l+r)//2
if arr[m] == num:
return -1
if arr[m] < num < arr[m+1]:
return m+1
if arr[m] > num:
r = m
elif arr[m] < num:
l = m+1
for _ in range(int(input())):
n = int(input())
narr = list(map(int, input().split()))
q = int(input())
for i in range(q):
x, y = list(map(int, input().split()))
a = x+y
j = posSearch(narr, a)
print(j)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
For her next karate demonstration, Ada will break some bricks.
Ada stacked three bricks on top of each other. Initially, their widths (from top to bottom) are $W_1, W_2, W_3$.
Ada's strength is $S$. Whenever she hits a stack of bricks, consider the largest $k \ge 0$ such that the sum of widths of the topmost $k$ bricks does not exceed $S$; the topmost $k$ bricks break and are removed from the stack. Before each hit, Ada may also decide to reverse the current stack of bricks, with no cost.
Find the minimum number of hits Ada needs in order to break all bricks if she performs the reversals optimally. You are not required to minimise the number of reversals.
-----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 four space-separated integers $S$, $W_1$, $W_2$ and $W_3$.
-----Output-----
For each test case, print a single line containing one integer ― the minimum required number of hits.
-----Constraints-----
- $1 \le T \le 64$
- $1 \le S \le 8$
- $1 \le W_i \le 2$ for each valid $i$
- it is guaranteed that Ada can break all bricks
-----Subtasks-----
Subtask #1 (50 points): $W_1 = W_2 = W_3$
Subtask #2 (50 points): original constraints
-----Example Input-----
3
3 1 2 2
2 1 1 1
3 2 2 1
-----Example Output-----
2
2
2
-----Explanation-----
Example case 1: Ada can reverse the stack and then hit it two times. Before the first hit, the widths of bricks in the stack (from top to bottom) are $(2,2,1)$. After the first hit, the topmost brick breaks and the stack becomes $(2,1)$. The second hit breaks both remaining bricks.
In this particular case, it is also possible to hit the stack two times without reversing. Before the first hit, it is $(1, 2, 2)$. The first hit breaks the two bricks at the top (so the stack becomes $(2)$) and the second hit breaks the last brick.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t=int(input())
for i in range(t):
n,w1,w2,w3=map(int,input().split())
if n>=w1+w2+w3:
print(1)
elif n>=w1+w2 or n>=w2+w3:
print(2)
else:
print(3)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a picture consisting of $n$ rows and $m$ columns. Rows are numbered from $1$ to $n$ from the top to the bottom, columns are numbered from $1$ to $m$ from the left to the right. Each cell is painted either black or white.
You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $x$ and $y$, where $1 \le x \le n$ and $1 \le y \le m$, such that all cells in row $x$ and all cells in column $y$ are painted black.
For examples, each of these pictures contain crosses:
[Image]
The fourth picture contains 4 crosses: at $(1, 3)$, $(1, 5)$, $(3, 3)$ and $(3, 5)$.
Following images don't contain crosses:
[Image]
You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.
What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?
You are also asked to answer multiple independent queries.
-----Input-----
The first line contains an integer $q$ ($1 \le q \le 5 \cdot 10^4$) — the number of queries.
The first line of each query contains two integers $n$ and $m$ ($1 \le n, m \le 5 \cdot 10^4$, $n \cdot m \le 4 \cdot 10^5$) — the number of rows and the number of columns in the picture.
Each of the next $n$ lines contains $m$ characters — '.' if the cell is painted white and '*' if the cell is painted black.
It is guaranteed that $\sum n \le 5 \cdot 10^4$ and $\sum n \cdot m \le 4 \cdot 10^5$.
-----Output-----
Print $q$ lines, the $i$-th line should contain a single integer — the answer to the $i$-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.
-----Example-----
Input
9
5 5
..*..
..*..
*****
..*..
..*..
3 4
****
.*..
.*..
4 3
***
*..
*..
*..
5 5
*****
*.*.*
*****
..*.*
..***
1 4
****
5 5
.....
..*..
.***.
..*..
.....
5 3
...
.*.
.*.
***
.*.
3 3
.*.
*.*
.*.
4 4
*.**
....
*.**
*.**
Output
0
0
0
0
0
4
1
1
2
-----Note-----
The example contains all the pictures from above in the same order.
The first 5 pictures already contain a cross, thus you don't have to paint anything.
You can paint $(1, 3)$, $(3, 1)$, $(5, 3)$ and $(3, 5)$ on the $6$-th picture to get a cross in $(3, 3)$. That'll take you $4$ minutes.
You can paint $(1, 2)$ on the $7$-th picture to get a cross in $(4, 2)$.
You can paint $(2, 2)$ on the $8$-th picture to get a cross in $(2, 2)$. You can, for example, paint $(1, 3)$, $(3, 1)$ and $(3, 3)$ to get a cross in $(3, 3)$ but that will take you $3$ minutes instead of $1$.
There are 9 possible crosses you can get in minimum time on the $9$-th picture. One of them is in $(1, 1)$: paint $(1, 2)$ and $(2, 1)$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
q = int(sys.stdin.readline().strip())
for t in range(0, q):
n, m = list(map(int, sys.stdin.readline().strip().split()))
L = []
R = [0] * n
C = [0] * m
for i in range (0, n):
L.append(sys.stdin.readline().strip())
for j in range (0, m):
if L[i][j] != "*":
R[i] = R[i] + 1
C[j] = C[j] + 1
ans = n + m - 1
for i in range (0, n):
for j in range (0, m):
x = 0
if L[i][j] != "*":
x = -1
ans = min([ans, R[i]+C[j]+x])
print(ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has recently learned about number bases and is becoming fascinated.
Chef learned that for bases greater than ten, new digit symbols need to be introduced, and that the convention is to use the first few letters of the English alphabet. For example, in base 16, the digits are 0123456789ABCDEF. Chef thought that this is unsustainable; the English alphabet only has 26 letters, so this scheme can only work up to base 36. But this is no problem for Chef, because Chef is very creative and can just invent new digit symbols when she needs them. (Chef is very creative.)
Chef also noticed that in base two, all positive integers start with the digit 1! However, this is the only base where this is true. So naturally, Chef wonders: Given some integer N, how many bases b are there such that the base-b representation of N starts with a 1?
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of one line containing a single integer N (in base ten).
-----Output-----
For each test case, output a single line containing the number of bases b, or INFINITY if there are an infinite number of them.
-----Constraints-----
-----Subtasks-----Subtask #1 (16 points):
- 1 ≤ T ≤ 103
- 0 ≤ N < 103
Subtask #2 (24 points):
- 1 ≤ T ≤ 103
- 0 ≤ N < 106
Subtask #3 (28 points):
- 1 ≤ T ≤ 103
- 0 ≤ N < 1012
Subtask #4 (32 points):
- 1 ≤ T ≤ 105
- 0 ≤ N < 1012
-----Example-----
Input:4
6
9
11
24
Output:4
7
8
14
-----Explanation-----
In the first test case, 6 has a leading digit 1 in bases 2, 4, 5 and 6: 610 = 1102 = 124 = 115 = 106.
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 finder(n):
cnt=0
for i in range(2,n+1):
a=n
while a!=0:
r=a%i
a=a//i
if r==1:
cnt+=1
return cnt
t=int(input())
for _ in range(t):
n=int(input())
if n==0:
print(0)
elif n==1:
print('INFINITY')
else:
print(finder(n))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
$n$ boys and $m$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $1$ to $n$ and all girls are numbered with integers from $1$ to $m$. For all $1 \leq i \leq n$ the minimal number of sweets, which $i$-th boy presented to some girl is equal to $b_i$ and for all $1 \leq j \leq m$ the maximal number of sweets, which $j$-th girl received from some boy is equal to $g_j$.
More formally, let $a_{i,j}$ be the number of sweets which the $i$-th boy give to the $j$-th girl. Then $b_i$ is equal exactly to the minimum among values $a_{i,1}, a_{i,2}, \ldots, a_{i,m}$ and $g_j$ is equal exactly to the maximum among values $b_{1,j}, b_{2,j}, \ldots, b_{n,j}$.
You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $a_{i,j}$ for all $(i,j)$ such that $1 \leq i \leq n$ and $1 \leq j \leq m$. You are given the numbers $b_1, \ldots, b_n$ and $g_1, \ldots, g_m$, determine this number.
-----Input-----
The first line contains two integers $n$ and $m$, separated with space — the number of boys and girls, respectively ($2 \leq n, m \leq 100\,000$). The second line contains $n$ integers $b_1, \ldots, b_n$, separated by spaces — $b_i$ is equal to the minimal number of sweets, which $i$-th boy presented to some girl ($0 \leq b_i \leq 10^8$). The third line contains $m$ integers $g_1, \ldots, g_m$, separated by spaces — $g_j$ is equal to the maximal number of sweets, which $j$-th girl received from some boy ($0 \leq g_j \leq 10^8$).
-----Output-----
If the described situation is impossible, print $-1$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
-----Examples-----
Input
3 2
1 2 1
3 4
Output
12
Input
2 2
0 1
1 0
Output
-1
Input
2 3
1 0
1 1 2
Output
4
-----Note-----
In the first test, the minimal total number of sweets, which boys could have presented is equal to $12$. This can be possible, for example, if the first boy presented $1$ and $4$ sweets, the second boy presented $3$ and $2$ sweets and the third boy presented $1$ and $1$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $12$.
In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.
In the third test, the minimal total number of sweets, which boys could have presented is equal to $4$. This can be possible, for example, if the first boy presented $1$, $1$, $2$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $4$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,m=map(int,input().split())
b=list(map(int,input().split()))
g=list(map(int,input().split()))
if max(b)>min(g):
print(-1)
else:
maxi=0
maxi2=0
for guy in b:
if guy>maxi:
maxi2,maxi=maxi,guy
elif guy>maxi2:
maxi2=guy
sumi=m*sum(b)+sum(g)-m*maxi+maxi-maxi2
if maxi in g:
sumi-=(maxi-maxi2)
print(sumi)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Little Elephant from the Zoo of Lviv currently is on the military mission. There are N enemy buildings placed in a row and numbered from left to right strating from 0. Each building i (except the first and the last) has exactly two adjacent buildings with indices i-1 and i+1. The first and the last buildings have just a single adjacent building.
Some of the buildings contain bombs. When bomb explodes in some building it destroys it and all adjacent to it buildings.
You are given the string S of length N, where Si is 1 if the i-th building contains bomb, 0 otherwise. Find for the Little Elephant the number of buildings that will not be destroyed after all bombs explode. Please note that all bombs explode simultaneously.
-----Input-----
The first line contains single integer T - the number of test cases. T test cases follow. The first line of each test case contains the single integer N - the number of buildings. The next line contains the string S of length N consisted only of digits 0 and 1.
-----Output-----
In T lines print T inetgers - the answers for the corresponding test cases.
-----Constraints-----
1 <= T <= 100
1 <= N <= 1000
-----Example-----
Input:
3
3
010
5
10001
7
0000000
Output:
0
1
7
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
T = int(sys.stdin.readline().strip())
for t in range(T):
sys.stdin.readline().strip()
st = '0'+sys.stdin.readline().strip()+'0'
res = 0
for i in range(1,len(st)-1):
if st[i] == st[i-1] == st[i+1] == '0':
res+=1
print(res)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Indraneel's student has given him data from two sets of experiments that the student has performed. Indraneel wants to establish a correlation between the two sets of data. Each data set is a sequence of $N$ numbers. The two data sets do not match number for number, but Indraneel believes that this is because data has been shifted due to inexact tuning of the equipment.
For example, consider the following two sequences:
$ $
3 8 4 23 9 11 28
2 3 22 26 8 16 12
$ $
Indraneel observes that if we consider the subsequences $3,4,23,9$ and $2,3,22,8$ and examine their successive differences we get $1,19,-14$. He considers these two subsequences to be "identical". He would like to find the longest such pair of subsequences so that the successive differences are identical. Your task is to help him do this.
-----Input:-----
The first line of the input will contain a single integer $N$ indicating the number of data points in each of Indraneel's student's data sets. This is followed by two lines, each containing $N$ integers.
-----Output:-----
The output consists of three lines. The first line of output contains a single integer indicating the length of the longest pair of subsequences (one from each sequence) that has identical successive differences. This is followed by two lines each containing the corresponding subsequences. If there is more than one answer, it suffices to print one.
-----Constraints:-----
- $1 \leq N \leq 150$.
- $0 \leq$ Each data point $\leq 1000$
-----Sample Input-----
7
3 8 4 23 9 11 28
2 3 22 26 8 16 12
-----Sample Output-----
4
3 4 23 9
2 3 22 8
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import copy
n=int(input())
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
c=[]
d=[]
lcs=[]
def lcsfn(a,c,corda,cordb):
for i in range(n+1):
d.append([0]*(n+1))
lcs.append([0]*(n+1))
for i in range(1,n+1):
for j in range(1,n+1):
if a[i-1]==c[j-1]:
lcs[i][j]=lcs[i-1][j-1]+1
d[i][j]='d'
elif lcs[i-1][j]>lcs[i][j-1]:
lcs[i][j]=lcs[i-1][j]
d[i][j]='u'
else:
lcs[i][j]=lcs[i][j-1]
d[i][j]='l'
i=n
j=n
cost=0
while i>=1 and j>=1:
if d[i][j]=='d':
corda.append(a[i-1])
cordb.append(b[j-1])
i-=1
j-=1
cost+=1
elif d[i][j]=='l':
j-=1
elif d[i][j]=='u':
i-=1
return cost
ma=-10**9
p1=[]
p2=[]
for i in range(-1000,1001):
c=[]
corda=[]
cordb=[]
for j in range(n):
c.append(b[j]+i)
p=lcsfn(a,c,corda,cordb)
if ma<p:
ma=p
p1=copy.deepcopy(corda)
p1=p1[::-1]
p2=copy.deepcopy(cordb)
p2=p2[::-1]
print(ma)
print(*p1)
print(*p2)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
In poker, you have 5 cards. There are 10 kinds of poker hands (from highest to lowest):
- royal flush - ace, king, queen, jack and ten, all in the same suit
- straight flush - five cards of the same suit in sequence, such
as 10,9,8,7,6 of clubs; ace can be counted both as the highest card or as the
lowest card - A,2,3,4,5 of hearts is a straight flush. But 4,3,2,A,K of hearts is not a straight flush - it's just a flush.
- four of a kind - four cards of the same rank, such as four kings.
- full house - three cards of one rank plus two cards of another rank
- flush - five cards of the same suit (but not a straight flush)
- straight - five cards in order - just like the straight flush, but mixed suits
- three of a kind - three cards of one rank and two other cards
- two pairs - two cards of one rank, two cards of another rank, and one more card
- pair - two cards of the same rank
- high card - none of the above
Write a program that will help you play poker by telling you what kind of hand you have.
-----Input-----
The first line of input contains the number of test cases (no more than 20). Each test case consists of one line - five space separated cards. Each card is represented by a two-letter (or digit) word. The first character is the rank (A,K,Q,J,T,9,8,7,6,5,4,3 or 2), the second character is the suit (S,H,D,C standing for spades, hearts, diamonds and clubs). The cards can be in any order (but they will not repeat).
-----Output-----
For each test case output one line describing the type of a hand, exactly like in the list above.
-----Example-----
Input:
3
AH KH QH TH JH
KH 5S 3C 5C 7D
QH QD 2S QC 2C
Output:
royal flush
pair
full house
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
cards = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']
def royal_flush(arr):
nonlocal ans, confirm
rf_set = 'TJQKA'
rf = 1
for char in arr:
if char[0] not in rf_set:
rf = 0
break
if rf :
if len(set(suit)) == 1:
ans = 'royal flush'
confirm = 1
def straight_flush(arr): # and 'straight'
nonlocal ans,confirm
sf = 1
for i in range(1,5):
if arr[i] - arr[i-1] != 1:
sf = 0
break
if sf:
if len(set(suit)) == 1 :
ans = 'straight flush'
confirm = 1
else:
ans = 'straight'
confirm = 1
def four(arr):
nonlocal ans, confirm
f = 0
for char in arr:
if arr.count(char) == 4:
f = 1
break
if f:
confirm = 1
ans = 'four of a kind'
def full_house(arr): # and three
nonlocal ans, confirm
fh = 0
three = 0
two = 0
for char in arr:
if arr.count(char) == 3:
three = 1
elif arr.count(char) == 2:
two = 1
if three and two:
confirm = 1
ans = 'full house'
elif three:
confirm = 1
ans = 'three of a kind'
def two_pairs(arr):
nonlocal ans, confirm
temp = []
for char in arr:
if arr.count(char) == 2:
if char not in temp:
temp.append(char)
if len(temp) == 2:
confirm = 1
ans = 'two pairs'
elif len(temp) == 1:
confirm = 1
ans = 'pair'
def idex(char_x):
return cards.index(char_x)
for _ in range(int(input())):
onhand = list(input().split())
cards_set = [[],[]]
suit = []
confirm = 0
ans = ''
for c in onhand:
num = idex(c[0])
cards_set[0].append(num)
if num == 0:
cards_set[1].append(13)
else:
cards_set[1].append(num)
suit.append(c[1])
royal_flush(onhand)
if not confirm:
cards_set[0] = sorted(cards_set[0])
cards_set[1] = sorted(cards_set[1])
straight_flush(cards_set[0])
straight_flush(cards_set[1])
if not confirm:
four(cards_set[0])
four(cards_set[1])
if not confirm:
full_house(cards_set[0])
full_house(cards_set[1])
if not confirm:
if len(set(suit)) == 1:
confirm = 1
ans = 'flush'
if not confirm:
two_pairs(cards_set[0])
two_pairs(cards_set[1])
print(ans if confirm else 'high card')
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.
For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the k-rounding of n.
-----Input-----
The only line contains two integers n and k (1 ≤ n ≤ 10^9, 0 ≤ k ≤ 8).
-----Output-----
Print the k-rounding of n.
-----Examples-----
Input
375 4
Output
30000
Input
10000 1
Output
10000
Input
38101 0
Output
38101
Input
123456789 8
Output
12345678900000000
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
n, k = map(int, input().split())
num_2 = 0
num_5 = 0
x = n
while (x % 2 == 0):
num_2 += 1
x //= 2
while (x % 5 == 0):
num_5 += 1
x //= 5
num_2 = k - min(num_2, k)
num_5 = k - min(num_5, k)
print(n * 5 ** num_5 * 2 ** num_2)
main()
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be $\frac{n(n + 1)}{2}$ of them.
You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis.
Find the minimal number of layers you have to use for the given N.
-----Input-----
The only input line contains a single integer N (1 ≤ N ≤ 100).
-----Output-----
Output a single integer - the minimal number of layers required to draw the segments for the given N.
-----Examples-----
Input
2
Output
2
Input
3
Output
4
Input
4
Output
6
-----Note-----
As an example, here are the segments and their optimal arrangement into layers for N = 4. [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())
print(max((i+1)*(n-i)for i in range(n)))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ripul was skilled in the art of lapidary. He used to collect stones and convert it into decorative items for sale. There were n stone shops. Each shop was having one exclusive stone of value s[i] , where 1<=i<=n. If number of stones collected are more than 1, then total value will be product of values of all the stones he collected. Ripul wants to have maximum value of stones he collected. Help Ripul in picking up the subarray which leads to maximum value of stones he collected.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each testcase contains an integer $N$, denoting number of elements in the given array.
- The second line contains $N$ space-separated integers $S1$, $S2$, …, $SN$ denoting the value of stone in each shop.
-----Output:-----
For each testcase, output the maximum value of stones possible, the starting index and ending index of the chosen subarray (0-based indexing). If there are multiple subarrays with same value, print the one with greater starting index. If there are multiple answer subarrays with same starting index, print the one with greater ending index. (The answer will fit in 64 bit binary number).
-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $-100 \leq S[i] \leq 100$
-----Subtasks-----
- 30 points : $1 \leq N \leq 10^3$
- 70 points : $1 \leq N \leq 10^5$
-----Sample Input:-----
1
3
1 2 3
-----Sample Output:-----
6 1 2
-----EXPLANATION:-----
If Ripul collects all the all the three gems, total value will be 6 (1 * 2 * 3).
If Ripul collects last two gems, total value will be 6 (1 * 2 * 3).
So, he picks the subarray with greater starting index.
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=int(input())
l=list(map(int,input().split()))
d=[]
dd=[]
s=1
for i in range(n-1):
s=l[i]
d.append(s)
dd.append([i,i])
for j in range(i+1,n):
s=s*l[j]
d.append(s)
dd.append([i,j])
d.append(l[n-1])
dd.append([n-1,n-1])
k=len(d)
m=max(d)
x,y=0,0
for i in range(k):
if(d[i]==m):
x=dd[i]
print(m,*x)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
-----Input-----
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer k_{i} (0 ≤ k_{i} ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains k_{i} integers — a_{ij} (1 ≤ a_{ij} ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
-----Output-----
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
-----Examples-----
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
-----Note-----
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
rd = lambda: list(map(int, input().split()))
def root(x):
if f[x]!=x: f[x] = root(f[x])
return f[x]
n, m = rd()
N = list(range(n))
f = list(N)
lang = [0]*n
for i in N: lang[i] = set(rd()[1:])
for i in N:
for j in N[:i]:
rj = root(j)
if lang[rj].intersection(lang[i]):
f[rj] = i
lang[i] = lang[i].union(lang[rj])
print(sum(1 for i in N if i==root(i)) - (sum(map(len, lang))>0))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Teacher Sungjae wanted to hold a programming competition for his students where every participant need to be included into team. The participants submitted their team names before the deadline. After the competition ran for half an hour, (It is assured that each registered team will submit absolutely once within half an hour) Sungjae mistakenly pressed a button that changed the order of the registered team names. Now in the submission list, order of the characters in the team's name doesn't matter. That means $abc$, $acb$, $bac$, $bca$, $cab$, $cba$ refers to the same team. The competition ran for two hours and then ended. Sungjae now counting each of the team's score and wants to print the registered team names and score. The scoreboard should be ordered based on scores in decreasing order and if two teams have same score, Sangjae would follow lexicographical order.
$N$.$B$. frequency of each character's in a registered team's name will not match with another team.
That means two teams named $xoxo$ and $oxox$ is not possible. Because both of them have the same frequency of each of the characters (two 'o' and two 'x'). Similarly $abb$ and $bab$ is not possible (because both of them have one 'a' and two 'b').
It is ensured that only possible test cases will be given.
-----Input:-----Input:
-
First line will contain $T$, number of testcases. Then the testcases follow.
-
The first line of each test case contains two integers , $N$ and $R$ - total number of submissions and the number of submissions within first half an hour.
-
Then $R$ lines follow: the i'th line contains a string $ti$, registered names of the teams and an integer $pi$, points they got on that submission.
-
Then $N-R$ lines follow: the i-th line contains a string $ti$- the i-th team's name (in any order) in lowercase letter only and $pi$ -points they got on that submission.
-----Output:-----Output:
For each testcase,print the scoreboard.
That means print the teams name and their point according to their score in decreasing order and if some of them have same score,print the teams name in lexicographical order
-----Constraints-----Constraints
- $1 \leq T \leq 10$
- $1 \leq R \leq N \leq 1000$
- $1 \leq ti \leq 1000$
- $1 \leq pi \leq 10^6$
Sum of points ($pi$) of a team will not cross $10^9$.
-----Sample Input:-----Sample Input:
1
10 5
amigoes 1
bannermen 1
monarchy 4
outliers 5
iniciador 10
aegimos 2
iiiacdnor 1
eilorstu 1
gimosae 3
mnachroy 7
-----Sample Output:-----Sample Output:
iniciador 11
monarchy 11
amigoes 6
outliers 6
bannermen 1
-----Explanation:-----Explanation:
$It$ $is$ $assured$ $that$ $each$ $team$ $will$ $submit$ $once$ $within$ $first$ $half$ $an$ $hour$.That means -
that kind of submissions isn't possible within first half an hour.
Dataset can be huge. Use faster I/O method.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
for t in range(int(input())):
n,k=map(int,input().split())
a=[]
sr=[]
for i in range(k):
x,y=input().split()
y=int(y)
a.append([10**10-y,x])
sr.append(sorted(x))
for i in range(n-k):
x,y=input().split()
y=int(y)
x=sorted(x)
for j in range(k):
if x==sr[j]:
a[j][0]-=y
break
a.sort()
for i in a:
print(i[1],abs(i[0]-10**10))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Tom has finally taken over the business empire and now looking for
a new Name of the business to make a new start.
Joe (Tom's dear friend) suggested a string $S$ consisting of
Uppercase and lowercase letters
Tom wants to make some changes as per the following criteria:
1) String should $not$ have any vowels .
2) Every other uppercase consonant(other characters except vowels) should
be in lowercase
For ex:
If the consonant character is Z then it should be z
3) There should be a character "." before each consonant.
Help Tom to make the required Changes.
-----Input:-----
- First line will contain string $S$,This string only consists of uppercase and lowercase letters.
-----Output:-----
Print the resulting string. It is guaranteed that this string is not empty.
-----Constraints-----
- Length of string is in [1 .. 100]
-----Sample Input:-----
$CodeSprInT$
-----Sample Output:-----
.c.d.s.p.r.n.t
-----EXPLANATION:-----
C is a consonant and it is in uppercase so turn it in lower case and add a “.” before it
o is a vowel so it is deleted
d is a consonant and in lowercase so just add a “.” before it
e is a vowel so it is deleted
S is a consonant and it is in uppercase so turn it in lower case and add a “.” before it
p is a consonant and in lowercase so just add a “.” before it
r is a consonant and in lowercase so just add a “.” before it
I is a vowel so it is deleted
n is a consonant and in lowercase so just add a “.” before it
T is a consonant and it is in uppercase so turn it in lower case and add a “.” before it
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input().lower()
vow = ["a", "e", "i", "o", "u", "y"]
ans = ""
for ch in s:
if ch in vow:
continue
if ch.isalpha():
ans += "." + ch
print(ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given $N$ integers in an array: $A[1], A[2], \ldots, A[N]$. You also have another integer $L$.
Consider a sequence of indices ($i_1, i_2, \ldots, i_k$). Note that a particular index can occur multiple times in the sequence, and there is no order in which these indices have to occur. ($i_1, i_2, \ldots, i_k$) is a sequence of size $k$. It is said to be an $Interesting$ sequence, if $A[i_1] \ge A[i_2] \ge \ldots \ge A[i_k]$.
The $Cost$ of an Interesting sequence ($i_1, i_2, \ldots, i_k$), is defined to be the minimum absolute difference between any two adjacent indices. In other words, the Cost is $min \{ |i_2 - i_1|, |i_3 - i_2|, \ldots, |i_k - i_{k-1}| \}$.
Your job is to consider the Costs of all the Interesting sequences of size $L$ associated with the given array, and output the maximum Cost. Note that you can show that there is always at least one Interesting sequence for the given constraints.
-----Input-----
- The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows.
- The first line of each testcase contains two space separated integers: $N$ and $L$.
- The second line of each testcase contains $N$ space separated integers: $A[1], A[2], \ldots, A[N]$.
-----Output-----
- For each testcase, output the answer in a new line.
-----Constraints-----
- $1 \leq T \leq 3$
- $1 \leq A[i] \leq 10^9$
- $2 \leq L \leq 10^9$
-----Subtasks-----
- Subtask 1: 7 points
- It is guaranteed that $A[1] > A[2] > \ldots > A[N]$
- Note that the above condition implies that all elements are distinct.
- $1 \leq N \leq 500$
- Subtask 2: 7 points
- It is guaranteed that $A[1] \ge A[2] \ge \ldots \ge A[N]$
- $1 \leq N \leq 500$
- Subtask 3: 14 points
- It is guaranteed that all elements are distinct.
- $1 \leq N \leq 500$
- Subtask 4: 14 points
- $1 \leq N \leq 500$
- Subtask 5: 25 points
- It is guaranteed that all elements are distinct.
- $1 \leq N \leq 3000$
- Subtask 6: 33 points
- $1 \leq N \leq 3000$
-----Sample Input-----
1
6 3
2 4 1 12 3 5
-----Sample Output-----
3
-----Explanation-----
We are looking for Interesting sequences of length 3. Some of them are:
- (4, 2, 3): This is Interesting because $A[4] \ge A[2] \ge A[3]$. Its cost is $min \{ |2-4|, |3-2|\} = 1$.
- (5, 1, 1): Cost is 0.
- (2, 2, 2): Cost is 0.
- (6, 1, 3): Cost is 2.
- (6, 2, 5): Cost is 3.
There are other Interesting Sequences of length 3 as well. But if you list them all out, you'll see that the maximum Cost is 3. Hence the answer 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
# from queue import PriorityQueue
# import bisect
def insort(l, v):
s = 0
e = len(l)
while True:
mid = (s+e)//2
if s == e or mid > len(l):
break
if l[mid][0] < v[0]:
s = mid+1
elif l[mid][0] > v[0]:
e = mid
else:
break
l.insert(mid, v)
for _ in range(int(input())):
n,l = map(int, input().split())
a_l = list(map(int, input().split()))
dic = {}
dif = 0
for i,v in enumerate(a_l, start=1):
if v not in dic:
dic[v] = [i, i]
else:
dic[v][0] = min(dic[v][0], i)
dic[v][1] = max(dic[v][1], i)
dif = max(dif, dic[v][1]-dic[v][0])
ans = dif
if l <= len(set(a_l)):
i_l = [[v,i] for i,v in enumerate(a_l, start=1)]
i_l.sort(reverse=True)
dp = [[-1 for _ in range(l)] for _ in range(n)]
pq_l = [[] for _ in range(l)]
for i in range(1,n):
il = 1
dif_l = []
for j in range(i):
dif = abs(i_l[i][1]-i_l[j][1])
dif_l.append(dif)
dp[i][il] = max(dp[i][il], dif)
for il in range(2,min(l,i+1)):
for prev_max, ind in reversed(pq_l[il-1]):
if ind == i:
continue
if prev_max < dp[i][il]:
break
else:
dp[i][il] = max(dp[i][il], min(dif_l[ind], prev_max))
insort(pq_l[il], [dp[i][il], i])
# tmp = [v[0] for v in pq_l[il]]
# ind = bisect.bisect_right(tmp, dp[i][il])
# pq_l[il].insert(ind, [dp[i][il], i])
il = 1
insort(pq_l[il], [dp[i][il], i])
# tmp = [v[0] for v in pq_l[il]]
# ind = bisect.bisect_right(tmp, dp[i][il])
# pq_l[il].insert(ind, [dp[i][il], i])
# print(i, pq_l, dif_l)
# dp[i][1] = max(dp[i][1], dif)
# for il in range(2,l):
# if dp[j][il-1] == -1:
# break
# dp[i][il] = max(dp[i][il], min(dif, dp[j][il-1]))
ans = max(ans, dp[i][-1])
# print(dp)
# print(dic)
print(ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Given an integer $x$, find two non-negative integers $a$ and $b$ such that $(a \wedge b) + (a \vee b) = x$, where $\wedge$ is the bitwise AND operation and $\vee$ is the bitwise OR operation.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer $x$.
-----Output-----
If there is no valid pair $(a, b)$, print a single line containing the integer $-1$. Otherwise, print a single line containing two space-separated integers $a$ and $b$.
If there are multiple solutions, you may print any one of them.
-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le x \le 10^{18}$
-----Subtasks-----
Subtask #1 (30 points):
- $1 \le T \le 200$
- $1 \le x \le 200$
Subtask #2 (70 points): original constraints
-----Example Input-----
2
1
8
-----Example Output-----
0 1
5 3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
n=int(input())
for _ in range(n):
a=int(input())
if(a%2==0):
f=(a//2)-1
s=a-f
else:
f=(a//2)
s=a-f
print(f,s)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
-----Problem Statement-----
Write a program that accepts a number, n, and outputs the same.
-----Input-----
The only line contains a single integer.
-----Output-----
Output the answer in a single line.
-----Constraints-----
- 0 ≤ n ≤ 105
-----Sample Input-----
123
-----Sample Output-----
123
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
a = int(input())
print(a)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a permutation $p_1, p_2, \dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.
Find three indices $i$, $j$ and $k$ such that: $1 \le i < j < k \le n$; $p_i < p_j$ and $p_j > p_k$. Or say that there are no such indices.
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 200$) — the number of test cases.
Next $2T$ lines contain test cases — two lines per test case. The first line of each test case contains the single integer $n$ ($3 \le n \le 1000$) — the length of the permutation $p$.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$; $p_i \neq p_j$ if $i \neq j$) — the permutation $p$.
-----Output-----
For each test case: if there are such indices $i$, $j$ and $k$, print YES (case insensitive) and the indices themselves; if there are no such indices, print NO (case insensitive).
If there are multiple valid triples of indices, print any of them.
-----Example-----
Input
3
4
2 1 4 3
6
4 6 1 2 5 3
5
5 3 1 2 4
Output
YES
2 3 4
YES
3 5 6
NO
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import math
#from queue import *
import random
#sys.setrecursionlimit(int(1e6))
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inara():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(list(map(int,input().split())))
################################################################
############ ---- THE ACTUAL CODE STARTS BELOW ---- ############
t=inp()
for _ in range(t):
n=inp()
ara=inara()
ans=[]
for i in range(1,n-1):
if ara[i]>ara[i-1] and ara[i]>ara[i+1]:
ans.append(i)
ans.append(i+1)
ans.append(i+2)
break
if len(ans)==0:
print("NO")
else:
print("YES")
print(*ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Bhallaladeva was an evil king who ruled the kingdom of Maahishmati. He wanted to erect a 100ft golden statue of himself and he looted gold from several places for this. He even looted his own people, by using the following unfair strategy:
There are N houses in Maahishmati, and the ith house has Ai gold plates. Each gold plate costs exactly 1 Nimbda, which is the unit of currency in the kingdom of Maahishmati. Bhallaladeva would choose an integer K, and loots all the houses in several steps. In each step:
- He would choose a house i which hasn't been looted yet, pay the owner exactly Ai Nimbdas, and take away all the gold plates in that house (Hence, he also ends up looting this house).
- He would now choose atmost K houses which haven't been looted yet and take away all the gold plates from these houses without paying a single Nimbda (Yes, he takes all of them for free).
He repeats the above steps until all the N houses have been looted. Your task is to devise a strategy for Bhallaladeva to loot the houses in some order, so that the number of nimbdas he has to pay is minimium. You'll also be given multiple values of K (Q of them to be precise), and you need to find the minimum number of nimbdas for each of these values.
-----Input-----
The first line of input consists of a single integer N denoting the number of houses in Maahishmati. The second line of input consists of N space separated integers denoting A1, A2, ..., AN, where Ai denotes the number of gold plates in the ith house. The third line of input consists of a single integer Q denoting the number of values of K to follow. Each of the following Q lines consist of a single integer, where the value on the ith line denotes the value of K for the ith query.
-----Output-----
Output exactly Q integers on separate lines, where the output on the ith line denotes the answer for the ith value of K.
-----Constraints-----
- 1 ≤ N ≤ 105
- 1 ≤ Q ≤ 105
- 0 ≤ K ≤ N-1
- 1 ≤ Ai ≤ 104
-----Example-----
Input:
4
3 2 1 4
2
0
2
Output:
10
3
-----Explanation-----
For the first query, K = 0. Hence, Bhallaladeva cannot take gold plates from any of the houses for free. It will cost him 3 + 2 + 1 + 4 = 10 nimbdas.
For the second query, K = 2. In the first step Bhallaladeva can pay 2 nimbdas for gold plates in house number 2, and take the gold in houses 1 and 4 for free (Note that house 1 has 3 gold plates and house 4 has 4 gold plates). Now, he has looted houses 1, 2 & 4. Now in the second step, he loots house 3, by paying 1 nimbda. Hence, the total cost = 1 + 2 = 3. Note that there might be multiple ways to achieve the minimum cost, and we have explained only one of them.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
n = int(input())
a = sorted(map(int,input().split()))
l = [0]*n
for i in range(n):
l[i] = a[i] + l[i-1]
for q in range(int(input())):
print(l[int(math.ceil(float(n)/(int(input())+1)))-1])
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef recently saw the movie Matrix. He loved the movie overall but he didn't agree with some things in it. Particularly he didn't agree with the bald boy when he declared - There is no spoon. Being a chef, he understands the importance of the spoon and realizes that the universe can't survive without it. Furthermore, he is sure there is a spoon; he saw it in his kitchen this morning. So he has set out to prove the bald boy is wrong and find a spoon in the matrix. He has even obtained a digital map already. Can you help him?
Formally you're given a matrix of lowercase and uppercase Latin letters. Your job is to find out if the word "Spoon" occurs somewhere in the matrix or not. A word is said to be occurred in the matrix if it is presented in some row from left to right or in some column from top to bottom. Note that match performed has to be case insensitive.
-----Input-----
The first line of input contains a positive integer T, the number of test cases. After that T test cases follow. The first line of each test case contains two space separated integers R and C, the number of rows and the number of columns of the matrix M respectively. Thereafter R lines follow each containing C characters, the actual digital map itself.
-----Output-----
For each test case print one line. If a "Spoon" is found in Matrix, output "There is a spoon!" else output "There is indeed no spoon!" (Quotes only for clarity).
-----Constraints-----
1 ≤ T ≤ 100
1 ≤ R, C ≤ 100
-----Sample Input-----
3
3 6
abDefb
bSpoon
NIKHil
6 6
aaaaaa
ssssss
xuisdP
oooooo
ioowoo
bdylan
6 5
bdfhj
cacac
opqrs
ddddd
india
yucky
-----Sample Output-----
There is a spoon!
There is a spoon!
There is indeed no spoon!
-----Explanation-----
In the first test case, "Spoon" occurs in the second row. In the second test case, "spOon" occurs in the last column.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
spoon = [ "SPOON", "spoon" ]
def main():
try:
tc=int(input())
while tc>0:
tc=tc-1
[r,c] = input().split()
r=int(r)
c=int(c)
k=0
flag=0
matrix=[0]*r
i=0
while i<r:
matrix[i]=input()
i=i+1
#Check row wise
for m in matrix:
for s in m:
if s==spoon[0][k] or s==spoon[1][k]:
k=k+1
if k==5:
flag=1
k=0
break
else:
k=0
if flag==1:
print("There is a spoon!")
continue
#Check column wise
i=0
k=0
while i<c:
j=0
while j<r:
if matrix[j][i]==spoon[0][k] or matrix[j][i]==spoon[1][k]:
k=k+1
if k==5:
flag=1
k=0
break
else:
k=0
j=j+1
i=i+1
if flag==1:
print("There is a spoon!")
continue
print("There is indeed no spoon!")
except:
return 0
main()
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.
Ivan represent his array with increasing sequences with help of the following algorithm.
While there is at least one unused number in array Ivan repeats the following procedure: iterate through array from the left to the right; Ivan only looks at unused numbers on current iteration; if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down.
For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4].
Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of elements in Ivan's array.
The second line contains a sequence consisting of distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — Ivan's array.
-----Output-----
Print representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.
-----Examples-----
Input
5
1 3 2 5 4
Output
1 3 5
2 4
Input
4
4 3 2 1
Output
4
3
2
1
Input
4
10 30 50 101
Output
10 30 50 101
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())
from bisect import bisect_left
a = list(map(int, input().split()))
ss = []
ms = []
for i in range(n):
k = a[i]
ind = bisect_left(ms, -k)
if ind == len(ms):
ss.append([])
ms.append(0)
ss[ind].append(k)
ms[ind] = -k
for s in ss:
print(' '.join([str(i) for i in s]))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
-----Input-----
The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.
-----Output-----
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10^{ - 9}.
-----Examples-----
Input
2 2 2
Output
0.333333333333 0.333333333333 0.333333333333
Input
2 1 2
Output
0.150000000000 0.300000000000 0.550000000000
Input
1 1 3
Output
0.057142857143 0.657142857143 0.285714285714
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
r, s, p = list(map(int, input().split()))
dp = [[[0] * (p+1) for _ in range(s+1)] for _ in range(r+1)]
dp[r][s][p] = 1
def nCk(n, k):
if n <= k:
return 1
res = 1
for i in range(k):
res *= n-i
for i in range(k):
res //= (i+1)
return res
C = [nCk(i, 2) for i in range(r+s+p+1)]
for ri in range(r, -1, -1):
for si in range(s, -1, -1):
for pi in range(p, -1, -1):
t = ri * si + si * pi + pi * ri
if t == 0: continue
if ri > 0:
dp[ri-1][si][pi] += dp[ri][si][pi] * ri * pi / t
if si > 0:
dp[ri][si-1][pi] += dp[ri][si][pi] * ri * si / t
if pi > 0:
dp[ri][si][pi-1] += dp[ri][si][pi] * si * pi / t
r_sum = sum([dp[ri][0][0] for ri in range(r+1)])
s_sum = sum([dp[0][si][0] for si in range(s+1)])
p_sum = sum([dp[0][0][pi] for pi in range(p+1)])
print(r_sum, s_sum, p_sum)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Nobody knows, but $N$ frogs live in Chef's garden.
Now they are siting on the X-axis and want to speak to each other. One frog can send a message to another one if the distance between them is less or equal to $K$.
Chef knows all $P$ pairs of frogs, which want to send messages. Help him to define can they or not!
Note : More than $1$ frog can be on the same point on the X-axis.
-----Input-----
- The first line contains three integers $N$, $K$ and $P$.
- The second line contains $N$ space-separated integers $A_1$, $A_2$, …, $A_N$ denoting the x-coordinates of frogs".
- Each of the next $P$ lines contains two integers $A$ and $B$ denoting the numbers of frogs according to the input.
-----Output-----
For each pair print "Yes" without a brackets if frogs can speak and "No" if they cannot.
-----Constraints-----
- $1 \le N, P \le 10^5$
- $0 \le A_i, K \le 10^9$
- $1 \le A, B \le N$
-----Example-----
-----Sample Input:-----
5 3 3
0 3 8 5 12
1 2
1 3
2 5
-----Sample Output:-----
Yes
Yes
No
-----Explanation-----
-
For pair $(1, 2)$ frog $1$ can directly speak to the frog $2$ as the distance between them is $3 - 0 = 3 \le K$ .
-
For pair $(1, 3)$ frog $1$ can send a message to frog $2$, frog $2$ can send it to frog $4$ and it can send it to frog $3$.
-
For pair $(2, 5)$ frogs can't send a message under current constraints.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
n, k, p = [int(i) for i in input().split()]
n_sep = list(map(int, input().split()))
count = 0
sep_sort = sorted(n_sep)
hashing = {sep_sort[0]: 0}
for j in range(1, n):
if (abs(sep_sort[j] - sep_sort[j - 1]) > k):
count += 1
hashing[sep_sort[j]] = count
#print(hashing)
for i in range(p):
pair = list(map(int, input().split()))
if hashing[n_sep[pair[1] - 1]] == hashing[n_sep[pair[0] - 1]]:
print("Yes")
else:
print("No")
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
4
1
2
3
4
-----Sample Output:-----
1
10
10
101
101
101
1010
1010
1010
1010
-----EXPLANATION:-----
No need, else pattern can be decode easily.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for _ in range(int(input())):
n = int(input())
num = ""
val = 1
for i in range(n):
num += str(val)
if val == 1:
val = 0
else:
val = 1
for i in range(n):
print(num)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Cersei wants to be the queen of seven kingdoms.
For this to happen, she needs to address the soldiers in her army. There are n$n$ soldiers in her army (numbered 1$1$ through n$n$). Cersei passes on the message to the first soldier (soldier 1).
This message needs to reach every soldier in the army. For this, the soldiers communicate among themselves by one soldier passing the message to another soldier through some communication links. It is known that the message could reach every soldier using the given links.
Now, each soldier will receive the message from exactly one soldier or Cersei and could pass on the message to atmost two soldiers. That is each soldier (except soldier 1) has only one incoming link and every soldier (including soldier 1) has atmost two outgoing links.
Now, the High Sparrow feels that Cersei is planning to kill his people first. Hence, for the sake of his people, he decided to appoint some sparrows to overhear every conversation between the soldiers (The conversation between Cersei and the first soldier needn't be overheard due to the fear of Ser Gregor Clegane).
To overhear a conversation between soldiers A$A$ and B$B$, there needs to be a sparrow either at soldier A$A$ or soldier B$B$ or both.
Also, by his research, the High Sparrow has found that the soldiers are partitioned into some classes (1$1$ to k$k$). That is, every soldier belongs to exactly one class. He then demands the presence of atleast one sparrow with each class he knows (1$1$ to k$k$).
Find the minimum number of sparrows the High Sparrow needs to recruit for the job or tell that he couldn't.
-----Input:-----
- The first line of the input contains the number of test cases t$t$.
- The first line of each test case gives the number of soldiers n$n$ in the army, the number of communication links m$m$ between the soldiers and the number of classes k$k$ in soldiers.
- The next line of the test case consists of n$n$ integers A1,A2....An$A_1,A_2....A_n$ each denoting the class of the ith$i^{th}$ soldier.
- The next m$m$ lines of the test case contain two integers u$u$ and v$v$, which denotes that soldier u$u$ can pass a message to soldier v$v$ (u≠v$u \neq v$).
-----Output:-----
For each test case, print in a single line the minimum number of sparrows required for the above task or print −1$-1$ if no such way is possible.
-----Constraints-----
- 1≤t≤500$1 \leq t \leq 500$
- 1≤n≤2500$1 \leq n \leq 2500$
- m=n−1$m = n - 1$
- 1≤k≤10$1 \leq k \leq 10$
- 1≤ai≤k$1 \leq a_i \leq k$
- The sum of n$n$ over all test cases is ≤2500$\leq 2500$.
-----Sample Input:-----
1
5 4 3
1 1 2 2 3
1 2
1 3
2 4
2 5
-----Sample Output:-----
3
-----EXPLANATION:-----
Selecting soldiers 1,4,5 would satisfy all the conditions.
-----Sample Input:-----
1
5 4 5
1 1 2 2 3
1 2
1 3
2 4
2 5
-----Sample Output:-----
-1
-----EXPLANATION:-----
Classes 4 and 5 are not present. So, there is no way possible.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
dt, a = None, None
def dfs(z):
r = [{}, {}];ln = len(dt[z])
if ln == 0:r[0][0] = 0;r[1][1 << a[z]] = 1
elif ln == 1:
l = dfs(dt[z][0]);r[0] = l[1]
for m in l[0]: r[1][(1 << a[z]) | m] = min(r[1][(1 << a[z]) | m], l[0][m] + 1) if (1 << a[z]) | m in r[1] else l[0][m] + 1
for m in l[1]: r[1][(1 << a[z]) | m] = min(r[1][(1 << a[z]) | m], l[1][m] + 1) if (1 << a[z]) | m in r[1] else l[1][m] + 1
elif ln == 2:
l0 = dfs(dt[z][0]);l1 = dfs(dt[z][1])
for i0 in range(2):
for i1 in range(2):
for m0 in l0[i0]:
for m1 in l1[i1]:r[1][(1 << a[z]) | m0 | m1] = min(r[1][(1 << a[z]) | m0 | m1], l0[i0][m0] + l1[i1][m1] + 1) if (1 << a[z]) | m0 | m1 in r[1] else l0[i0][m0] + l1[i1][m1] + 1
for m0 in l0[1]:
for m1 in l1[1]: r[0][m0 | m1] = min(r[0][m0 | m1], l0[1][m0] + l1[1][m1]) if m0 | m1 in r[0] else l0[1][m0] + l1[1][m1]
return r
for i in range(int(input())):
n, m, k = map(int, input().split());a = [0] + [int(x) - 1 for x in input().split()];dt = [[] for i in range(n + 1)];
for i in range(m):u, v = map(int, input().split());dt[u].append(v)
r = dfs(1);k = (1 << k) - 1
if (k in r[0]): v = min(r[0][k], r[1][k])
elif (k in r[1]): v = r[1][k]
else: v = -1
print(v)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Let's define a periodic infinite sequence S$S$ (0$0$-indexed) with period K$K$ using the formula Si=(i%K)+1$S_i = (i \% K) + 1$.
Chef has found a sequence of positive integers A$A$ with length N$N$ buried underground. He suspects that it is a contiguous subsequence of some periodic sequence. Unfortunately, some elements of A$A$ are unreadable. Can you tell Chef the longest possible period K$K$ of an infinite periodic sequence which contains A$A$ (after suitably filling in the unreadable elements) as a contiguous subsequence?
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains a single integer N$N$.
- The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$. Unreadable elements are denoted by −1$-1$.
-----Output-----
For each test case, print a single line.
- If the period can be arbitrarily large, this line should contain a single string "inf".
- Otherwise, if A$A$ cannot be a contiguous subsequence of a periodic sequence, it should contain a single string "impossible".
- Otherwise, it should contain a single integer — the maximum possible period.
-----Constraints-----
- 1≤T≤100$1 \le T \le 100$
- 2≤N≤105$2 \le N \le 10^5$
- the sum of N$N$ over all test cases does not exceed 106$10^6$
- for each valid i$i$, 1≤Ai≤106$1 \le A_i \le 10^6$ or Ai=−1$A_i = -1$
-----Subtasks-----
Subtask #1 (50 points):
- 2≤N≤1,000$2 \le N \le 1,000$
- the sum of N$N$ over all test cases does not exceed 10,000$10,000$
Subtask #2 (50 points): original constraints
-----Example Input-----
3
3
-1 -1 -1
5
1 -1 -1 4 1
4
4 6 7 -1
-----Example Output-----
inf
4
impossible
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
from math import gcd
for _ in range(int(input())):
n,a,k,min_k,e = int(input()),[int(i) for i in input().split()],0,0,-1
for j in range(n):
if(a[j] != -1):break
for i in range(j,n):
if min_k==0:min_k,e = a[i],a[i]+1
else:
if min_k < a[i]:min_k = a[i]
if(a[i] == -1):pass
else:
if(a[i] == e):pass
else:
if( k == 0):k = e-a[i]
else:
new_k = e-a[i]
if(new_k < 0):k = -1
else:k = gcd(k,new_k)
if(k<min_k or k<0): k = -1; break
if k != 0 and a[i]!=-1: e = a[i]%k+1
else:e += 1
if(k == -1):print("impossible")
elif k == 0 :print("inf")
else:print(k)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Levko loves array a_1, a_2, ... , a_{n}, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
Increase all elements from l_{i} to r_{i} by d_{i}. In other words, perform assignments a_{j} = a_{j} + d_{i} for all j that meet the inequation l_{i} ≤ j ≤ r_{i}. Find the maximum of elements from l_{i} to r_{i}. That is, calculate the value $m_{i} = \operatorname{max}_{j = l_{i}}^{r_{i}} a_{j}$.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 10^9 in their absolute value, so he asks you to find such an array.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 5000) — the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer t_{i} (1 ≤ t_{i} ≤ 2) that describes the operation type. If t_{i} = 1, then it is followed by three integers l_{i}, r_{i} and d_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, - 10^4 ≤ d_{i} ≤ 10^4) — the description of the operation of the first type. If t_{i} = 2, then it is followed by three integers l_{i}, r_{i} and m_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, - 5·10^7 ≤ m_{i} ≤ 5·10^7) — the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
-----Output-----
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a_1, a_2, ... , a_{n} (|a_{i}| ≤ 10^9) — the recovered array.
-----Examples-----
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
a = [10**9 for _ in range(n)]
extra = [0 for _ in range(n)]
query = list()
for _ in range(m):
t, l, r, x = map(int, input().split())
l -= 1
r -= 1
query.append((t, l, r, x))
if t == 1:
for j in range(l, r + 1):
extra[j] += x
else:
for j in range(l, r + 1):
a[j] = min(a[j], x - extra[j])
extra = a.copy()
for t, l, r, x in query:
if t == 1:
for j in range(l, r + 1):
a[j] += x
else:
val = -10**9
for j in range(l, r + 1):
val = max(val, a[j])
if not val == x:
print('NO')
return
print('YES')
for x in extra:
print(x, end=' ')
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
It is well-known that the elephants are afraid of mouses. The Little Elephant from the Zoo of Lviv is not an exception.
The Little Elephant is on a board A of n rows and m columns (0-based numeration). At the beginning he is in cell with coordinates (0; 0) and he wants to go to cell with coordinates (n-1; m-1). From cell (x; y) Little Elephant can go either to (x+1; y) or (x; y+1).
Each cell of the board contains either 1 or 0. If A[i][j] = 1, then there is a single mouse in cell (i; j). Mouse at cell (i; j) scared Little Elephants if and only if during the path there was at least one such cell (x; y) (which belongs to that path) and |i-x| + |j-y| <= 1.
Little Elephant wants to find some correct path from (0; 0) to (n-1; m-1) such that the number of mouses that have scared the Little Elephant is minimal possible. Print that number.
-----Input-----
First line contains single integer T - the number of test cases. Then T test cases follow. First line of each test case contain pair of integers n and m - the size of the board. Next n lines contain n strings, each of size m and consisted of digits 0 and 1.
-----Output-----
In T lines print T integer - the answers for the corresponding test.
-----Constraints-----
1 <= T <= 50
2 <= n, m <= 100
-----Example-----
Input:
2
3 9
001000001
111111010
100100100
7 9
010101110
110110111
010011111
100100000
000010100
011011000
000100101
Output:
9
10
-----Explanation-----
Example case 1:
The optimized path is: (0, 0) -> (0, 1) -> (0, 2) -> (0, 3) -> (0, 4) -> (0, 5) -> (0, 6) -> (0, 7) -> (0, 8) -> (1, 8) -> (2, 8). The mouses that scared the Little Elephant are at the following cells: (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 7), (0, 2), (0, 8).
Example case 2:
The optimized path is: (0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3) -> (4, 3) -> (4, 4) -> (5, 4) -> (5, 5) -> (6, 5) -> (6, 6) -> (6, 7) -> (6, 8). The 10 mouses that scared the Little Elephant are at the following cells: (0, 1), (1, 0), (1, 1), (2, 1), (3, 3), (4, 4), (5, 4), (5, 5), (6, 6), (6, 8).
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
from itertools import product
def solve(mouse,n,m):
# shadow matrix will contains the count of mice which affect (i,j) position
# if there is a mice at position (i,j) then in shadow matrix it will affect all four adjacent blocks
shadow=[[0 for i in range(m)]for j in range(n)]
for i,j in product(list(range(n)),list(range(m))):
if mouse[i][j]==1:
if i>0:
shadow[i-1][j]+=1
if j>0:
shadow[i][j-1]+=1
if i<n-1:
shadow[i+1][j]+=1
if j<m-1:
shadow[i][j+1]+=1
# dp is a dictionary which contains a tuple of 3 values (i,j,0)=>we are coming at destination (i,j) from left side
# (i,j,1)=> we are coming at destination (i,j) from top
dp=defaultdict(int)
#
dp[(0,0,0)]=dp[(0,0,1)]=shadow[0][0]-mouse[0][0]
# fill only first row
# in first row we can only reach at (0,j) from (0,j-1,0) as we can't come from top.
# so here we will assign count of mices which will affect current cell (shadow[0][i]) + previous result i.e,(0,j-1,0) and
# if mouse is in the current cell than we have to subtract it bcoz we have add it twice i.e, when we enter at this block
# and when we leave this block
for i in range(1,m):
dp[(0,i,0)]=dp[(0,i,1)]=shadow[0][i]-mouse[0][i]+dp[(0,i-1,0)]
# same goes for first column
# we can only come at (i,0) from (i-1,0) i.e top
for i in range(1,n):
dp[(i,0,0)]=dp[(i,0,1)]=shadow[i][0]-mouse[i][0]+dp[(i-1,0,1)]
# for rest of the blocks
# for a block (i,j) we have to add shadow[i][j] and subtract mouse[i][j] from it for double counting
# now for each block we have two choices, either take its previous block with same direction or take previous block with different
# direction and subtract corner double counted mouse. We have to take min of both to find optimal answer
for i,j in product(list(range(1,n)),list(range(1,m))):
a=shadow[i][j]-mouse[i][j]
b=a
a+=min(dp[(i,j-1,0)],dp[(i,j-1,1)]-mouse[i-1][j])
b+=min(dp[(i-1,j,1)],dp[(i-1,j,0)]-mouse[i][j-1])
dp[(i,j,0)]=a
dp[(i,j,1)]=b
# what if [0][0] and [n-1][m-1] have mice, so we have to add them as we haven't counted them yet.
return min(dp[(n-1,m-1,0)],dp[(n-1,m-1,1)])+mouse[0][0]+mouse[n-1][m-1]
for _ in range(int(input())):
n,m=list(map(int,input().split( )))
mouse=[]
for i in range(n):
x=input()
mouse.append(list(map(int,x)))
print(solve(mouse,n,m))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Witua is a little student from the University of Lviv. He enjoys studying math. Witua knows a lot of famous mathematicians like Eratosthenes, Pythagoras, Fermat, Diophantus, Furko, Gauss and so on. However, his favorite one is Euler. The only thing Witua likes more than Euler is Euler’s totient function φ. He is exploring the nature of this function. One of the steps of his work is finding φ(i)/i for all 2≤i≤N. He doesn’t need to know every such value, but Witua wonders for what value i, is φ(i)/i the maximum he can get? Help little student to find such i that φ(i)/i is maximum among all the 2≤i≤N.
-----Input-----
The first line contains single integer T - the number of test cases. Each of the next T lines contains a single integer N.
-----Output-----
For every test case output i such that φ(i)/i is maximum among all i (2≤i≤N) in a separate line.
-----Constrains-----
T (1≤T≤500 )
N(2≤N≤10^18)
-----Example-----
Input:
3
2
3
4
Output:
2
3
3
Explanationφ(2)/2=1/2
φ(3)/3=2/3
φ(4)/4=2/4
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
def modular_pow(base, exponent, modulus):
result = 1
while exponent > 0:
if(exponent %2 == 1):
result = (result * base) % modulus
exponent = exponent//2
base = (base * base)%modulus
return result
def passesMillerRabinTest(n, a):
s = 0
d = n-1
while(d%2 == 0):
s += 1
d >>= 1
x = modular_pow(a, d, n)
if(x == 1 or x == n-1):
return True
for ss in range(s - 1):
x = (x*x)%n
if(x == 1):
return False
if(x == n-1):
return True
return False
primeList = (2, 3,5,7,11,13,17,19, 23,29, 31,37)
def isPrime(n):
for p in primeList:
if n%p == 0:
return n == p
for p in primeList:
if passesMillerRabinTest(n, p) == False:
return False
return True
t = int(input())
for tt in range(t):
n = int(input())
if(n == 2):
print(2)
continue
if n%2 == 0:
n -= 1
while True:
if(isPrime(n)):
print(n)
break
n -= 2
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a string s, consisting of lowercase English letters, and the integer m.
One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves.
Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order.
Formally, we choose a subsequence of indices 1 ≤ i_1 < i_2 < ... < i_{t} ≤ |s|. The selected sequence must meet the following condition: for every j such that 1 ≤ j ≤ |s| - m + 1, there must be at least one selected index that belongs to the segment [j, j + m - 1], i.e. there should exist a k from 1 to t, such that j ≤ i_{k} ≤ j + m - 1.
Then we take any permutation p of the selected indices and form a new string s_{i}_{p}_1s_{i}_{p}_2... s_{i}_{p}_{t}.
Find the lexicographically smallest string, that can be obtained using this procedure.
-----Input-----
The first line of the input contains a single integer m (1 ≤ m ≤ 100 000).
The second line contains the string s consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100 000. It is also guaranteed that the number m doesn't exceed the length of the string s.
-----Output-----
Print the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.
-----Examples-----
Input
3
cbabc
Output
a
Input
2
abcab
Output
aab
Input
3
bcabcbaccba
Output
aaabb
-----Note-----
In the first sample, one can choose the subsequence {3} and form a string "a".
In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
m = int(input())
s = input().strip()
sa = [0] * len(s)
for i in range(len(s)):
sa[i] = ord(s[i]) - ord('a')
sa = [-1] + sa + [-1]
def check_value(sa, m, threshold):
prev_ind = 0
for i in range(len(sa)):
if sa[i] <= threshold:
if i - prev_ind <= m:
prev_ind = i
else:
return False
return True
def get_indexes(sa, threshold):
seq = [i for i in range(len(sa)) if sa[i] <= threshold]
# seq = []
# for i in range(len(sa)):
# if sa[i] < threshold:
# seq[i].append(sa[i], i)
return seq
def filter_indexes(sa, seq, el, m):
new_seq = [0]
for i in range(1, len(seq) - 1):
if sa[seq[i]] != el or (sa[seq[i]] == el and seq[i+1] - new_seq[-1] > m):
new_seq.append(seq[i])
return new_seq[1:]
threshold = -1
while (not check_value(sa, m, threshold)):
# print(threshold, get_indexes(sa, threshold))
threshold += 1
# print(threshold, get_indexes(sa, threshold), sa)
seq = get_indexes(sa, threshold)
seq = filter_indexes(sa, seq, threshold, m)
s = ''.join(sorted([chr(ord('a') + sa[x]) for x in seq]))
print(s)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer a_{i} — the current skill level. All skills have the same maximum level A.
Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: The number of skills that a character has perfected (i.e., such that a_{i} = A), multiplied by coefficient c_{f}. The minimum skill level among all skills (min a_{i}), multiplied by coefficient c_{m}.
Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force.
-----Input-----
The first line of the input contains five space-separated integers n, A, c_{f}, c_{m} and m (1 ≤ n ≤ 100 000, 1 ≤ A ≤ 10^9, 0 ≤ c_{f}, c_{m} ≤ 1000, 0 ≤ m ≤ 10^15).
The second line contains exactly n integers a_{i} (0 ≤ a_{i} ≤ A), separated by spaces, — the current levels of skills.
-----Output-----
On the first line print the maximum value of the Force that the character can achieve using no more than m currency units.
On the second line print n integers a'_{i} (a_{i} ≤ a'_{i} ≤ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces.
-----Examples-----
Input
3 5 10 1 5
1 3 1
Output
12
2 5 2
Input
3 5 10 1 339
1 3 1
Output
35
5 5 5
-----Note-----
In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1.
In the second test one should increase all skills to maximum.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import itertools
import bisect
n, A, cf, cm, m = [int(x) for x in input().split()]
skills = [int(x) for x in input().split()]
sorted_skills = list(sorted((k, i) for i, k in enumerate(skills)))
bottom_lift = [0 for i in range(n)]
for i in range(1, n):
bottom_lift[i] = bottom_lift[i-1] + i * (sorted_skills[i][0] - sorted_skills[i-1][0])
root_lift = [0 for i in range(n+1)]
for i in range(1, n+1):
root_lift[i] = root_lift[i-1] + A - sorted_skills[n-i][0]
max_level = -1
for i in range(n+1):
money_left = m - root_lift[i]
if money_left < 0: break
k = min(bisect.bisect(bottom_lift, money_left), n-i)
money_left -= bottom_lift[k-1]
min_level = min(A, sorted_skills[k-1][0] + money_left//k) if k > 0 else A
level = cf*i + cm*min_level
if max_level < level:
max_level = level
argmax = i
argmax_min_level = min_level
argmax_k = k
ans = [0 for i in range(n)]
for i, skill in enumerate(sorted_skills):
if i < argmax_k:
ans[skill[1]] = argmax_min_level
elif i >= n - argmax:
ans[skill[1]] = A
else:
ans[skill[1]] = skill[0]
print(max_level)
for a in ans:
print(a, end = ' ')
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Gru has a string $S$ of length $N$, consisting of only characters $a$ and $b$ for banana and $P$ points to spend.
Now Gru wants to replace and/or re-arrange characters of this given string to get the lexicographically smallest string possible. For this, he can perform the following two operations any number of times.
1) Swap any two characters in the string. This operation costs $1$ $point$. (any two, need not be adjacent)
2) Replace a character in the string with any other lower case english letter. This operation costs $2$ $points$.
Help Gru in obtaining the lexicographically smallest string possible, by using at most $P$ points.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains two lines of input, first-line containing two integers $N$ , $P$.
- The second line contains a string $S$ consisting of $N$ characters.
-----Output:-----
For each testcase, output in a single containing the lexicographically smallest string obtained.
-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $0 \leq P \leq 2N$
- $S$ only consists of $'a'$ and $'b'$
-----Sample Input:-----
1
3 3
bba
-----Sample Output:-----
aab
-----Explanation:-----
We swap $S[0]$ and $S[2]$, to get $abb$. With the 2 remaining points, we replace $S[1]$ to obtain $aab$ which is the lexicographically smallest string possible for this case.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def __starting_point():
t=int(input())
for _ in range(t):
n,p=input().split()
n,p=int(n),int(p)
s=input()
a,b=0,0
arr=[0]*n
for i in range(n):
arr[i]=s[i]
for c in s:
if c=='a':
a+=1
else:
b+=1
swap=0
for i in range(a):
if s[i]=='b':
swap+=1
tmpp=p
if p<=swap:
for i in range(n):
if p==0:
break
if arr[i]=='b':
arr[i]='a'
p-=1
p=tmpp
for i in range(n-1,-1,-1):
if p==0:
break
if arr[i]=='a':
arr[i]='b'
p-=1
for c in arr:
print(c,end="")
print()
else:
for i in range(n):
if i<a:
arr[i]='a'
else:
arr[i]='b'
p-=swap
for i in range(n):
if arr[i]=='b':
if s[i]=='b' and p>=2:
p-=2
arr[i]='a'
if s[i]=='a' and p>=1:
p-=1
arr[i]='a'
for c in arr:
print(c,end="")
print()
__starting_point()
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a sequence of N$N$ powers of an integer k$k$; let's denote the i$i$-th of these powers by kAi$k^{A_i}$. You should partition this sequence into two non-empty contiguous subsequences; each element of the original sequence should appear in exactly one of these subsequences. In addition, the product of (the sum of elements of the left subsequence) and (the sum of elements of the right subsequence) should be maximum possible.
Find the smallest position at which you should split this sequence in such a way that this product is maximized.
-----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 k$k$.
- The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$.
-----Output-----
For each test case, print a single line containing one integer — the size of the left subsequence. If there is more than one possible answer, print the smallest possible one.
-----Constraints-----
- 1≤T≤10$1 \le T \le 10$
- 2≤N≤105$2 \le N \le 10^5$
- 2≤k≤109$2 \le k \le 10^9$
- 0≤Ai≤105$0 \le A_i \le 10^5$ for each valid i$i$
-----Subtasks-----
Subtask #1 (30 points):
- 2≤N≤1,000$2 \le N \le 1,000$
- 0≤Ai≤1,000$0 \le A_i \le 1,000$ for each valid i$i$
Subtask #2 (70 points): original constraints
-----Example Input-----
1
5 2
1 1 3 3 5
-----Example Output-----
4
-----Explanation-----
Example case 1: The actual sequence of powers is [21,21,23,23,25]=[2,2,8,8,32]$[2^1, 2^1, 2^3, 2^3, 2^5] = [2, 2, 8, 8, 32]$. The maximum product is 20⋅32=640$20 \cdot 32 = 640$. In the optimal solution, the sequence is partitioned into [2,2,8,8]$[2, 2, 8, 8]$ and [32]$[32]$.
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 main():
for _ in range(int(input())):
N, k = [int(x) for x in input().split()]
Powers = [k ** int(x) for x in input().split()]
s1, s2 = 0, sum(Powers)
ans = (0, None)
i = 0
while i < N - 1:
s1 += Powers[i]
s2 -= Powers[i]
z = s1 * s2
if z > ans[0]:
ans = (z, i)
# print(z)
i += 1
print(ans[1] + 1)
main()
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = s_{k} + 1s_{k} + 2... s_{n}s_1s_2... s_{k}. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.
Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability.
Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
-----Input-----
The only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only.
-----Output-----
Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10^{ - 6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-6}$
-----Examples-----
Input
technocup
Output
1.000000000000000
Input
tictictactac
Output
0.333333333333333
Input
bbaabaabbb
Output
0.100000000000000
-----Note-----
In the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.
In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
str = input()
l = len(str)
a = [0] * (2 * l)
pos = [[] for i in range(26)]
for i, c in enumerate(str):
t = ord(c) - ord('a')
a[i] = t
a[i + l] = t
pos[t].append(i)
ans = 0
for c in range(26):
cur = 0
for k in range(1, l):
cnt = [0] * 26
for i in pos[c]:
cnt[a[i + k]] += 1
cur = max(cur, len(list([x for x in cnt if x == 1])))
ans += cur
print(ans / l)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "d_{i} → t_{i}", that means "replace all digits d_{i} in string s with substrings equal to t_{i}". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("replace 3 by an empty string") transforms it to s = 1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to s by 1000000007 (10^9 + 7). When you represent s as a decimal number, please ignore the leading zeroes; also if s is an empty string, then it's assumed that the number equals to zero.
Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!
-----Input-----
The first line contains string s (1 ≤ |s| ≤ 10^5), consisting of digits — the string before processing all the requests.
The second line contains a single integer n (0 ≤ n ≤ 10^5) — the number of queries.
The next n lines contain the descriptions of the queries. The i-th query is described by string "d_{i}->t_{i}", where d_{i} is exactly one digit (from 0 to 9), t_{i} is a string consisting of digits (t_{i} can be an empty string). The sum of lengths of t_{i} for all queries doesn't exceed 10^5. The queries are written in the order in which they need to be performed.
-----Output-----
Print a single integer — remainder of division of the resulting number by 1000000007 (10^9 + 7).
-----Examples-----
Input
123123
1
2->00
Output
10031003
Input
123123
1
3->
Output
1212
Input
222
2
2->0
0->7
Output
777
Input
1000000008
0
Output
1
-----Note-----
Note that the leading zeroes are not removed from string s after the replacement (you can see it in the third sample).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MOD = 10**9+7
s = input()
n = int(input())
qs = [['',s]]+[input().split('->') for i in range(n)]
ds = {}
for i in range(10):
ds[str(i)] = (10,i)
for i in range(n,-1,-1):
out = 0
mul = 1
for d in qs[i][1]:
out = (out * ds[d][0] + ds[d][1]) % MOD
mul = (mul * ds[d][0]) % MOD
ds[qs[i][0]] = (mul,out)
print(ds[''][1])
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward).
[Image]
Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.
-----Input-----
The first line of the input contains a single number n (1 ≤ n ≤ 26) — the number of colors of beads. The second line contains after n positive integers a_{i} — the quantity of beads of i-th color. It is guaranteed that the sum of a_{i} is at least 2 and does not exceed 100 000.
-----Output-----
In the first line print a single number — the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace.
Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.
-----Examples-----
Input
3
4 2 1
Output
1
abacaba
Input
1
4
Output
4
aaaa
Input
2
1 1
Output
0
ab
-----Note-----
In the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.
In the second sample there is only one way to compose a necklace.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
#import fractions
from functools import reduce
n = int(input())
odd = -1
beads = [int(x) for x in input().split()]
for i in range(n):
if beads[i]%2:
if odd >= 0:
print(0)
print(''.join(chr(ord('a') + i)*beads[i] for i in range(n)))
break
else:
odd = i
else:
gcd = reduce(lambda x,y: math.gcd(x,y), beads)
print(gcd)
if odd >= 0:
s = ''.join(chr(ord('a') + i)*(beads[i]//(2*gcd)) for i in range(n) if i != odd)
p = s + chr(ord('a') + odd)*(beads[odd]//gcd) + s[::-1]
print(p*gcd)
else:
s = ''.join(chr(ord('a') + i)*(beads[i]//gcd) for i in range(n))
p = s + s[::-1]
print(p*(gcd//2))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chefina is always interested to play with string. But due to exam pressure she has no time to solve a string problem. She wants your help. Can you help her to solve that problem?
You are given a string. You have to find out the $Wonder$ $Sum$ of the string. $Wonder$ $Sum$ of a string is defined as the sum of the value of each character of the string.
The value of each character means:
- If the string is started with "a" , then the value of each character of the string is like "a"=100, "b"=101, "c"="102" ………"z"=125.
- If the string is started with "z" , then the value of each character of the string is like "a"=2600, "b"=2601, "c"="2602" ………"z"=2625.
Since even the $Wonder$ $Sum$ can be large, output $Wonder$ $Sum$ modulo ($10^9 + 7$).
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, a string $S$ with lower case alphabet
only.
-----Output:-----
For each testcase, output in a single line integer i.e. $Wonder$ $Sum$ modulo ($10^9 + 7$).
-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq |S| \leq 10^5$
-----Sample Input:-----
$2$$cab$
$sdef$
-----Sample Output:-----
$903$
$7630$
-----EXPLANATION:-----
i) For the first test case, since the string is started with "$c$", so output is ($302$+$300$+$301$)=$903$
ii)For the second test case, since the string is started with "$s$", so output is ($1918$+$1903$+$1904$+$1905$)=$7630$
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())):
string = input().rstrip()
start=(ord(string[0])-96)*100
sum=0
#print(start)
for i in range(len(string)):
sum+=start+(ord(string[i])-97)
print(sum%1000000007)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Let's consider a rooted binary tree with the following properties:
- The number of nodes and edges in the tree is infinite
- The tree root is labeled by $1$
- A node labeled by $v$ has two children: $2 \cdot v$ (the left child of $v$), and $2 \cdot v + 1$ (the right child of $v$).
Here is an image of the first several layers of such a tree:
Let's consider four operations that you are allowed to apply during the tree traversal:
- move to the left child - move from $v$ to $2 \cdot v$
- move to the right child - move from $v$ to $2 \cdot v + 1$
- move to the parent as a left child - move from $v$ to $\frac{v}{2}$ if $v$ is an even integer
- move to the parent as a right child - move from $v$ to $\frac{v - 1}{2}$ if $v$ is an odd integer
It can be proven, that for any pair of nodes $u$ and $v$, there is only one sequence of commands that moves from $u$ to $v$ and visits each node of the tree at most once. Let's call such a sequence of commands a path configuration for a pair of nodes $(u, v)$.
You are asked to process a series of the following queries:
You are given three integers $n$, $u$ and $v$ ($1 \leq u, v \leq n$). Count the pairs of nodes $(w, t)$ ($1 \leq w, t \leq n$) such that the path configuration for $(w, t)$ is the same with the path configuration for $(u, v)$.
-----Input-----
- The first line of input contains a single integer $Q$, denoting the number of queries to process.
- Each of the next $Q$ lines contains three space-separated integers $n$, $u$ and $v$ denoting a query.
-----Output-----
For each query, print the answer on a separate line.
-----Constraints-----
- $1 \leq Q \leq 2 \cdot 10^4$
- $1 \leq u, v \leq n \leq 10^{9}$
-----Example Input-----
3
11 9 11
10 2 2
8 1 8
-----Example Output-----
2
10
1
-----Explanation-----
In the first query from the example test case, you should count pairs $(5, 7)$ and $(9, 11)$.
In the second query from the example test case, you should count the following pairs: $(1, 1)$, $(2, 2)$, $(3, 3)$, $(4, 4)$, $(5, 5)$, $(6, 6)$, $(7, 7)$, $(8, 8)$, $(9, 9)$ and $(10, 10)$.
In the third query from the example test case, you should only count a pair $(1, 8)$.
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-=1;
n,l,r = list(map(int,input().split()));
a = bin(l)[2:];
b = bin(r)[2:];
# find matching
z = 0;
l = min(len(a),len(b));
for i in range(l):
if a[i]==b[i]:
z+=1;
else:
break;
#find base string
a = a[z:]
b = b[z:]
if(len(a)==0 and len(b)==0):
print(n);
else :
m = max(len(a),len(b))
#print m;
zz = bin(n)[2:]
x= len(zz)
y = zz[:x-m]
f1 = y+a;
f2 = y+b;
ans = int(y,2)
if(int(f1,2)>n or int(f2,2)>n):
ans-=1;
print(ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
In a regular table tennis match, the player who serves changes every time after 2 points are scored, regardless of which players scored them.
Chef and Cook are playing a different match — they decided that the player who serves would change every time after $K$ points are scored instead (again regardless of which players scored them). When the game starts, it's Chef's turn to serve.
You are given the current number of points scored by Chef and Cook ($P_1$ and $P_2$ respectively). Find out whether Chef or Cook has to serve next.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains three space-separated integers $P_1$, $P_2$ and $K$.
-----Output-----
For each test case, print a single line containing the string "CHEF" if it is Chef's turn or "COOK" if it is Cook's turn.
-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le K \le 10^{9}$
- $0 \le P_1, P_2 \le 10^{9}$
-----Subtasks-----
Subtask #1 (100 points): original constraints
-----Example Input-----
3
1 3 2
0 3 2
34 55 2
-----Example Output-----
CHEF
COOK
CHEF
-----Explanation-----
Example case 1: Chef serves for the first two points, Cook serves for the next two, so Chef has to serve again now.
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):
l=list(map(int,input().split()))
k=l[0]+l[1]
k=k%(2*l[2])
if k>=0 and k<l[2]:
print("CHEF")
else:
print("COOK")
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Kshitij has recently started solving problems on codechef. As he is real problem solving enthusiast, he wants continuous growth in number of problems solved per day.
He started with $a$ problems on first day.
He solves $d$ problems more than previous day. But after every $k$ days , he increases $d$ by
$inc$ .
Can you guess how many questions he will solve on $nth $ day ?
-----Input:-----
- First line contains $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input,five integers $a, d, k, n, inc$.
-----Output:-----
For each testcase, output in a single line number of questions solved on $nth$ day.
-----Constraints-----
- $1 \leq T \leq 15$
- $1 \leq a \leq 99$
- $1 \leq d \leq 100$
- $1 \leq n \leq 10000$
- $1 \leq k \leq n$
- $0 \leq inc \leq 99$
-----Sample Input:-----
1
1 4 3 8 2
-----Sample Output:-----
43
-----EXPLANATION:-----
The number of questions solved in first 8 days is :
$1$ $5$ $9$ $15$ $21$ $27$ $35$ $43$ .
On first day he solved 1 problem . Here $d$ is 4 for first 3 days.
Then after 3 days $d$ increases by 2 (that is 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
t = int(input())
for _ in range(t):
a,d,k,n,inc = map(int, input().strip().split())
res = a
for i in range(1, n):
if i%k == 0:
d += inc
res += d
print(res)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Coach Moony wants the best team to represent their college in ICPC. He has $N$ students standing in a circle with certain rating $X_i$ on a competitive coding platform. It is an established fact that any coder with more rating on the platform is a better coder.
Moony wants to send his best $3$ coders based upon their rating. But all coders only want to have their friends in their team and every coder is friends with four other coders, adjacent two on left side in the circle, and adjacent two on right. So Moony comes up with a solution that team with maximum cumulative rating of all three members in a team shall be representing their college.
You need to give the cumulative score of the team that will be representing the college.
-----Input:-----
- First line will contain $T$, number of testcases.
- First line of each test case contains a single integer $N$.
- Second line of each test case takes $N$ integers, denoting rating of $ith$ coder.
-----Output:-----
For each testcase, output a single integer denoting cumulative rating of the team.
-----Constraints-----
- $1 \leq T \leq 10$
- $7 \leq N \leq 10^5$
- $0 \leq X_i \leq 10^9$
-----Sample Input:-----
1
7
10 40 30 30 20 0 0
-----Sample Output:-----
100
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
#Moony and ICPC team
T = int(input())
for i in range(T):
N,data = int(input()),list(map(int,input().split()))
if(N==3):
print(sum(data))
else:
best = data[0]+data[1]+data[2]
overall = best
k=len(data)
for i in range(1,k-2):
overall=overall - data[i-1] + data[i+2]
if(overall>best):
best = overall
j=max(data[1],data[-2])
l= data[-1]+data[0]+j
if(best < l):
best = l
print(best)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Consider the infinite sequence $s$ of positive integers, created by repeating the following steps:
Find the lexicographically smallest triple of positive integers $(a, b, c)$ such that $a \oplus b \oplus c = 0$, where $\oplus$ denotes the bitwise XOR operation. $a$, $b$, $c$ are not in $s$. Here triple of integers $(a_1, b_1, c_1)$ is considered to be lexicographically smaller than triple $(a_2, b_2, c_2)$ if sequence $[a_1, b_1, c_1]$ is lexicographically smaller than sequence $[a_2, b_2, c_2]$. Append $a$, $b$, $c$ to $s$ in this order. Go back to the first step.
You have integer $n$. Find the $n$-th element of $s$.
You have to answer $t$ independent test cases.
A sequence $a$ is lexicographically smaller than a sequence $b$ if in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases.
Each of the next $t$ lines contains a single integer $n$ ($1\le n \le 10^{16}$) — the position of the element you want to know.
-----Output-----
In each of the $t$ lines, output the answer to the corresponding test case.
-----Example-----
Input
9
1
2
3
4
5
6
7
8
9
Output
1
2
3
4
8
12
5
10
15
-----Note-----
The first elements of $s$ are $1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $
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
out = []
t = int(input())
for _ in range(t):
n = int(input())
n -= 1
rem = n % 3
n //= 3
s = []
if n:
n -= 1
while n >= 0:
s.append([['00','00','00'],['01','10','11'],['10','11','01'],['11','01','10']][n % 4][rem])
n //= 4
n -= 1
s.append(['1','10','11'][rem])
s.reverse()
out.append(int(''.join(s),2))
print('\n'.join(map(str,out)))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.
The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().
-----Input-----
The first line contains a non-negative integer a.
The second line contains a non-negative integer b.
The numbers a, b may contain leading zeroes. Each of them contains no more than 10^6 digits.
-----Output-----
Print the symbol "<" if a < b and the symbol ">" if a > b. If the numbers are equal print the symbol "=".
-----Examples-----
Input
9
10
Output
<
Input
11
10
Output
>
Input
00012345
12345
Output
=
Input
0123
9
Output
>
Input
0123
111
Output
>
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a = input()
b = input()
n, m = len(a), len(b)
if n > m: b = '0' * (n - m) + b
else: a = '0' * (m - n) + a
i = 0
while i < max(n, m) and a[i] == b[i]:
i += 1
print('=' if i == max(n, m) else '<' if int(a[i]) < int(b[i]) else '>')
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has a sequence $A_1, A_2, \ldots, A_N$. For a positive integer $M$, sequence $B$ is defined as $B = A*M$ that is, appending $A$ exactly $M$ times. For example, If $A = [1, 2]$ and $M = 3$, then $B = A*M = [1, 2, 1, 2, 1, 2]$
You have to help him to find out the minimum value of $M$ such that the length of the longest strictly increasing subsequence is maximum possible.
-----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 minimum value of $M$.
-----Constraints-----
- $1 \le T \le 500$
- $1 \le N \le 2*10^5$
- $1 \le A_i \le 10^9$
- It's guaranteed that the total length of the sequence $A$ in one test file doesn't exceed $2*10^6$
-----Sample Input:-----
3
2
2 1
2
1 2
5
1 3 2 1 2
-----Sample Output:-----
2
1
2
-----Explanation:-----
In the first test case, Choosing $M = 2$ gives $B = [2, 1, 2, 1]$ which has a longest strictly increasing sequence of length $2$ which is the maximum possible.
In the second test case, Choosing $M = 1$ gives $B = [1, 2]$ which has a longest strictly increasing sequence of length $2$ which is the maximum possible.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def mForMaxSeq(arr, n):
eim = dict()
for i in range(n):
if arr[i] in eim:
eim[arr[i]].append(i)
else:
eim[arr[i]] = [i]
keys = sorted(eim.keys())
# print(eim, keys)
connected = False
count = 0
pI = -1
nKeys = len(keys)
for i in range(nKeys-1):
if not connected:
pI = eim[keys[i]][0]
for idx in eim[keys[i+1]]:
if idx >pI:
connected = True
count += 1
pI = idx
break
else:
connected = False
for idx in eim[keys[i+1]]:
if idx > pI:
connected = True
count += 1
pI = idx
break
return (nKeys - count)
def __starting_point():
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
print(mForMaxSeq(arr, n))
__starting_point()
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."
And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not.
Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $k$, so they got $k+1$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.
In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $3$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.
More formally, Sasha wants for the given palindrome $s$ find such minimum $k$, that you can cut this string into $k + 1$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $s$. It there is no answer, then print "Impossible" (without quotes).
-----Input-----
The first line contains one string $s$ ($1 \le |s| \le 5\,000$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $s$ is a palindrome.
-----Output-----
Print one integer $k$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
-----Examples-----
Input
nolon
Output
2
Input
otto
Output
1
Input
qqqq
Output
Impossible
Input
kinnikkinnik
Output
1
-----Note-----
In the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.
In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.
In the third example, you can't make a string, that won't be equal to the initial one.
In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def solve(s):
n = len(s)
for i in range(n):
s2 = s[i:] + s[:i]
# print(s2)
if s != s2 and s2[::-1] == s2:
return 1
for i in range( (n // 2) + 1, n):
if s[i] != s[0]:
return 2
# print(s[i])
return "Impossible"
s = input()
print(solve(s))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Given a number n. Find the last two digits of 5 ^ n ( 5 to the power of n ).
Remember that overflow can occur.
-----Input:-----
- N — the power in which you need to raise number 5.
-----Output:-----
Last two digits of 5^n.
-----Constraints-----
- $2 \leq N \leq 2.1018$
-----Sample Input:-----
2
-----Sample Output:-----
25
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
print(25)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The land of Programmers Army is surrounded by many islands. A unique number is associated with each island. The king of the islands is a very generous person, he donates a certain amount of gold coins to travelers for visiting each island that they visited to.
Now, you are appointed as a traveler, who will travel to all these(or some) islands as many times as the Army wants, and you will collect gold coins from the king of the island.
In each trip, you will be asked to give the total sum of gold coins you have collected.
-----Input:-----
- The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows.
- The next line of the input contains a single integer $N$. $N$ denotes the total number of Islands.
- The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ where $ith$ number denotes the maximum number of coins that the king of $ith$ island can donate.
- Next line contains a single integer $Q$. $Q$ denotes the total number of times traveler have to go for the trip.
- Next $Q$ lines contains, two space-separated integers $Q1,Q2$ denoting the start and end number of islands, i.e. traveler will start the trip from $Q1th$ island and will go till $Q2th$ island, in each trip.
Note: islands are numbered from $1$ to $N$.
-----Output:-----
- For each trip print the total number of gold coins, traveler will collect(each on a new line).
-----Constraints:-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^4$
- $1 \leq A1, A2, A3...An \leq 10^5$
- $1 \leq Q \leq 10^3$
- $1 \leq Q1,Q2 \leq N$
-----Sample Input:-----
1
4
10 2 5 50
2
1 3
2 4
-----Sample Output:-----
17
57
-----Explanation:-----
-
In 1st Trip, traveler will go from 1st Island to 3rd Island, hence the total number of coins traveler can collect is 10+2+5 = 17
-
In 2 d Trip, traveler will go from 2nd Island to 4th Island, hence the total number of coins traveler can collect is 2+5+50 = 57
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
for i in range(int(input())):
N = int(input())
l = list(map(int, input().split()))
for j in range(int(input())):
q1, q2 = map(int, input().split())
temp = l[q1 - 1 : q2]
print(sum(temp))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Berland Football Cup starts really soon! Commentators from all over the world come to the event.
Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.
If $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment.
Organizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.
What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?
-----Input-----
The only line contains four integer numbers $n$, $m$, $a$ and $b$ ($1 \le n, m \le 10^{12}$, $1 \le a, b \le 100$), where $n$ is the initial number of the commentary boxes, $m$ is the number of delegations to come, $a$ is the fee to build a box and $b$ is the fee to demolish a box.
-----Output-----
Output the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$). It is allowed that the final number of the boxes is equal to $0$.
-----Examples-----
Input
9 7 3 8
Output
15
Input
2 7 3 7
Output
14
Input
30 6 17 19
Output
0
-----Note-----
In the first example organizers can build $5$ boxes to make the total of $14$ paying $3$ burles for the each of them.
In the second example organizers can demolish $2$ boxes to make the total of $0$ paying $7$ burles for the each of them.
In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get $5$ boxes.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m, a, b = list(map(int, input().split()))
k = n%m
print(min(k*b, (m - k)*a))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Hooray! Polycarp turned $n$ years old! The Technocup Team sincerely congratulates Polycarp!
Polycarp celebrated all of his $n$ birthdays: from the $1$-th to the $n$-th. At the moment, he is wondering: how many times he turned beautiful number of years?
According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $1$, $77$, $777$, $44$ and $999999$. The following numbers are not beautiful: $12$, $11110$, $6969$ and $987654321$.
Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).
Help Polycarpus to find the number of numbers from $1$ to $n$ (inclusive) that are beautiful.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow.
Each test case consists of one line, which contains a positive integer $n$ ($1 \le n \le 10^9$) — how many years Polycarp has turned.
-----Output-----
Print $t$ integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $1$ and $n$, inclusive.
-----Example-----
Input
6
18
1
9
100500
33
1000000000
Output
10
1
9
45
12
81
-----Note-----
In the first test case of the example beautiful years are $1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$ and $11$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = []
for i in range(1, 10):
k = 0
for l in range(1, 10):
k *= 10
k += i
s.append(k)
s.sort()
q = int(input())
while q:
n = int(input())
l = 0
r = len(s)
while l + 1 < r:
m = (l + r) // 2
if s[m] <= n:
l = m
else:
r = m
print(r)
q -= 1
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef got in the trouble! He is the king of Chefland and Chessland. There is one queen in Chefland and one queen in Chessland and they both want a relationship with him. Chef is standing before a difficult choice…
Chessland may be considered a chessboard with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). Let's denote a unit square in row $r$ and column $c$ by $(r, c)$. Chef lives at square $(X, Y)$ of this chessboard.
Currently, both queens are living in Chessland too. Each queen, when alone on the chessboard, can see all squares that lie on the same row, column or diagonal as itself. A queen from $(x_q, y_q)$ cannot see a square $(r, c)$ if the square $(X, Y)$ is strictly between them. Of course, if the queens can see each other, the kingdom will soon be in chaos!
Help Chef calculate the number of possible configurations of the queens such that the kingdom will not be in chaos. A configuration is an unordered pair of distinct squares $(x_{q1}, y_{q1})$ and $(x_{q2}, y_{q2})$ such that neither of them is the square $(X, Y)$. Two configurations are different if the position of queen $1$ is different or the position of queen $2$ is different.
-----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 four space-separated integers $N$, $M$, $X$ and $Y$.
-----Output-----
For each test case, print a single line containing one integer — the number of configurations such that the kingdom will not be in chaos.
-----Constraints-----
- $1 \le T \le 1000$
- $1 \le X \le N \le 10^2$
- $1 \le Y \le M \le 10^2$
- $2 \le N, M$
-----Example Input-----
2
3 3 2 2
4 4 2 3
-----Example Output-----
24
94
-----Explanation-----
Example case 1: Half of these configurations are:
- $(1, 1), (3, 3)$
- $(1, 1), (2, 3)$
- $(1, 1), (3, 2)$
- $(1, 2), (3, 3)$
- $(1, 2), (3, 2)$
- $(1, 2), (3, 1)$
- $(1, 3), (3, 1)$
- $(1, 3), (3, 2)$
- $(1, 3), (2, 1)$
- $(2, 1), (2, 3)$
- $(2, 1), (1, 3)$
- $(2, 1), (3, 3)$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def C(n):
return n*(n-1)//2
def sol():
equal, mini = False, min(N,M)
total_ways = 2*C(N * M)
if N==M:
equal = True
ways = 0
if not equal:
ways = (N*C(M)+M*C(N))
diag = 0
for i in range(2, mini+1):
diag += 2*C(i)
for i in range(mini+1,max(N,M)):
diag += C(mini)
diag *= 2
ways += diag
ways *= 2
else:
ways = (N*C(M)+M*C(N))
diag = 0
for i in range(2, mini):
diag += 2*C(i)
diag += C(mini)
diag *= 2
ways += diag
ways *=2
safe = total_ways - ways
l, r, t, d = Y-1, M-Y, X-1, N-X
safe_add, to_remove = 0, 0
for i in range(1,N+1):
for j in range(1, M+1):
if i==X or j==Y or abs(i-X)==abs(j-Y):
continue
else:
to_remove += 1
if l>0 and r>0 and t>0 and d>0:
dtl, dtr, dbl, dbr = min(l,t), min(r,t), min(l,d), min(r,d)
safe_add += dtl*dbr*2 + dtr*dbl*2
safe_add += t*d*2
safe_add += l*r*2
elif l>0 and r>0:
safe_add += l*r*2
elif t>0 and d>0:
safe_add += t*d*2
safe += safe_add - to_remove*2
return safe
T = int(input())
for _ in range(T):
N, M, X, Y = [int(x) for x in input().split()]
print(sol())
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Vasya's older brother, Petya, attends an algorithm course in his school. Today he learned about matchings in graphs. Formally, a set of edges in a graph is called a matching if no pair of distinct edges in the set shares a common endpoint.
Petya instantly came up with an inverse concept, an antimatching. In an antimatching, any pair of distinct edges should have a common endpoint.
Petya knows that finding a largest matching in a graph is a somewhat formidable task. He wonders if finding the largest antimatching is any easier. Help him find the number of edges in a largest antimatching in a given graph.
-----Input:-----
The first line contains T$T$, number of test cases per file.
The first line of each test case contains two integers n$n$ and m−$m-$ the number of vertices and edges of the graph respectively (1≤n≤104$1 \leq n \leq 10^4$, 0≤m≤104$0 \leq m \leq 10^4$).
The next m$m$ lines describe the edges. The i$i$-th of these lines contains two integers ui$u_i$ and vi−$v_i-$ the indices of endpoints of the i$i$-th edge (1≤ui,vi≤n$1 \leq u_i, v_i \leq n$, ui≠vi$u_i \neq v_i$).
It is guaranteed that the graph does not contain self-loops nor multiple edges. It is not guaranteed that the graph is connected.
-----Output:-----
Print a single number per test case −$-$ the maximum size of an antichain in the graph.
-----Constraints-----
- 1≤T≤10$1 \leq T \leq 10$
- 1≤n≤104$1 \leq n \leq 10^4$
- 0≤m≤104$0 \leq m \leq 10^4$
- 1≤ui,vi≤n$1 \leq u_i, v_i \leq n$
- ui≠vi$u_i \neq v_i$
-----Sample Input:-----
3
3 3
1 2
1 3
2 3
4 2
1 2
3 4
5 0
-----Sample Output:-----
3
1
0
-----EXPLANATION:-----
In the first sample all three edges form an antimatching.
In the second sample at most one of the two edges can be included in an antimatching since they do not share common endpoints.
In the third sample there are no edges, hence the answer is 0$0$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def detect_triangle(adj):
for x in range(len(adj)):
for y in adj[x]:
if not set(adj[x]).isdisjoint(adj[y]):
return True
for _ in range(int(input())):
n,m=list(map(int,input().split()))
graph=[[] for i in range(n)]
for i in range(m):
u,v=list(map(int,input().split()))
graph[u-1].append(v-1)
graph[v-1].append(u-1)
h=[]
for i in range(len(graph)):
h.append(len(graph[i]))
h1=max(h)
if h1>=3:
print(h1)
continue
if detect_triangle(graph):
print(3)
continue
print(h1) # cook your dish here
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are standing near a very strange machine. If you put C cents in the machine, the remaining money in your purse will transform in an unusual way. If you have A dollars and B cents remaining in your purse after depositing the C cents, then after the transformation you will have B dollars and A cents. You can repeat this procedure as many times as you want unless you don't have enough money for the machine. If at any point C > B and A > 0, then the machine will allow you to break one of the A dollars into 100 cents so you can place C cents in the machine. The machine will not allow you to exchange a dollar for 100 cents if B >= C.
Of course, you want to do this to maximize your profit. For example if C=69 and you have 9 dollars and 77 cents then after you put 69 cents in the machine you will have 8 dollars and 9 cents (9.77 --> 9.08 --> 8.09). But I should warn you that you can't cheat. If you try to throw away 9 cents before the transformation (in order to obtain 99 dollars and 8 cents after), the machine will sense you are cheating and take away all of your money. You need to know how many times you should do this transformation in order to make a maximum profit. Since you are very busy man, you want to obtain the maximum possible profit in the minimum amount of time.
-----Input-----
The first line contains a single integer T <= 40, the number of test cases. T test cases follow. The only line of each test case contains three nonnegative integers A, B and C where A, B, C < 100. It means that you have A dollars and B cents in your purse and you need to put C cents in the machine to make the transformation.
-----Output-----
For each test case, output a single line containing the minimal number of times you should do this transformation in order to make a maximal profit. It is guaranteed that the answer is less than 10000.
-----Example-----
Input:
2
9 77 69
98 99 69
Output:
4
0
-----Explanation-----
In the first test we have the following sequence: 9.77, 8.09, 40.07, 38.39, 70.37, 68.69, 0.68. After last step we have not enough money for further transformations. The maximal profit will be after 4 transformations.
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())):
a,b,c=list(map(int, input().split()))
p=a*100+b
mx=p
ans, cnt = 0, 0
while True:
cnt+=1
if p<c or cnt==10000:
break
else:
p-=c
a=p//100
b=p%100
p=b*100+a
if p>mx:
mx=p
ans=cnt
print(ans)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You have found $M$ different types of jewels in a mine and each type of jewel is present in an infinite number.
There are $N$ different boxes located at position $(1 ,2 ,3 ,...N)$.
Each box can collect jewels up to a certain number ( box at position $i$ have $i$ different partitions and each partition can collect at most one jewel of any type).
Boxes at odd positions are already fully filled with jewels while boxes at even positions are completely empty.
Print the total number of different arrangements possible so that all boxes can be fully filled.
As the answer can be very large you can print it by doing modulo with 1000000007(10^9+7).
-----Input:-----
- First line will contain $T$, number of testcases.
- Each testcase contains of a single line of input, two integers $N , M$.
-----Output:-----
For each testcase, Print the total number of different arrangement.
-----Constraints-----
- $1 \leq T \leq 20000$
- $1 \leq N \leq 1e9$
- $1 \leq M \leq 1e14$
-----Sample Input:-----
2
1 10
5 2
-----Sample Output:-----
1
64
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:
M = 1000000007
n, m = list(map(int, input().split()))
ans = 1
tt = n//2
tt = tt * (tt + 1)
ans = pow(m, tt, M)
print(ans)
t -= 1
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef gives an integer $K$ in the input. If the given number is beautiful binary number, print it, Else find its previous beautiful binary number. A beautiful binary number is a number whose binary representation does not contain any consecutive 1s.
Note: 1 is also a beautiful binary number.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, print a beautiful number.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq K \leq 10^5$
-----Sample Input:-----
3
3
6
8
-----Sample Output:-----
2
5
8
-----EXPLANATION:-----
For 1) 3 is not a beautiful binary number because the binary representation of 3 is "11" which has consecutive 1s. hence 2 which is less than 3 is printed.
For 3) 8 is already a beautiful binary number with no consecutive 1s in its binary representation. so, print 8 as it is.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
pref = []
for i in range(10 ** 5 + 10):
b = bin(i)[2:]
if not any(b[j] == b[j+1] == '1' for j in range(len(b) - 1)):
pref.append(i)
else:
pref.append(pref[-1])
for i in range(int(input())):
print(pref[int(input())])
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef had a sequence of positive integers with length $N + K$. He managed to calculate the arithmetic average of all elements of this sequence (let's denote it by $V$), but then, his little brother deleted $K$ elements from it. All deleted elements had the same value.
Chef still knows the remaining $N$ elements — a sequence $A_1, A_2, \ldots, A_N$. Help him with restoring the original sequence by finding the value of the deleted elements or deciding that there is some mistake and the described scenario is impossible.
Note that the if it is possible for the deleted elements to have the same value, then it can be proven that it is unique. Also note that this value must be a positive integer.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains three space-separated integers $N$, $K$ and $V$.
- 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 value of the deleted elements, or $-1$ if there is a mistake.
-----Constraints-----
- $1 \le T \le 100$
- $1 \le N, K \le 100$
- $1 \le V \le 10^5$
- $1 \le A_i \le 10^5$ for each valid $i$
-----Subtasks-----
Subtask #1 (100 points): original constraints
-----Example Input-----
3
3 3 4
2 7 3
3 1 4
7 6 5
3 3 4
2 8 3
-----Example Output-----
4
-1
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def __starting_point():
t=int(input())
for _ in range(t):
n,k,v=map(int,input().split())
li=list(map(int,input().split()))
sumn=0
for i in range(n):
sumn=sumn+li[i]
sumk=v*(n+k)-sumn
e=int(sumk/k)
r=sumk%k
if e<=0:
print(-1)
elif r!=0:
print(-1)
else:
print(e)
__starting_point()
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Petya recieved a gift of a string s with length up to 10^5 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves: Extract the first character of s and append t with this character. Extract the last character of t and append u with this character.
Petya wants to get strings s and t empty and string u lexicographically minimal.
You should write a program that will help Petya win the game.
-----Input-----
First line contains non-empty string s (1 ≤ |s| ≤ 10^5), consisting of lowercase English letters.
-----Output-----
Print resulting string u.
-----Examples-----
Input
cab
Output
abc
Input
acdb
Output
abdc
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
S = input()
mn = [ 300 for i in range( len( S ) ) ]
for i in range( len( S ) - 1, -1, -1 ):
if i == len( S ) - 1:
mn[ i ] = ord( S[ i ] )
else:
mn[ i ] = min( mn[ i + 1 ], ord( S[ i ] ) )
ans = ""
dq = deque()
for i in range( len( S ) ):
dq.append( ord( S[ i ] ) )
while len( dq ) and ( i + 1 == len( S ) or dq[ len( dq ) - 1 ] <= mn[ i + 1 ] ):
ans += chr( dq[ len( dq ) - 1 ] )
dq.pop()
print( ans )
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Raj loves to listen to songs in his free time. It’s his birthday tomorrow and his friend Neelansh wants his gift to be the most unique. Being great at making music, he decides to produce a song for him. However, Raj likes songs according to their beauty. He determines the beauty of the song as the number of times all the octave musical tones are completed in ascending order.
He begins with a jumbled tone of length N and numbers each octave tone as 1,2,3….8.
Neelansh wants to maximize the beauty of the song but since he uses the trial version of the software,
- He cannot change the size of N.
- He cannot introduce any new tone, but can choose any two tones and swap their positions
However, Neelansh just received a mail that he needs to submit all his pending assignments by tomorrow. He has tons of assignments left to do, but he doesn’t want to spoil the idea of his gift. Can you help him?
-----INPUT-----
- The first line contains a single integer T- the number of test cases
- The first line of each test case contains a single integer N- the length of the song
- The second line contains N- space separated integers ai, ai+1,.....aN
-----OUTPUT-----
For each test case, print a single line containing one integer- the maximum possible beauty of the song
-----CONSTRAINTS-----
1<=T<=102
1<=N<=105
1<=a<=8
-----EXAMPLE INPUT-----
2
8
1 2 3 4 5 6 7 8
16
1 2 1 2 3 3 4 4 5 5 6 6 7 8 7 8
-----EXAMPLE OUTPUT-----
1
2
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for _ in range(int(input())):
n = int(input())
ar = list(map(int,input().split()))
d = {}
for ele in ar:
if ele in d:
d[ele] += 1
else:
d[ele] = 1
m = 99999
count = 0
for ele in d:
count+=1
if m>d[ele]:
m = d[ele]
if count!=8:
print(0)
else:
print(m)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
"I don't have any fancy quotes." - vijju123
Chef was reading some quotes by great people. Now, he is interested in classifying all the fancy quotes he knows. He thinks that all fancy quotes which contain the word "not" are Real Fancy; quotes that do not contain it are regularly fancy.
You are given some quotes. For each quote, you need to tell Chef if it is Real Fancy or just regularly fancy.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single string $S$ denoting a quote.
-----Output-----
For each test case, print a single line containing the string "Real Fancy" or "regularly fancy" (without quotes).
-----Constraints-----
- $1 \le T \le 50$
- $1 \le |S| \le 100$
- each character of $S$ is either a lowercase English letter or a space
-----Subtasks-----
Subtask #1 (100 points): original constraints
-----Example Input-----
2
i do not have any fancy quotes
when nothing goes right go left
-----Example Output-----
Real Fancy
regularly fancy
-----Explanation-----
Example case 1: "i do not have any fancy quotes"
Example case 2: The word "not" does not appear in the given quote.
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 re
t=int(input())
while(t>0):
s=list(input().split(' '))
if("not" in s):
print("Real Fancy")
else:
print("regularly fancy")
t=t-1
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Motu and Patlu are racing against each other on a circular track of radius $R$. Initially they are at the same point on the track and will run in same direction .The coach ordered them to run $X$ rounds of the circular field. Patlu wants to know how many times they will meet after the race starts and before any of them finishes $X$ rounds. But he is busy in warm up so he wants you to calculate this. You are given speed of both Motu and Patlu ($A$ and $B$).
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, four integers $X, R, A, B$.
-----Output:-----
For each testcase, output in a single line answer the number of times whey will meet before any of them completes $X$ rounds.
-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq R \leq 10^9$
- $1 \leq X \leq 10^9$
- $1 \leq A \leq 10^9$
- $1 \leq B \leq 10^9$
- Speed of both are different
-----Sample Input:-----
2
3 10 2 5
2 20 5 10
-----Sample Output:-----
1
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# cook your dish here
import math
def swap(a,b):
return b,a
t = int(input())
while(t!=0):
z = list(map(int,input().strip().split(" ")))
x=z[0]
r=z[1]
a=z[2]
b=z[3]
#p = math.pi
peri = 2*r
tp = x*peri
if(a<b):
a,b=swap(a,b)
t1 = tp/a
d2 = t1* b
dd = abs(tp-d2)
if(dd%peri==0):
print(int(dd//peri)-1)
else:
n = int(dd//peri)
print(n)
t-=1
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Anas is playing an amazing game on a grid with $N$ rows and $M$ columns. The rows are numbered $1$ through $N$ from top to bottom and the columns are numbered $1$ through $M$ from left to right.
Anas wants to destroy this grid. To do that, he wants to send two heroes from the top left cell to the bottom right cell:
- The first hero visits cells in row-major order: $(1,1) \rightarrow (1,2) \rightarrow \ldots \rightarrow (1,M) \rightarrow (2,1) \rightarrow (2,2) \rightarrow \ldots \rightarrow (2,M) \rightarrow \ldots \rightarrow (N,M)$.
- The second hero visits cells in column-major order: $(1,1) \rightarrow (2,1) \rightarrow \ldots \rightarrow (N,1) \rightarrow (1,2) \rightarrow (2,2) \rightarrow \ldots \rightarrow (N,2) \rightarrow \ldots \rightarrow (N,M)$.
We know that each hero destroys the first cell he visits, rests in the next $K$ cells he visits without destroying them, then destroys the next cell he visits, rests in the next $K$ cells, destroys the next cell, and so on until he reaches (and rests in or destroys) the last cell he visits.
Anas does not know the value of $K$. Therefore, for each value of $K$ between $0$ and $N \cdot M - 1$ inclusive, he wants to calculate the number of cells that will be destroyed by at least one hero. Can you help him?
-----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 $M$.
-----Output-----
For each test case, print a single line containing $N \cdot M$ space-separated integers as described above.
-----Constraints-----
- $1 \le T \le 100$
- $2 \le N, M \le 1,000$
- the sum of $N \cdot M$ over all test cases does not exceed $2 \cdot 10^6$
-----Subtasks-----
Subtask #1 (30 points):
- $2 \le N, M \le 50$
- the sum of $N \cdot M$ over all test cases does not exceed $5,000$
Subtask #2 (70 points): original constraints
-----Example Input-----
1
2 3
-----Example Output-----
6 4 3 3 2 1
-----Explanation-----
Example case 1:
- $K = 0$: All cells will be destroyed by the heroes.
- $K = 1$: The first hero will destroy the cells $[(1,1), (1,3), (2,2)]$, while the second one will destroy the cells $[(1,1), (1,2), (1,3)]$.
- $K = 2$: The first hero will destroy the cells $[(1,1), (2,1)]$, while the second one will destroy the cells $[(1,1), (2,2)]$.
- $K = 3$: The first hero will destroy the cells $[(1,1), (2,2)]$, while the second one will destroy the cells $[(1,1), (1,3)]$.
- $K = 4$: The first hero will destroy the cells $[(1,1), (2,3)]$ and the second one will also destroy the cells $[(1,1), (2,3)]$.
- $K = 5$ : The first hero will destroy the cell $(1,1)$ and the second one will also destroy the cell $(1,1)$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Code chef problem DESTCELL, Destroy Cells
"""
def find_destroyed_cells(cell_advance, n, m, k):
row = 1
col = 1
destroyed_cells = {(1, 1)}
while True:
row, col = cell_advance(row, col, n, m, k)
if row <= n and col <= m:
destroyed_cells.add((row, col))
else:
break
return destroyed_cells
def cell_advance_hero1(row, col, n, m, k):
return row + (col + k) // m, (col + k) % m + 1
def cell_advance_hero2(row, col, n, m, k):
return (row + k) % n + 1, col + (row + k)//n
def main():
t = int(input())
for _ in range(t):
n, m = [int(s) for s in input().split(' ')]
counts = []
for k in range(n*m):
cells_h1 = find_destroyed_cells(cell_advance_hero1, n, m, k)
cells_h2 = find_destroyed_cells(cell_advance_hero2, n, m, k)
destroyed = len(cells_h1) + len(cells_h2) - len(cells_h1 & cells_h2)
counts.append(destroyed)
print(' '.join([str(c) for c in counts]))
main()
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Prime numbers are arranged in a ordered list U$U$, in increasing order. Let S$S$ be a sublist of U$U$ with a unique property that for every element A$A$ belonging to list S$S$, if i$i$ denotes the index of A$A$ in list U$U$, than i$i$ also belongs to list U$U$.
Given N$N$, find sum of first N$N$ elements of list S$S$, assuming 1-based indexing.
As the sum can be very large, print the sum modulo 109+7$10^{9}+7$.
-----Input:-----
-The first line of the input contains a single integer T$T$ denoting the number of test cases.
-Only line of each test case has an integer N$N$ .
-----Output:-----
For each test case, print a single integer denoting the sum of first N$N$ elements of set S$S$ modulo 109+7$10^{9}+7$.
-----Constraints-----
- 1≤T≤10000$1 \leq T \leq 10000$
- 1≤N≤1000$1 \leq N \leq 1000$
-----Subtasks-----
-
20 points :
-
1≤T≤10000$1 \leq T \leq 10000$
-
1≤N≤10$1 \leq N \leq 10$
-
20 points :
-
1≤T≤100$1 \leq T \leq 100$
-
1≤N≤100$1 \leq N \leq 100$
-
60 points : Original Constraints
-----Sample Input:-----
2
1
2
-----Sample Output:-----
3
8
-----EXPLANATION:-----
Example case 1:
First few elements of set S$S$ are {3,5,11…} , so sum is 3.
Example case 2:
Sum is 3+5=8.
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 prime(aa):
f=0
for y in ar:
if aa%y==0:
return 0
return 1
ar=[]
ar.append(2)
pc=3
te=int(input())
for _ in range(te):
a=int(input())
f=0
c=0
add=0
for x in ar:
try:
add=add+ar[x-1]
except:
while True:
if prime(pc)==1:
ar.append(pc)
if x<=len(ar):
break
pc+=1
pc+=1
add=add+ar[x-1]
c+=1
if c==a:
break
print(add)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a sequence of n integers a1, a2, ..., an and an integer d.
Find the length of the shortest non-empty contiguous subsequence with sum of elements at least d. Formally, you should find the smallest positive integer k with the following property: there is an integer s (1 ≤ s ≤ N-k+1) such that as + as+1 + ... + as+k-1 ≥ d.
-----Input-----
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains two space-separated integers n and d.
- The second line contains n space-separated integers a1, a2, ..., an.
-----Output-----
For each test case, print a single line containing one integer — the length of the shortest contiguous subsequence with sum of elements ≥ d. If there is no such subsequence, print -1 instead.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- -109 ≤ d ≤ 109
- -104 ≤ ai ≤ 104
- 1 ≤ sum of n over all test cases ≤ 2 · 105
-----Example-----
Input:
2
5 5
1 2 3 1 -5
5 1
1 2 3 1 -5
Output:
2
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
import collections
def shortestSubarray(A, K):
N = len(A)
P = [0]
for x in A:
P.append(P[-1] + x)
#Want smallest y-x with Py - Px >= K
ans = N+1 # N+1 is impossible
monoq = collections.deque() #opt(y) candidates, represented as indices of P
for y, Py in enumerate(P):
#Want opt(y) = largest x with Px <= Py - K
if not monoq:
if Py>=K: return 1
while monoq and Py <= P[monoq[-1]]:
monoq.pop()
while monoq and Py - P[monoq[0]] >= K:
ans = min(ans, y - monoq.popleft())
monoq.append(y)
return ans if ans < N+1 else -1
for t in range(int(input())):
N, D = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
print(shortestSubarray(A, D))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Dhiraj loves Chocolates.He loves chocolates so much that he can eat up to $1000$ chocolates a day. But his mom is fed up by this habit of him and decides to take things in her hand.
Its diwali Season and Dhiraj has got a lot of boxes of chocolates and Dhiraj's mom is afraid that dhiraj might eat all boxes of chocolates.
So she told Dhiraj that he can eat only exactly $k$ number of chocolates and dhiraj has to finish all the chocolates in box selected by him and then move on to next box of chocolate.Now Dhiraj is confused that whether he will be able to eat $k$ number of chocolates or not. Since dhiraj is weak at maths,he asks for your help to tell him whether he can eat $k$ number of chocolates or not.
So given number of chocolates are $k$ which dhiraj has to eat and the boxes of chocolates each containing some number of chocolates, tell whether dhiraj will be able to eat $k$ number of chocolates or not.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- $k$, representing the number of chocolates dhiraj has to eat.
- the third line contains $N$ representing the no. of boxes of chocolates.
- fourth line contains list of $a[]$ size $N$ specifying the number of chocolates in each Box.
-----Output:-----
- For each testcase, output in a single line answer $0$ or $1$.
- $0$ if dhiraj cant eat $k$ chocolates from given combination and $1$ if he can eat $k$ chocolates from given combination.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 10^7$
- $1 \leq N \leq 800$
- $1 \leq a[i] \leq 10^3$
-----Sample Input:-----
2
20
5
8 7 2 10 5
11
4
6 8 2 10
-----Sample Output:-----
1
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def isSubsetSum(arr, n, sum):
subset = [ [False for j in range(sum + 1)] for i in range(3) ]
for i in range(n + 1):
for j in range(sum + 1):
if (j == 0):subset[i % 2][j] = True
elif (i == 0):subset[i % 2][j] = False
elif (arr[i - 1] <= j):subset[i % 2][j] = subset[(i + 1) % 2][j - arr[i - 1]] or subset[(i + 1)% 2][j]
else:subset[i % 2][j] = subset[(i + 1) % 2][j]
return subset[n % 2][sum]
for _ in range(int(input())):
k,n,a = int(input()),int(input()),list(map(int,input().split()))
if sum(a) < k or k < min(a):print(0);continue
print(1) if isSubsetSum(a, n, k) else print(0)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
This is one more story about our old friend, the Despotic King. Once every year, it was customary for the king to give audience to the rich merchants of his country in a large hall. On that day, the merchants were ushered in to meet the king one by one and after paying their respects to the king they were seated in the auditorium.
It was the job of the minister to introduce each merchant, as he arrived, to the others in the hall. He would announce his name and his wealth. However, our quirky king demanded that in addition, he should also announce the rank of the merchant among all those in the hall (at the time of his arrival) in terms of his wealth.
For example, let us suppose that the wealth of the 6 merchants who met the king (in the order in which they arrived) is given by the sequence
78246840398978246840398978 \quad 24 \quad 68 \quad 40 \quad 39 \quad 89
Then, clearly the first merchant is the richest in the hall when he enters it (since there are no others in the hall) and so his rank is $1$. Since $24 < 78$ the rank of the second merchant when he enters the hall is $2$. The rank of the third merchant is also $2$ since $24 < 68 < 78$. The rank of the fourth merchant is $3$ since $24 < 40 < 68 < 78$, the rank of the fifth merchant is $4$ since $24 < 39 < 40 < 68 < 78$ and finally the rank of the sixth merchant is $1$ since $24 < 39 < 40 < 68 < 78 < 89$. The sequence of ranks announced by the minister would thus be:
1223411223411 \quad 2 \quad 2 \quad 3 \quad 4 \quad 1
Your task is to write a program that takes as input a sequence of distinct positive integers indicating the wealth of the merchants in the order in which they visit the king and outputs the sequence of ranks announced by the minister.
-----Input:-----
The first line contains a single integer $N$ indicating the number of merchants. The next $N$ lines (line $2,...,N+1$) describe the wealth of these $N$ merchants. Line $i+1$ contains a single positive integer indicating the wealth of the $i^{th}$ merchant to enter the hall.
-----Output:-----
Your output should consist of $N$ lines. Line $i$ should be the rank announced when the $i^{th}$ minister enters the hall.
-----Constraints:-----
- $1 \leq N \leq 45000$.
- No two merchants have the same wealth.
- You may also assume that in $30 \%$ of of the inputs $1 \leq N \leq 8000$.
-----Sample Input-----
6
78
24
68
40
39
89
-----Sample Output-----
1
2
2
3
4
1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
arr=[]
n=int(input())
for i in range(n):
a=int(input())
arr.append(a)
arr.sort()
p=arr.index(a)
print((i-p)+1)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Nadaca is a country with N$N$ cities. These cities are numbered 1$1$ through N$N$ and connected by M$M$ bidirectional roads. Each city can be reached from every other city using these roads.
Initially, Ryan is in city 1$1$. At each of the following K$K$ seconds, he may move from his current city to an adjacent city (a city connected by a road to his current city) or stay at his current city. Ryan also has Q$Q$ conditions (a1,b1),(a2,b2),…,(aQ,bQ)$(a_1, b_1), (a_2, b_2), \ldots, (a_Q, b_Q)$ meaning that during this K$K$-second trip, for each valid i$i$, he wants to be in city ai$a_i$ after exactly bi$b_i$ seconds.
Since you are very good with directions, Ryan asked you to tell him how many different trips he could make while satisfying all conditions. Compute this number modulo 109+7$10^9 + 7$. A trip is a sequence of Ryan's current cities after 1,2,…,K$1, 2, \ldots, K$ seconds.
-----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 three space-separated integers N$N$, M$M$ and K$K$.
- Each of the next M$M$ lines contains two space-separated integers u$u$ and v$v$ denoting a road between cities u$u$ and v$v$.
- The next line contains a single integer Q$Q$.
- Q$Q$ lines follow. For each i$i$ (1≤i≤Q$1 \le i \le Q$), the i$i$-th of these lines contains two space-separated integers ai$a_i$ and bi$b_i$.
-----Output-----
For each test case, print a single line containing one integer — the number of trips Ryan can make, modulo 109+7$10^9+7$.
-----Constraints-----
- 1≤T≤50$1 \le T \le 50$
- 1≤N,M,K,Q≤9,000$1 \le N, M, K, Q \le 9,000$
- 1≤ui,vi≤N$1 \le u_i, v_i \le N$ for each valid i$i$
- ui≠vi$u_i \neq v_i$ for each valid i$i$
- there is at most one road between each pair of cities
- each city is reachable from every other city
- 1≤ai≤N$1 \le a_i \le N$ for each valid i$i$
- 0≤bi≤K$0 \le b_i \le K$ for each valid i$i$
- the sum of N$N$ over all test cases does not exceed 9,000$9,000$
- the sum of K$K$ over all test cases does not exceed 9,000$9,000$
- the sum of M$M$ over all test cases does not exceed 9,000$9,000$
- the sum of Q$Q$ over all test cases does not exceed 9,000$9,000$
-----Subtasks-----
Subtask #1 (20 points):
- the sum of N$N$ over all test cases does not exceed 400$400$
- the sum of K$K$ over all test cases does not exceed 400$400$
- the sum of M$M$ over all test cases does not exceed 400$400$
- the sum of Q$Q$ over all test cases does not exceed 400$400$
Subtask #2 (80 points): original constraints
-----Example Input-----
3
4 3 3
1 2
1 3
1 4
0
4 3 3
1 2
1 3
1 4
1
2 2
4 3 3
1 2
1 3
1 4
1
2 1
-----Example Output-----
28
4
6
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
T = int(input())
for _ in range(T):
N, M, K = [int(x) for x in input().split()]
UV = [[int(x) for x in input().split()] for _ in range(M)]
Q = int(input())
AB = [[int(x) for x in input().split()] for _ in range(Q)]
X = [[i] for i in range(N)]
for u, v in UV:
X[u - 1] += [v - 1]
X[v - 1] += [u - 1]
A = [[1 if i > 0 or j == 0 else 0 for j in range(N)] for i in range(K + 1)]
for a, b in AB:
A[b] = [1 if i == a - 1 else 0 for i in range(N)]
if A[0][0] == 1:
for k in range(K - 1, -1, -1):
for i in range(N):
if A[k][i] != 0:
A[k][i] = sum(A[k + 1][j] for j in X[i])
print(A[0][0])
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.
The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].
You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.
-----Input-----
The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 10^6). Each character in s will be either "l" or "r".
-----Output-----
Output n lines — on the i-th line you should print the i-th stone's number from the left.
-----Examples-----
Input
llrlr
Output
3
5
4
2
1
Input
rrlll
Output
1
2
5
4
3
Input
lrlrr
Output
2
4
5
3
1
-----Note-----
In the first example, the positions of stones 1, 2, 3, 4, 5 will be $\frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \frac{3}{16}, \frac{5}{32}$, respectively. So you should print the sequence: 3, 5, 4, 2, 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = input()
a, b = [i for i, d in enumerate(t, 1) if d == 'l'], [i for i, d in enumerate(t, 1) if d == 'r']
a.reverse()
print('\n'.join(map(str, b)))
print('\n'.join(map(str, a)))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Rohit collects coins: he has exactly one coin for every year from 1 to n. Naturally, Rohit keeps all the coins in his collection in the order in which they were released. Once Rohit's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order. That is, he took a certain segment [l, r] and reversed it. At that, the segment's endpoints did not coincide. For example, if n = 8, then initially Rohit's coins were kept in the order 1 2 3 4 5 6 7 8. If Rohit's younger brother chose the segment [2, 6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Rohit suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 … n using exactly one segment reversal. If it is possible, find the segment itself.
-----Input:-----
- The first line contains an integer N which is the number of coins in Rohit's collection.
- The second line contains space-separated n integers which are the spoilt sequence of coins. It is guaranteed that the given sequence is a permutation, i.e. it contains only integers from 1 to n, and every number is used exactly 1 time.
-----Output:-----
If it is impossible to obtain the given permutation from the original one in exactly one action, print 0 0. Otherwise, print two numbers l, r (1 ≤ l < r ≤ n) which are the endpoints of the segment that needs to be reversed to obtain from permutation 1 2 … n the given one.
-----Constraints-----
- $1 \leq N \leq 1000$
- $1 \leq A[N] \leq 10^9$
-----Sample Input:-----
8
1 6 5 4 3 2 7 8
-----Sample Output:-----
2 6
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
a=list(map(int,input().split()))
l,r=-1,-1
for i in range(n):
if a[i]!=i+1:
l=i
break
for i in range(n-1,-1,-1):
if a[i]!=i+1:
r=i
break
j=r+1
for i in range(l,r+1):
if a[i]==j:
j-=1
continue
else:
print(0,0)
return
print(l+1,r+1)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?
Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same!
The storehouse is represented as matrix n × m. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells.
Sofa A is standing to the left of sofa B if there exist two such cells a and b that x_{a} < x_{b}, a is covered by A and b is covered by B. Sofa A is standing to the top of sofa B if there exist two such cells a and b that y_{a} < y_{b}, a is covered by A and b is covered by B. Right and bottom conditions are declared the same way.
Note that in all conditions A ≠ B. Also some sofa A can be both to the top of another sofa B and to the bottom of it. The same is for left and right conditions.
The note also stated that there are cnt_{l} sofas to the left of Grandpa Maks's sofa, cnt_{r} — to the right, cnt_{t} — to the top and cnt_{b} — to the bottom.
Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions.
Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.
-----Input-----
The first line contains one integer number d (1 ≤ d ≤ 10^5) — the number of sofas in the storehouse.
The second line contains two integer numbers n, m (1 ≤ n, m ≤ 10^5) — the size of the storehouse.
Next d lines contains four integer numbers x_1, y_1, x_2, y_2 (1 ≤ x_1, x_2 ≤ n, 1 ≤ y_1, y_2 ≤ m) — coordinates of the i-th sofa. It is guaranteed that cells (x_1, y_1) and (x_2, y_2) have common side, (x_1, y_1) ≠ (x_2, y_2) and no cell is covered by more than one sofa.
The last line contains four integer numbers cnt_{l}, cnt_{r}, cnt_{t}, cnt_{b} (0 ≤ cnt_{l}, cnt_{r}, cnt_{t}, cnt_{b} ≤ d - 1).
-----Output-----
Print the number of the sofa for which all the conditions are met. Sofas are numbered 1 through d as given in input. If there is no such sofa then print -1.
-----Examples-----
Input
2
3 2
3 1 3 2
1 2 2 2
1 0 0 1
Output
1
Input
3
10 10
1 2 1 1
5 5 6 5
6 4 5 4
2 1 2 0
Output
2
Input
2
2 2
2 1 1 1
1 2 2 2
1 0 0 0
Output
-1
-----Note-----
Let's consider the second example. The first sofa has 0 to its left, 2 sofas to its right ((1, 1) is to the left of both (5, 5) and (5, 4)), 0 to its top and 2 to its bottom (both 2nd and 3rd sofas are below). The second sofa has cnt_{l} = 2, cnt_{r} = 1, cnt_{t} = 2 and cnt_{b} = 0. The third sofa has cnt_{l} = 2, cnt_{r} = 1, cnt_{t} = 1 and cnt_{b} = 1.
So the second one corresponds to the given conditions.
In the third example The first sofa has cnt_{l} = 1, cnt_{r} = 1, cnt_{t} = 0 and cnt_{b} = 1. The second sofa has cnt_{l} = 1, cnt_{r} = 1, cnt_{t} = 1 and cnt_{b} = 0.
And there is no sofa with the set (1, 0, 0, 0) so the answer is -1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from sys import stdin, stdout
k = int(stdin.readline())
n, m = map(int, stdin.readline().split())
left, right, down, up = [], [], [], []
coordinates = []
for i in range(k):
x1, y1, x2, y2 = map(int, stdin.readline().split())
if x1 == x2:
if y1 < y2:
coordinates.append((x1, y1, x2, y2, i))
else:
coordinates.append((x2, y2, x1, y1, i))
else:
if x1 < x2:
coordinates.append((x1, y1, x2, y2, i))
else:
coordinates.append((x2, y2, x1, y1, i))
left.append(coordinates[-1])
right.append(coordinates[-1])
up.append(coordinates[-1])
down.append(coordinates[-1])
left.sort(key = lambda x: (x[0], x[2]))
down.sort(key = lambda x: (x[1], x[3]))
challengers = [[], [], [], []]
cntl, cntr, cntd, cntu = map(int, stdin.readline().split())
label = 1
if cntl or not cntl:
for i in range(cntl, -1, -1):
if (left[i][0], left[i][2]) == (left[cntl][0], left[cntl][2]):
challengers[0].append(left[i][-1])
else:
break
for i in range(cntl + 1, k):
if (left[i][0], left[i][2]) == (left[cntl][0], left[cntl][2]) and left[i][2] > left[i][0]:
label = 0
if (left[i][0], left[i][2]) == (left[cntl][0], left[cntl][2]):
challengers[0].append(left[i][-1])
else:
break
if cntr or not cntr:
for i in range(k - 1 - cntr, k):
if (left[i][0], left[i][2]) == (left[k - 1 - cntr][0], left[k - 1 - cntr][2]):
challengers[1].append(left[i][-1])
else:
break
for i in range(k - 2 - cntr, -1, -1):
if (left[i][0], left[i][2]) == (left[k - 1 - cntr][0], left[k - 1 - cntr][2]) and left[i][2] > left[i][0]:
label = 0
if (left[i][0], left[i][2]) == (left[k - 1 - cntr][0], left[k - 1 - cntr][2]):
challengers[1].append(left[i][-1])
else:
break
#!!!!!!!!!!!
if cntd or not cntd:
for i in range(cntd, -1, -1):
if (down[i][1], down[i][3]) == (down[cntd][1], down[cntd][3]):
challengers[2].append(down[i][-1])
else:
break
for i in range(cntd + 1, k):
if (down[i][1], down[i][3]) == (down[cntd][1], down[cntd][3]) and down[i][3] > down[i][1]:
label = 0
if (down[i][1], down[i][3]) == (down[cntd][1], down[cntd][3]):
challengers[2].append(down[i][-1])
else:
break
if cntu or not cntu:
for i in range(k - 1 - cntu, k):
if (down[i][1], down[i][3]) == (down[k - 1 - cntu][1], down[k - 1 - cntu][3]):
challengers[3].append(down[i][-1])
else:
break
for i in range(k - 2 - cntu, -1, -1):
if (down[i][1], down[i][3]) == (down[k - 1 - cntu][1], down[k - 1 - cntu][3]) and down[i][3] > down[i][1]:
label = 0
if (down[i][1], down[i][3]) == (down[k - 1 - cntu][1], down[k - 1 - cntu][3]):
challengers[3].append(down[i][-1])
else:
break
ans = set(challengers[0]) & set(challengers[1]) & set(challengers[2]) & set(challengers[3])
if not len(ans) or not label:
stdout.write('-1')
else:
stdout.write(str(list(ans)[0] + 1))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to a_{i}. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 360) — the number of pieces into which the delivered pizza was cut.
The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 360) — the angles of the sectors into which the pizza was cut. The sum of all a_{i} is 360.
-----Output-----
Print one integer — the minimal difference between angles of sectors that will go to Vasya and Petya.
-----Examples-----
Input
4
90 90 90 90
Output
0
Input
3
100 100 160
Output
40
Input
1
360
Output
360
Input
4
170 30 150 10
Output
0
-----Note-----
In first sample Vasya can take 1 and 2 pieces, Petya can take 3 and 4 pieces. Then the answer is |(90 + 90) - (90 + 90)| = 0.
In third sample there is only one piece of pizza that can be taken by only one from Vasya and Petya. So the answer is |360 - 0| = 360.
In fourth sample Vasya can take 1 and 4 pieces, then Petya will take 2 and 3 pieces. So the answer is |(170 + 10) - (30 + 150)| = 0.
Picture explaning fourth sample:
[Image]
Both red and green sectors consist of two adjacent pieces of pizza. So Vasya can take green sector, then Petya will take red sector.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
mn = 360
for i in range(n):
x = 0
for j in range(i, n):
x += a[j]
mn = min(mn, abs(x - (360 - x)))
print(mn)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Given a binary string $S$ consisting of only 1’s and 0’s where 1 represents a Square and 0 represents a Circle. The diameter of the circle and the side of the square must be any integer (obviously > 0) . You will have to perfectly inscribe (as shown in the example below) the respective geometric figure at $S$$i+1$ inside of $S$$i$ where $i$ $\epsilon$ $[0,N-2]$, if it is possible. Note that, it will not be possible to inscribe if the dimension of the geometric figure you are perfectly inscribing is not an integer and you will discard the rest of the string. Find the maximum number of circles we can inscribe in a square according to the given string.
For a given binary string there can be only one geometric figure and this figure is concentric.
For example : the string 1100 can be represented as the figure below, the first two squares have the same side length and the next two circles have the same diameter.
Another example : the string 0001 can be represented as the one given below
Again here, we have 3 circles of the same diameter and one square inscribed in them.
-----Input:-----
The first line contains $N$, the number of strings
Then each of the next $N$ lines contains a binary string $S$.
-----Output:-----
The $N$ lines of output should have $N$ integers in separate lines, the maximum number of circles we can inscribe in a square according to the given string $S$ .
-----Constraints-----
- 1 $\leq$ $N$ $\leq$ 103
- 1 $\leq$ length of string $S$ $\leq$ 104
-----Sample Input:-----
3
1110
0010
1001000
-----Sample Output:-----
1
0
2
-----Explanation:-----
In the first case, we can inscribe the string 1110 as : three squares of side length 4 units (on top of each other) and then we can inscribe one circle of diameter 4 units.
The answer is 1 since, there is 1 circle inscribed in a square.
In the second case 0010, Let the first two circles be of some diameter 10, we can see that we cannot inscribe another square of any integer dimension inside them.
So, the answer is 0.
In the third case 1001000, we can take the first square of size 10, then inscribe two circles of diameter 5, then we cannot inscribe another square in this since, it will not be of any possible integer dimension and we discard the rest of the string.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for z in range(int(input())):
s = input()
n = len(s)
i = 0
while i<n and s[i]=='1':
i+=1
if i==0:
print(0)
else:
k = 0
while i<n and s[i]=='0':
i+=1
k+=1
print(k)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a string $s$. And you have a function $f(x)$ defined as:
f(x) = 1, if $x$ is a vowel
f(x) = 0, if $x$ is a constant
Your task is to apply the above function on all the characters in the string s and convert
the obtained binary string in decimal number $M$.
Since the number $M$ can be very large, compute it modulo $10^9+7$.
-----Input:-----
- The first line of the input contains a single integer $T$ i.e the no. of test cases.
- Each test line contains one String $s$ composed of lowercase English alphabet letters.
-----Output:-----
For each case, print a single line containing one integer $M$ modulo $10^9 + 7$.
-----Constraints-----
- $1 ≤ T ≤ 50$
- $|s|≤10^5$
-----Subtasks-----
- 20 points : $|s|≤30$
- 80 points : $ \text{original constraints}$
-----Sample Input:-----
1
hello
-----Sample Output:-----
9
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())
MOD=(10**9)+7
l=['a','e','i','o','u']
for i in range(t):
s=input()
k=[]
for j in s:
if j in l:
k.append(1)
else:
k.append(0)
r=bin(int(''.join(map(str, k)), 2) << 1)
print((int(r,2)//2)%MOD)
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Appy and Chef are participating in a contest. There are $N$ problems in this contest; each problem has a unique problem code between $1$ and $N$ inclusive. Appy and Chef decided to split the problems to solve between them ― Appy should solve the problems whose problem codes are divisible by $A$ but not divisible by $B$, and Chef should solve the problems whose problem codes are divisible by $B$ but not divisible by $A$ (they decided to not solve the problems whose codes are divisible by both $A$ and $B$).
To win, it is necessary to solve at least $K$ problems. You have to tell Appy whether they are going to win or lose.
-----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 four space-separated integers $N$, $A$, $B$ and $K$.
-----Output-----
For each test case, print a single line containing the string "Win" if they can solve at least $K$ problems or "Lose" otherwise (without quotes).
-----Constraints-----
- $1 \le T \le 15$
- $1 \le K \le N \le 10^{18}$
- $1 \le A, B \le 10^9$
-----Subtasks-----
Subtask #1 (15 points):
- $1 \le T \le 15$
- $1 \le K \le N \le 10^6$
- $1 \le A, B \le 10^3$
Subtask #2 (85 points): original constraints
-----Example Input-----
1
6 2 3 3
-----Example Output-----
Win
-----Explanation-----
Example case 1: Appy is solving the problems with codes $2$ and $4$, Chef is solving the problem with code $3$. Nobody is solving problem $6$, since $6$ is divisible by both $2$ and $3$. Therefore, they can solve $3$ problems and win.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
for t in range(int(input())):
n, a , b , k = map(int,input().split())
solvedbychef = 0
solvedbyappy = 0
for i in range(n+1):
if i % a == 0 and i % b == 0 :
continue
elif i%a == 0 :
solvedbyappy+=1
elif i%b == 0:
solvedbychef+=1
totalsolved = solvedbychef + solvedbyappy
if totalsolved>=k:
print("Win")
else :
print("Lose")
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
In these quarantine days, Chef and Chefina are getting bored. So, Chef came up with a game for her. He gets a pack of cards with numbers written on them. Chef then asks her to remove cards from the pack in the following manner: Chefina can choose any 3 cards at a time, having unique values, and remove the smallest and largest of them, and put back the middle one. For example, say Chefina chooses 3 cards that have numbers $x$, $y$, $z$ on them, such that $x <= y <= z$. Then she can throw away cards with number $x$ and $z$, but has to put the card with number $y$ on it back into the pack. Chefina can repeat this process any number of times. As soon as the pack contains cards with unique numbers, the game ends. If Chefina can determine the count of cards that will remain in the end, and tell it to Chef beforehand, she wins the game. Chefina asks for your help to win this game. Given the number written on the cards, help her find the count of cards in the pack when she wins.
$Note:$ You need to maximize the array length or the number of unique elements
-----Input:-----
- The first line of the input consists of a single integer $T$, denoting the number of test cases. Description of $T$ test cases follow.
- The first line of each test case consists of a single integer $N$, denoting the number of cards in the pack
- The next line consists of $N$ space separated numbers $A1$, $A2$ … $An$. For each valid $i (1 <= i <= N)$, the $i$-th card has the number $Ai$ written on it.
-----Output:-----
- For each test case, print the count of the cards that remain in the end.
-----Constraints-----
- $1 \leq T \leq 500$
- $1 \leq N \leq 10^6$
- $1 \leq Ai \leq N$
-----Subtasks-----
- 30 points : $1 \leq T \leq 20$; $ 1 \leq N \leq 5*10^5$
- 70 points : Original constraints
-----Sample Input:-----
2
5
1 2 2 3 5
9
1 2 2 3 3 5 8 8 9
-----Sample Output:-----
3
5
-----EXPLANATION:-----
Test case 1:
Chefina chooses the cards with number: 2, 3, 5, throws away 2 & 5, and puts back 3. So, the pack now contains cards with numbers: 1, 2, 3. Since the pack contains cards with unique numbers only, these are the 3 final cards.
Test case 2:
Chefina chooses the cards with number: 2, 3, 8, throws away 2 & 8, and puts back 3. Now the pack contains cards with numbers: 1, 2, 3, 3, 5, 8, 9. Next, she chooses cards with number: 3, 5, 8 throws away 3 & 8, and puts back 5. Now the pack contains cards with number: 1, 2, 3, 5, 9. Since the pack contains cards with unique numbers only, these are the 5 final cards.
Note: There might be multiple options to choose the 3 cards from the pack in any turn
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())):
n=int(input())
l=[int(j) for j in input().split()][:n]
d={}
for j in l:
d[j]=d.get(j,0)+1
a=len(d)
c=0
for j in list(d.keys()):
while(d[j]>=3):
d[j]=(d[j]//3)+(d[j]%3)
if(d[j]==2):
c=c+1
if(c&1):
s=0
for j in list(d.values()):
s=s+j
print(s-c-1)
else:
s=0
for j in list(d.values()):
s=s+j
print(s-c)
except:
pass
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A permutation of length $n$ is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ are permutations, and $[1, 1]$, $[0, 1]$, $[2, 2, 1, 4]$ are not.
There was a permutation $p[1 \dots n]$. It was merged with itself. In other words, let's take two instances of $p$ and insert elements of the second $p$ into the first maintaining relative order of elements. The result is a sequence of the length $2n$.
For example, if $p=[3, 1, 2]$ some possible results are: $[3, 1, 2, 3, 1, 2]$, $[3, 3, 1, 1, 2, 2]$, $[3, 1, 3, 1, 2, 2]$. The following sequences are not possible results of a merging: $[1, 3, 2, 1, 2, 3$], [$3, 1, 2, 3, 2, 1]$, $[3, 3, 1, 2, 2, 1]$.
For example, if $p=[2, 1]$ the possible results are: $[2, 2, 1, 1]$, $[2, 1, 2, 1]$. The following sequences are not possible results of a merging: $[1, 1, 2, 2$], [$2, 1, 1, 2]$, $[1, 2, 2, 1]$.
Your task is to restore the permutation $p$ by the given resulting sequence $a$. It is guaranteed that the answer exists and is unique.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 400$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the length of permutation. The second line of the test case contains $2n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$. It is guaranteed that the array $a$ represents the result of merging of some permutation $p$ with the same permutation $p$.
-----Output-----
For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$), representing the initial permutation. It is guaranteed that the answer exists and is unique.
-----Example-----
Input
5
2
1 1 2 2
4
1 3 1 4 3 4 2 2
5
1 2 1 2 3 4 3 5 4 5
3
1 2 3 1 2 3
4
2 3 2 4 1 3 4 1
Output
1 2
1 3 4 2
1 2 3 4 5
1 2 3
2 3 4 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())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
print(*set(a))
``` |
|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Write a program to take two numbers as input and print their difference if the first number is greater than the second number otherwise$otherwise$ print their sum.
-----Input:-----
- First line will contain the first number (N1$N1$)
- Second line will contain the second number (N2$N2$)
-----Output:-----
Output a single line containing the difference of 2 numbers (N1−N2)$(N1 - N2)$ if the first number is greater than the second number otherwise output their sum (N1+N2)$(N1 + N2)$.
-----Constraints-----
- −1000≤N1≤1000$-1000 \leq N1 \leq 1000$
- −1000≤N2≤1000$-1000 \leq N2 \leq 1000$
-----Sample Input:-----
82
28
-----Sample Output:-----
54
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
m = int(input())
n = int(input())
print(m-n) if m>n else print(m+n)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.