source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Sereja have array A' that contain N integers. Now Sereja want to permute elements of the array, he want to use some permutation p, such that A[i] = A'[p[i]], where A - new array.
Lets function f(A,i) = S - A[i] - A[i +1] - ... - A[j], where j ... | ```python
# Md. Khairullah Gaurab
# SUST, CSE, 20th Batch
# gaurab.cse.sust@gmail.com
test = int(input());
for i in range(test):
N, S, K = list(map(int,input().split()));
lis = list(map(int,input().split()));
ans = [i+1 for i in range(N)] ;
ans.sort(reverse=True);
for j in range(N):
prin... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ahmed Gafer failed to pass the test, but he got the job because of his friendship with Said and Shahhoud. After working in the kitchen for a while, he blew it. The customers didn't like the food anymore and one day he even burned the kitchen. No... | ```python
# cook your dish here
for _ in range(int(input())):
s=input()
count=0
i=0
while i<len(s)-1:
ch=s[i]
j=i+1
while j<len(s) and s[j]==ch:
j+=1
l=j-i
if i!=0 and j!=len(s) and s[i-1]==s[j] :
count+=1
count+=l*(l-1)//2
#print(s[i:j],count)
i=j
print(count)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Master Shifu is training Po to become The Dragon Warrior and as a final assignment he must obtain maximum deliciousness from dumplings. There are $N$ plates of dumplings in front of him with deliciousness $A_1, A_2, \ldots, A_N$, Po can choose ... | ```python
# cook your dish here
N=int(input())
for _ in range(N):
n=int(input())
arr=list(map(int,input().split()))[:n]
count=0
last=0
for i in range(n):
if(arr[i]!=0):
break
last=i
count+=1
for i in arr[-1:last:-1]:
if(i!=0):
break
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough ... | ```python
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
def solve():
s,c = input().split()
# i,jでjが複数あるとき
n = len(s)
for i in range(n-1):
prev = s[i]
pos = i
for j in range(i+1, n):
if s[j]<prev:
prev = s[j]
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The students of Codechef Middle School are visiting an amusement park. The children want to go on a ride, however, there is a minimum height requirement of $X$ cm. Determine if the children are eligible to go on the ride.
Print "Yes" if they ar... | ```python
# cook your dish here
for _ in range(int(input())):
h,x=map(int,input().split())
if(h>=x):
print("Yes")
else:
print("No")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has two integer sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_M$. You should choose $N+M-1$ pairs, each in the form $(A_x, B_y)$, such that the sums $A_x + B_y$ are all pairwise distinct.
It is guaranteed that under the given c... | ```python
# cook your dish here
n,m = map(int, input().split())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
max1 = arr1.index(max(arr1))
min2 = arr2.index(min(arr2))
arr = []
for i in range(m):
arr.append([max1, i])
for i in range(n):
if i!=max1:
arr.append([i , min2])... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to $1$ meter movement in the south, north, west or east direction respectively).
It is known that if he moves along a pr... | ```python
DIR = {"N": (0, 1), "S": (0, -1), "W": (-1, 0), "E": (1, 0)}
for t in range(int(input())):
path = input()
tracks = set()
x, y = 0, 0
time = 0
for char in path:
x1 = x + DIR[char][0]
y1 = y + DIR[char][1]
if (x, y, x1, y1) in tracks or (x1, y1, x, y) in tracks:
time +... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has N subordinates. In order to complete a very important order he will choose exactly K of them. He can't choose less than K since it will be not enough to complete the order in time. On the other hand if he chooses more than K subordinate... | ```python
def nCr(n,k):
if(k>n):return 0
k=min(k,n-k)
num,den=1,1
for i in range(k):
num*=(n-i)
den*=(i+1)
return num/den
def Main():
for cases in range(int(input())):
a,b=[int(x) for x in input().split()]
print(nCr(a,b))
Main()
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given string $s$ of length $n$ consisting of 0-s and 1-s. You build an infinite string $t$ as a concatenation of an infinite number of strings $s$, or $t = ssss \dots$ For example, if $s =$ 10010, then $t =$ 100101001010010...
Calculate... | ```python
t=int(input())
for i in ' '*t:
n,x=map(int,input().split())
s=input()
L=[0]
for i in s:
if i=='0':L.append(L[-1]+1)
else:L.append(L[-1]-1)
L.pop(0)
k=L[-1]
c=0
if x==0:c+=1
if k>0:
for i in L:
if i%k==x%k and i<=x:c+=1
print(c)
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$). Find any such rectangular matrix of size $n \times m$ that satisfies all of the following conditions:
each row of the matrix contains ex... | ```python
for _ in range(int(input())):
n, m, a, b = list(map(int, input().split()))
if a * n != b * m:
print('NO')
else:
ar = []
for i in range(n):
ar.append([0] * m)
x, y = 0, a
for i in range(n):
if x < y:
for j in range(x, y... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K(odd) to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of tes... | ```python
from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 99824435... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction.
A fraction in notation with base $b$ is finite if it contains ... | ```python
import sys
def binpow(a, n, p):
res = 1
while n > 0:
if n % 2 == 1:
res = (res * a) % p
a = (a * a) % p
n >>= 1
return res
def main():
result = []
t = int(sys.stdin.readline())
for line in sys.stdin.readlines():
p, q, b = list(map(int,... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number... | ```python
n = int(input())
pos,tree,ans,sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n-1):
tree[pos[i]-1].append(i+1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n)... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef likes prime numbers. However, there is one thing he loves even more. Of course, it's semi-primes! A semi-prime number is an integer which can be expressed as a product of two distinct primes. For example, $15 = 3 \cdot 5$ is a semi-prime nu... | ```python
# cook your dish here
import sys
n = 201
v = [0 for i in range(n + 1)]
def gen():
for i in range(1, n + 1):
v[i] = i
countDivision = [0 for i in range(n + 1)]
for i in range(n + 1):
countDivision[i] = 2
for i in range(2, n + 1, 1):
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef is making Window frames for his new office, for this he has n wooden Logs whose lengths are l1, l2, … ln respectively. Chef Doesn’t want to break any logs or Stick 2 or more logs together.
To make a h × w Window Frame, he needs two Logs w... | ```python
# cook your dish here
t=int(input())
j=0
while j<t:
n=int(input())
lst=list(map(int,input().split()))
s=set()
d=list()
for i in lst:
if i in s:
s.remove(i)
d.append(i)
else:
s.add(i)
x=len(d)
if x%2==0:
print(x//2)
els... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Mandarin chinese
, Russian and Vietnamese as well.
You are given a grid with $n$ rows and $m$ columns. Each cell of this grid can either be empty or it contains one particle. It can never contain more than one particle. Let's denote the cell in ... | ```python
def main():
for _ in range(int(input())):
rows,column = map(int,input().split())
arr = []
for i in range(rows):
arr.append(list(input()))
string = input()
last = string[-1]
operation = Find(string,last)
for i in string[0]+operation:
if i == "L":
arr = Left(arr)
if i == "R":
arr... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Consider all binary strings of length $m$ ($1 \le m \le 60$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $2^m$ such strings in t... | ```python
def read_int():
return int(input())
def read_ints():
return list(map(int, input().split(' ')))
t = read_int()
for case_num in range(t):
n, m = read_ints()
a = []
for i in range(n):
a.append(int(input(), 2))
a.sort()
k = 2 ** m - n
ans = (k - 1) // 2
for ai in a:... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A balanced parenthesis string is defined as follows:
- The empty string is balanced
- If P is balanced, (P) is also
- If P and Q are balanced, PQ is also balanced
You are given two even integers n$n$ and k$k$. Find any balanced paranthesis stri... | ```python
import sys
def input():
return sys.stdin.readline().strip()
for i in range(int(input())):
n, k = map(int, input().split())
arr = []
if k == 2 or k == 4 or n % 2 != 0 or n == k:
arr.append('-1')
elif k % 2 != 0:
for i in range(int(n / 2)):
arr.append('(')
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Anmol gained a lot of weight last semester. So this semester, he decided to run everyday. There is a very long straight road starting at his hostel. There are N poles on the road - P1, P2, P3,..., PN on the road. All the poles lie on the same si... | ```python
#code snippet reference:http://www.geeksforgeeks.org/searching-for-patterns-set -2-kmp-algorithm/
def KMPMatch(pattern, string):
M = len(pattern)
N = len(string)
nonlocal ans
lps = [0]*M
j = 0
LPSCompute(pattern, M, lps)
i = 0
while i < N:
if pattern[j] == string[i]:
i+=1
j+=1
if j==... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Naman owns a very famous Ice Cream parlour in Pune. He has a wide range of flavours with different pricing.
Every flavour costs ₹ X per gram and quantity of each flavour in the parlour is indefinite. Now, Naman has
received an order for a pa... | ```python
test = int(input())
for i in range(test):
flavor = int(input())
rate = input()
gaf = input()
gaf = gaf.split()
gaf = [int(x) for x in gaf]
rate = rate.split()
rate = [int(x) for x in rate]
rate.sort()
c = gaf[0] - gaf[1]
sum = rate[0]*c
t = True
if gaf[0] < gaf[1]:
t = False
j = 0
while(j<gaf[... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Chef has a positive intege... | ```python
# cook your dish here
for _ in range(0,int(input())):
n=input().strip()
x=n.count('4')
y=n.count('7')
print(len(n)-x-y)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
It is an interesting exercise to write a program to print out all permutations of $1, 2, …, n$. However, since there are $6227020800$ permutations of $1, 2, …, 13$, it is unlikely that we would ever run this program on an input of size more than... | ```python
import sys
# import math as mt
# from collections import Counter
# from itertools import permutations
# from functools import reduce
# from heapq import nsmallest, nlargest, heapify, heappop, heappush, heapreplace
def get_inpt(): return sys.stdin.readline().strip()
def get_int(): return int(sys.stdin.readlin... | |
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 cas... | ```python
t=int(input())
for t in range(t):
n=int(input())
for i in range(0,n):
for j in range(0,n):
if i%2==0:
if j%2==0:
print(0,end="")
else:
print(1,end="")
else:
if j%2==0:
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
DZY loves planting, and he enjoys solving tree problems.
DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge ... | ```python
n = int(input())
edges = [[int(x) for x in input().split()] for i in range(n-1)]
edges = sorted(edges)
use_count = [0]+[int(input()) for i in range(n)]
lo,hi = 0,10000
def getpar(par,u):
if par[par[u]] == par[u]:
return par[u]
par[u] = getpar(par,par[u])
return par[u]
def unite(par,sz,use,... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A spy needs your help to encrypt a 5 letter message.
To encrypt the message the following steps are need to be done:
1)Each letter of the message will be converted to it's equivalent number (i.e A=0, B=1,..Z=25)
2)98, 57, 31, 45, 46 are the 5 ... | ```python
# cook your dish here
import string
from collections import OrderedDict
from itertools import zip_longest
dic = OrderedDict(zip(string.ascii_uppercase, range(0, 26)))
keys = [98, 57, 31, 45, 46]
t = int(input()) # number of test cases
s1 = []
for i in range(t):
s = input()
for i in s:
if i in dic.key... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You have a laser with P amount of energy in it. You are playing a game where you have to use the laser to destroy some crystals, each with some health of their own. Initially, you have 0 points.
Each crystal has an associated health. The health ... | ```python
def game(n,l,p):
if(len(l)==0):
return 0
l.sort()
if(len(l)>=1 and p<l[0]):
return 0
l.sort()
c=0
ma=set()
ma.add(0)
while(len(l)):
if(p>=l[0]):
p-=l[0]
c+=1
ma.add(c)
l=l[1:]
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Consider the fraction, $a/b$, where $a$ and $b$ are positive integers. If $a < b$ and $GCD(a,b) = 1$, it is called a reduced proper fraction.
If we list the set of a reduced proper fraction for $d \leq 8$, (where $d$ is the denominator) in ascen... | ```python
from sys import stdin
from fractions import Fraction
input = stdin.readline
for _ in range(int(input())):
a, b, n = list(map(int, input().split()))
ab = Fraction(a, b)
p = set()
for i in range(1, n+1):
for j in range(n, 0, -1):
x = Fraction(i, j)
if x > ab:... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Give me Chocolate
Anushka wants to buy chocolates.there are many chocolates in front of her, tagged with their prices.
Anushka has only a certain amount to spend, and she wants to maximize the number of chocolates she buys with this money.
Gi... | ```python
n,k = map(int,input().split())
prices = list(map(int,input().split()))
prices.sort()
sum,cnt = 0, 0
for price in prices:
sum += price
if sum <= k: cnt += 1
else: break
print(cnt)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interestin... | ```python
m = 10** 6 + 3
n, k = list(map(int, input().split()))
p = 1
for i in range(n):
p *= 2
if p > k:
break
if p < k:
print('1 1')
return
gcd = tmp = k - 1
while tmp:
gcd -= tmp % 2
tmp //= 2
b = pow(2, (k - 1) * n - gcd, m)
a = 1
mem = [-1]*100
for i in range(1, k):
cnt = 0
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows ... | ```python
__author__ = 'Pavel Mavrin'
n = int(input())
a = [int(x) for x in input().split()]
s = 0
res = 0
for i in a:
if i == 0:
res += s
else:
s += 1
print(res)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has created a special dividing machine that supports the below given operations on an array of positive integers.
There are two operations that Chef implemented on the machine.
Type 0 Operation
Update(L,R):
for i = L to R:
a[i] = a[i] /... | ```python
import math
n=1001
a=[True]*n
l=[]
for i in range(2,33):
if(a[i]):
for j in range(i*i,n,i):
a[j]=False
for pr in range(2,1001):
if(a[pr]):
l.append(pr)
t=int(input())
for j in range(t):
n,m=list(map(int,input().strip().split()))
arr=[int(num) for num in input().strip().split()]
Matrix =[]
index=[... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Many things in this first paragraph are references to some pretty famous YouTube stars, so be careful about rephrasing. Thanks!
Michael, Kevin and Jake are sharing a cake, in celebration of their Webby award. They named it VCake. Unlike other c... | ```python
#!/usr/bin/python
import sys
def __starting_point():
t = int(input())
for iteration in range(t):
r,c,m_inp,k_inp,j_inp = input().strip().split(" ")
r=int(r)
c=int(c)
m_inp=int(m_inp)
k_inp=int(k_inp)
j_inp=int(j_inp)
ans = ""
if (r*c) != (m_inp+k_inp+j_inp):
print("No")
continue
el... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The name of our college is "Government College of Engineering and Textile Technology Berhampore". There is another college named "Government College of Engineering and Textile Technology Serampore". As the names are quite similar, those who are ... | ```python
# cook your dish here
try:
t=int(input())
for i in range(t):
n=input()
n=n.lower()
a="berhampore"
b="serampore"
if a in n:
if b in n:
print("Both")
else:
print("GCETTB")
elif b in n:
i... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a string S of length N consisting of lowercase English letters.
Process Q queries of the following two types:
- Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.)
- Type 2: answe... | ```python
n = int(input())
s = list(input())
s = [ord(i)-97 for i in s]
dic = {}
for i in range(26):
dic[i] = []
for i in range(n):
dic[s[i]].append(i)
for i in range(26):
dic[i].append(float('inf'))
from bisect import bisect_left
q = int(input())
for i in range(q):
x, y, z = input().split()
if ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white a... | ```python
def init_factorials(N, mod):
f = 1
fac = [1] * N
for i in range(1, N):
f *= i
f %= mod
fac[i] = f
return fac
def init_inv(N, mod, fac):
b = bin(mod-2)[2:][-1::-1]
ret = 1
tmp = fac[N]
if b[0] == '1':
ret = fac[N]
for bi in b[1:]:
tmp... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given $n$ points on the plane. The polygon formed from all the $n$ points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $1... | ```python
import sys
input = sys.stdin.readline
n = int(input())
x = []
y = []
for i in range(n):
xi, yi = map(int, input().split())
x.append(xi)
y.append(yi)
min_x = min(x)
max_x = max(x)
min_y = min(y)
max_y = max(y)
answer = 0
for i in range(n):
dx = max(max_x - x[i], x[i] - min_x)
dy = max(max_... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array $a_1$, $a_2$, ..., $a_n$ of integers, such that $1 \le a_1 < a_2 < \ldots < a_n \le 10^3$, and then went to the bathroom.
... | ```python
n = int(input())
a = [0] + list(map(int, input().split())) + [1001]
mx = 1
p = 1
for i in range(1, n + 2):
if a[i] == a[i - 1] + 1:
p += 1
mx = max(p, mx)
else:
p = 1
print(max(0, mx - 2))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There are two friends Alice and Bob. They have a packet of $n$ candies. They want to split the candies between them, and to do so, they kept them all in a single line. The $i^{\text{th}}$ candy in the line has a sweetness value of $a_i$. They de... | ```python
from sys import setrecursionlimit
setrecursionlimit(10 ** 9)
def solve(i, j, c=0):
if i > j:
return 0
if (i, j) in dp:
return dp[i, j]
x0 = solve(i+1, j, c^1)
x1 = solve(i, j-1, c^1)
if c == 0:
y = 1 << (j - i)
x0 += a[i] * y
x1 += a[j] * y
dp[i, j] = x0 + x1
return dp[i, j]
for _ in ra... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Arpa is researching the Mexican wave.
There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.
At time 1, the first spectator stands. At time 2, the second spectator stands. ... At time k, the k-... | ```python
def read_ints():
return [int(i) for i in input().split()]
n, k, t = read_ints()
if t <= k:
print(t)
elif t > n:
print(k + n - t)
else:
print(k)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
For the multiset of positive integers $s=\{s_1,s_2,\dots,s_k\}$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $s$ as follow: $\gcd(s)$ is the maximum positive integer $x$, such that all integers in $s$ are divisibl... | ```python
def Sieve(n):
ret = []
divlis = [-1] * (n+1)
flag = [True] * (n+1)
flag[0] = False
flag[1] = False
ind = 2
while ind <= n:
if flag[ind]:
ret.append(ind)
ind2 = ind ** 2
while ind2 <= n:
flag[ind2] = False
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might... | ```python
n = int(input())
ans = 0
stk = []
for v in map(int, input().split()):
last = 0
while len(stk) and stk[-1][0] < v and stk[-1][1]:
last = max(last, stk[-1][1])
del stk[-1]
if not len(stk) or stk[-1][0] < v:
stk.append((v, 0))
else:
stk.append((v, last + 1)); ans ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Vivek was quite bored with the lockdown, so he came up with an interesting task. He successfully completed this task and now, he would like you to solve it.
You are given two strings $A$ and $B$, each with length $N$. Let's index the characters ... | ```python
for _ in range(int(input())):
n=int(input())
a=input()
b=input()
l=[]
flag=0
for i in range(n):
if b[i]!=a[i]:
if b[i] in a and b[i]<a[i]:
l.append(b[i])
else:
flag=1
break
if flag==1:
print(-1)
else:
if l==[]:
print(0)
else:
l = sorted(list(set(l)), reverse = True)
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 2015_10 = 11111011111_2. Note that he... | ```python
def zero(strx):
k = []
str2 = list(strx)
for i in range(1, len(str2)):
str3 = str2[:]
str3[i] = '0'
k.append(''.join(str3))
return k
a = []
for i in range(1, 64):
a += zero('1'*i)
ct = 0
x, y = list(map(int, input().split(' ')))
for i in a:
if x <= int(i, 2) <=... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they... | ```python
n = int(input())
ans = 'YES\n'
for i in range(n):
x1, y1, x2, y2 = map(int, input().split())
res = (x1 & 1) * 2 + (y1 & 1) + 1
ans += str(res) + '\n'
print(ans)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a_1, a_2, ..., a_{k}, that their sum is equal to n and greatest common divisor is maximal.
Greatest common divisor of sequence is... | ```python
n, k = map(int, input().split())
div = []
i = 1
n1 = n
while i * i <= n:
if n % i == 0:
div.append(i)
div.append(n // i)
i += 1
div.sort()
mx = -1
for i in range(len(div)):
a = div[i] * k * (k + 1) // 2
if a <= n:
mx = div[i]
if mx == -1:
print(-1)
else:
for i i... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in e... | ```python
from math import factorial
def lol(n):
if n == 1:
yield [0]
yield [1]
else:
for p in lol(n - 1):
p.append(0)
yield p
p[-1] = 1
yield p
p.pop()
def sp(g1, g2, g3, f):
if g1 == 0:
if g2 == g3:
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has a natural number N. Cheffina challenges chef to check whether the given number is divisible by the sum of its digits or not. If the given number is divisible then print "Yes" else "No".
-----Input:-----
- First-line will contain $T$, t... | ```python
import sys,io,os,math
from math import ceil,log,gcd,inf
from itertools import permutations
mod=1000000007
mod1=998244353
def printlist(n):
sys.stdout.write(" ".join(map(str,n)) + "\n")
printf=lambda n:sys.stdout.write(str(n)+"\n")
def printns(n):
sys.stdout.write(str(n))
def intinp():
return in... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group fo... | ```python
import sys
readline = sys.stdin.readline
N, D, M = map(int, readline().split())
A = list(map(int, readline().split()))
Am = [a for a in A if a > M]
Ao = [a for a in A if a <= M]
Am.sort(reverse = True)
Ao.sort(reverse = True)
Cam = Am[:]
Cao = Ao[:]
for i in range(1, len(Cam)):
Cam[i] += Cam[i-1]
for i ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
After completing some serious investigation, Watson and Holmes are now chilling themselves in the Shimla hills. Very soon Holmes became bored. Holmes lived entirely for his profession. We know he is a workaholic. So Holmes wants to stop his vaca... | ```python
t=int(input())
for i in range(0,t):
n=int(input())
lis=list(map(int,input().split()))
lis2=[]
for j in range(0,10):
lis2.append(0)
for j in range(0,len(lis)):
lis2[lis[j]]+=1;
s=sum(lis)
while s%3!=0:
if s%3==2:
if lis2[2]>=1:
lis2[2]-=1
s=s-2
elif lis2[5]>=1:
lis2[5]-=1
s=s... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N).
Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence.
Then, perform t... | ```python
import sys
input = sys.stdin.readline
import numpy as np
from heapq import heappush, heappop
N = int(input())
A = np.array(input().split(), dtype=np.int32)
a_to_i = {a:i for i,a in enumerate(A)}
# sparse table を使ってRMQ
# parityの同じところだけを見るようにしておく
U = len(A).bit_length()
sp = [None,A]
for i in range(2,U):
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Eugene loves sequences, especially arithmetic progressions. One day he was asked to solve a difficult problem.
If a sequence of numbers A1, A2, ... , AN form an arithmetic progression A, he was asked to calculate sum of F(Ai), for L ≤ i ≤ R.
F(... | ```python
import fractions
import sys
f = sys.stdin
if len(sys.argv) > 1:
f = open(sys.argv[1], "rt")
sum_cache = {}
def sum_func(x):
if x < 10:
return x
r = sum_cache.get(x)
if r is not None:
return r
xx = 0
while x > 0:
xx += x % 10
x /= 10
r = sum... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The life goes up and down, just like nice sequences. Sequence t_1, t_2, ..., t_{n} is called nice if the following two conditions are satisfied: t_{i} < t_{i} + 1 for each odd i < n; t_{i} > t_{i} + 1 for each even i < n.
For example, seque... | ```python
def main():
n, l = int(input()), list(map(int, input().split()))
if not (n & 1):
l.append(0)
l.append(150001)
i, b, c, fails0, fails1 = 0, 0, 150001, [], []
try:
while True:
a, b, c = b, c, l[i]
if a >= b or b <= c:
if len(fails0) + l... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chefland has all the cities on a straight line. There are $N$ cities in Chefland numbered $1$ to $N$. City $i$ is located at coordinate $x_i$ on the x-axis. Guru wants to travel from city $A$ to city $B$. He starts at time t=0. He has following ... | ```python
t=int(input())
for _ in range(t):
n,a,b,c,d,p,q,y=list(map(int,input().split()))
l=list(map(int,input().split()))
ans = abs((l[b-1]-l[a-1]))*p
x=abs(l[c-1]-l[a-1])*p
if x<=y:
x=y+abs(l[d-1]-l[c-1])*q+abs(l[b-1]-l[d-1])*p
ans=min(ans,x)
print(ans)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
We all know how great ABD aka AB-DE-VILLIERS is. However his team mates were jealous of him and posed a problem for him to solve.The problem description is as follows :
Given an array of integers,find the length of the largest subarray(contiguo... | ```python
n=eval(input())
a=list(map(int,input().split()))
c=m=0
maxi=max(a)
for i in range(n):
if a[i]==maxi:
c+=1
m=max(c,m)
else:
c=0
print(m)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a prime number $p$, $n$ integers $a_1, a_2, \ldots, a_n$, and an integer $k$.
Find the number of pairs of indexes $(i, j)$ ($1 \le i < j \le n$) for which $(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$.
-----Input-----
The firs... | ```python
def check(num1, num2, p, k):
v = num1 + num2
v *= num1 * num1 + num2 * num2
v %= p
v += p
v %= p
return v == k % p
def __starting_point():
n, p, k = (int(x) for x in input().split())
idx___number = [int(x) for x in input().split()]
idx___precount = [((pow(x, 4, p) - k * ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ziota found a video game called "Monster Invaders".
Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.
For the sake of simplicity, we only consider two different types of monsters and t... | ```python
n,r1,r2,r3,D = map(int,input().split())
state = [0,0] # after odd number of 2 (1st), or not (2nd)
a = list(map(int,input().split()))
# First element
# Choosing P~P + A
state[0] = r1 * a[0] + r3
# Choosing L + P later or all P
state[1] = min(r2 + r1 + D, r1 * (a[0] + 2) + D)
# Second to Second Last ele... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a grid with $R$ rows (numbered $1$ through $R$) and $C$ columns (numbered $1$ through $C$). A cell in row $r$ and column $c$ is denoted by $(r, c)$. Two cells in the grid are adjacent if they have a common side. For each valid $i$ ... | ```python
for _ in range(int(input())):
r,c = map(int,input().split())
l = []
for k in range(r):
a = list(map(int,input().split()))
l.append(a)
ans = "Stable"
for i in range(r):
for j in range(c):
p = l[i][j]
count=0
if i-1>=0 and j>=0:
count+=1
if i>=0 and j-1>=0:
count+=1
if i+1<=... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that... | ```python
h, w = map(int, input().split())
x0, y0, x1, y1, c = 1000, 1000, -1, -1, 0
for i in range(h):
row = str(input())
for j in range(w):
if row[j] == 'B':
x0, y0, x1, y1, c = min(x0, i), min(y0, j), max(x1, i), max(y1, j), c + 1
ln = max(x1 - x0 + 1, y1 - y0 + 1)
if ln > min(h, w):
print(-1)
elif x... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Masha and Grisha like studying sets of positive integers.
One day Grisha has written a set A containing n different integers a_{i} on a blackboard. Now he asks Masha to create a set B containing n different integers b_{j} such that all n^2 inte... | ```python
d = [-1] * 1000001
for t in range(int(input())):
n, a = int(input()), list(map(int, input().split()))
a.sort()
for i in range(n):
for j in range(i + 1, n): d[a[j] - a[i]] = t
i = 1
while any(d[i * j] == t for j in range(1, n)): i += 1
print("YES\n" + ' '.join(str(j * i + 1) fo... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Jones Trucking Company tracks the location of each of its trucks on a grid similar to an (x, y) plane. The home office is at the location (0, 0). Read the coordinates of truck A and the coordinates of truck B and determine which is closer to... | ```python
# cook your dish here
try:
t = int(input())
for i in range(t):
ar=list(map(int,input().split()))
if (ar[0]**2 + ar[1]**2 > ar[2]**2 + ar[3]**2):
print("B IS CLOSER")
else:
print("A IS CLOSER")
except:
pass
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The MEX of a set of integers is defined as the smallest non-negative integer that does not belong to this set. For example, $\mathrm{MEX}(\{0,2,3\}) = 1$ and $\mathrm{MEX}(\{1,3\}) = 0$.
Chef has a tree with $N$ nodes (numbered $1$ through $N$).... | ```python
# cook your dish here
# cook your dish here
from math import log2;
import sys;
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
inf = float("inf")
def find_height(node):
nodes[node]=1
for i in graph[node]:
nodes[node]+=find_height(i)
return nodes[node]
def find_sum(node... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Head Chef is receiving a lot of orders for cooking the best of the problems lately. For this, he organized an hiring event to hire some talented Chefs. He gave the following problem to test the skills of the participating Chefs. Can you solv... | ```python
def base5(n):
if n == 0: return
for x in base5(n // 5): yield x
yield n % 5
def seq(n):
return int(''.join(str(2 * x) for x in base5(n)) or '0')
for i in range(eval(input())):
k=eval(input())
while(i<k):
i=i+1
print(seq(i-1))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has a strip of length $N$ units and he wants to tile it using $4$ kind of tiles
-A Red tile of $2$ unit length
-A Red tile of $1$ unit length
-A Blue tile of $2$ unit length
-A Blue tile of $1$ unit length
Chef is having an infinite ... | ```python
# Fibonacci Series using
# Optimized Method
# function that returns nth
# Fibonacci number
MOD = 1000000007
def fib(n):
F = [[2, 2],
[1, 0]]
power(F, n - 1)
ans = [6, 2]
return (F[0][0] * 6 + F[0][1] * 2) % MOD
# return F[0][0]
def multiply(F, M):
x = (F[... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Probably everyone has experienced an awkward situation due to shared armrests between seats in cinemas. A highly accomplished cinema manager named "Chef" decided to solve this problem.
When a customer wants to buy a ticket, the clerk at the tic... | ```python
for i in range(eval(input())):
n,m,z,l,r,b = list(map(int, input().split()))
rows=n
columns=m
hand_rest=n*(m+1)
if(m%2==0):
hand_rest -=max(0,n-l-r)
if(l+r+(2*b)<=hand_rest):
# print "kanu"
print(min(n*m,l+r+z+b))
else:
temp=l+r+(hand_rest-l-r)/2
# print "parth"
print(min(n*m,temp+z))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
All strings in Chefland are beautiful because they are binary strings (a binary string contains only characters '0' and '1'). The beauty of a binary string $S$ is defined as the number of pairs $(i, j)$ ($1 \le i \le j \le |S|$) such that the su... | ```python
t = int(input())
for _ in range(t):
s = input()
pref = [0]*len(s)
if s[0]=="1":
pref[0]+=1
for i in range(1,len(s)):
if s[i]=="1":
pref[i]+=1
pref[i]=pref[i]+pref[i-1]
k=1
cnt=0
while (k+k*k)<=len(s):
r = k+k*k
i=r-1
while i<len(s):
if (i-r)>=0:
if pref[i]-pref[i-r]==k:
cnt+=... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Problem Statement:Captain America and Iron Man are at WAR and the rage inside Iron Man is rising.
But Iron Man faces a problem to identify the location of Captain America.
There are N buildings situtaed adjacently to each other and Captain Ame... | ```python
t = int(input())
while t> 0:
t =t -1
n,k = list(map(int,input().split()))
a = [0]*n
done = True
def swap(z):
for j in range(0,n):
if a[j] == 0:
a[j] = z
done = True
break
else:
if a[j] > z:
swap(j)
a[j] = z
else:
done = False
break
for i in range(0,n):
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.
Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge u... | ```python
def main():
n, m = list(map(int, input().split()))
l = [[] for _ in range(n + 1)]
for _ in range(m):
u, v = list(map(int, input().split()))
l[u].append(v)
l[v].append(u)
res = [0] * (n + 1)
for u, x in enumerate(res):
if not x:
x, nxt = -1, [u]
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
— Hey folks, how do you like this problem?
— That'll do it.
BThero is a powerful magician. He has got $n$ piles of candies, the $i$-th pile initially contains $a_i$ candies. BThero can cast a copy-paste spell as follows: He chooses two pile... | ```python
import math
t = int(input())
for test in range(t):
n,k = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
ans = 0
for i in range(1,n):
if(A[i]>k):
ans = 0
break
rem = k-A[i]
ans+=rem//A[0]
print(ans)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the fi... | ```python
n = int(input())
t = [1] + [0] * n
b, a = d = [], []
h, s = [], []
for i in range(n):
f, k = input().split()
d[int(k)].append(f)
m = len(a)
for i in a:
if i.isdigit() and i[0] != '0':
j = int(i)
if 0 < j <= m:
t[j] = 1
elif m < j <= n:
t[j] = -1
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The only difference between easy and hard versions is constraints.
You are given a sequence $a$ consisting of $n$ positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these... | ```python
from operator import itemgetter
import sys
input = sys.stdin.readline
MAX_A = 200
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
ruiseki = [[0] * MAX_A for i in range(n + 1)]
for i in range(n):
for j in range(MAX_A):
ruiseki[... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Given an Array of length $N$ containing elements $Ai$ ( i = 1 to n ) . You have to handle $Q$ queries on this array . Each Query is of two types k=(1 or 2).
Type 1:- $k$ $l$ $r$ in which you have to tell whether the product of numbers in rang... | ```python
def update(index, value, bi_tree):
while index < len(bi_tree):
bi_tree[index] += value
index += index & -index
def get_sum(index, bi_tree):
ans = 0
while index > 0:
ans += bi_tree[index]
index -= index & -index
return ans
def get_range_sum(left, right, bi_tree):
ans = get_sum(right, bi_tree)... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a binary string S of N bits. The bits in the string are indexed starting from 1. S[i] denotes the ith bit of S.
Let's say that a sequence i1, i2, …, iK(1 ≤ K; 1 ≤ i1 < i2 < … < iK ≤ N) produces a palindrome when applied to S, if t... | ```python
def powerset(s):
n = len(s)
masks = [1 << j for j in range(n)]
for i in range(2**n):
yield [j + 1 for j in range(n) if (masks[j] & i)]
def is_power2(num):
return num != 0 and ((num & (num - 1)) == 0)
def special(l):
n = len(l)
for i in range(n):
lis = [i + 1]
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersect... | ```python
lanes = []
for i in range(4):
lanes.append(list(map(int, input().split())))
lanes.extend(lanes)
for i in range(4):
ln = lanes[i]
if (ln[3] and (ln[0] or ln[1] or ln[2])) or \
(ln[0] and lanes[i + 3][3]) or \
(ln[1] and lanes[i + 2][3]) or \
(ln[2] and lanes[i... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
-----Problem Statement-----
One of the things JEC is known for is its GR (Group Recreation) where juniors and seniors do friendly interaction ;P
As for the new session of 2020 seniors decided to have their first GR and give them some treat. Juni... | ```python
t=int(input())
while t:
t=t-1
n,x=input().split()
n=int(n)
x=int(x)
d,l=input().split()
if d=='L':
p=x
elif d=='R':
p=(n-x)+1
if p%2==1:
if l=='H':
lang='H'
else:
lang='E'
elif p%2==0:
if l=='H':
lang='E'
else:
lang='H'
print(p,lang)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Sunita has lots of tasks pending and she has no time to complete. She needs your help and wants you complete the task.
You are given a list of integers and two values $N$ and $K$ $-$ the size of array of integers and the numbers of partitions t... | ```python
from sys import stdin,stdout
from math import gcd
for _ in range(int(stdin.readline())):
# n=int(stdin.readline()) k-pieces
n,k=list(map(int,stdin.readline().split()))
a=list(map(int,stdin.readline().split()))
gr=[[0 for _ in range(n)]for _ in range(n)];ans=0;k-=1
for sz in range(n)... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Kabir likes Tara's smile and wants to look at her smile. They are sitting in the class and you are friends with Kabir. You have to place a mirror (point size) in the front wall of the class so that Kabir can have a glimpse of Tara's smile.
Cons... | ```python
# cook your dish here
try:
t = int(input())
for _ in range(t):
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
q[1] *= -1
m = (q[1]-p[1])/(q[0]-p[0])
c = p[1] - m*p[0]
print("{:.2f}".format(-c/m))
except:
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ashish and Vivek play a game on a matrix consisting of $n$ rows and $m$ columns, where they take turns claiming cells. Unclaimed cells are represented by $0$, while claimed cells are represented by $1$. The initial state of the matrix is given. ... | ```python
t = int(input())
for _ in range(t):
n, m = [int(x) for x in input().split()]
grid = [[int(x) for x in input().split()] for _ in range(n)]
rows = sum(1 for x in grid if all(y == 0 for y in x))
cols = sum(1 for j in range(m) if all(grid[i][j] == 0 for i in range(n)))
res = min(rows, cols)... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time.
Polycarp is good at marketing, so he has already collec... | ```python
from bisect import bisect_left, insort_left
a = []
n = int(input())
for _ in range(n):
#print(a)
s, d = list(map(int, input().split()))
if len(a) == 0:
print(s, s+d - 1)
a.append((s, s + d - 1))
continue
p = bisect_left(a, (s, s + d - 1))
#print('p', p)
ok = Tru... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Given a Complete Binary Tree of ‘n’ depth, you can perform 4 types of mirror operation on the tree:-
Mirror on the right. The tree is mirrored to the right and rightmost node on every level is connected with the mirrored corresponding node.
Mi... | ```python
import os,sys
from io import BytesIO, IOBase
def ii(): return int(input())
def si(): return input()
def mi(): return list(map(int,input().split()))
def li(): return list(mi())
import math
import collections
def CountFrequency(arr):
return collections.Counter(arr)
for i in range(1):
n,q=mi()
p=pow(2... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Three Best Friends $AMAN$ , $AKBAR$ , $ANTHONY$ are planning to go to “GOA” , but just like every other goa trip plan there is a problem to their plan too.
Their parents will only give permission if they can solve this problem for them
They are... | ```python
import sys
def get_array(): return list(map(int , sys.stdin.readline().strip().split()))
def get_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()
import sys
sys.setrecursionlimit(10**9)
from math import sqrt,ceil,floor
n=int(input())
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or alive
NEKO#ΦωΦ has just got a new maze game on her PC!
The game's main puzzle is a maze, in the forms of a $2 \times n$ rectangle grid. NEKO's task is to lead a Nekomimi girl fro... | ```python
import sys
readline = sys.stdin.readline
N, Q = list(map(int, readline().split()))
state = [[False]*(N+2) for _ in range(2)]
cnt = 0
Ans = [None]*Q
for qu in range(Q):
r, c = list(map(int, readline().split()))
r -= 1
c -= 1
state[r][c] = not state[r][c]
res = state[r-1][c-1] + state[r-1... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
One day Chef was playing with numbers. He loves Lowest Common Multiple (LCM) too much and he is a very curious guy. He always try to do new things. Now he want to make a large number with it. But he doesn't want to take too many numbers.
He is ... | ```python
from fractions import gcd
for testCases in range(eval(input())):
n = eval(input())
if n == 1:
print('1')
elif n == 2:
print('2')
elif n == 3:
print('6')
else:
c = n*(n-1)
k = n - 2
while True:
if gcd(k,n-1) == 1 and gcd(k,n) == 1:
break
k -= 1
d = (n-1)*(n - 2)
k1 = n - 3
whil... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Consider the following algorithm
order(arr, i) {
if length(arr) <= 1 {
return arr
}
l = []
r = []
n = length(arr) - 1
for j in 0, 1, ..., n {
if ( (arr[j] modulo power(2,i+1)) < power(2,i) ) {
append arr[j] to l
}else{
append arr[j] to r
}
}
... | ```python
for _ in range(int(input())):
p, idx = map(int, input().split())
b = bin(idx)[2:]
b = ('0' * (p - len(b)) + b)[::-1]
print(int(b, 2))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Let's define the niceness of a sequence of positive integers X1,X2,…,XN$X_1, X_2, \dots, X_N$ as the sum of greatest common divisors of all pairs of its elements, i.e.
N∑i=1N∑j=i+1gcd(Xi,Xj).∑i=1N∑j=i+1Ngcd(Xi,Xj).\sum_{i=1}^N \sum_{j=i+1}^N \ma... | ```python
# cook your dish here
mod = 10**9 + 7
from math import gcd
def fac50():
f = [0]*51
f[0] ,f[1] = 1,1
for i in range(1,51):f[i] = (f[i-1]*i)%mod
return f
def gcd110():
gc = [[0]*111 for i in range(111)]
for i in range(111):
for j in range(111):gc[i][j] = gcd(i,j)
return gc
fa... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e.... | ```python
n = int(input())
arr = []
for i in range(n):
l,r = map(int, input().split())
arr.append([l,r])
lts = []
for i in range(n):
if arr[i][0] == 0:
l = i
j = i
while arr[j][1] != 0:
j = arr[j][1] - 1
r = j
lts.append([l,r])
for i in range(1, len(... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a permutation $p=[p_1, p_2, \ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \le m \le n$) beautiful, if there exists two indices $l, r$ ($1 \le l \le r \le n$), such that the numbers $[p_l, p_{l+1}, \ldots,... | ```python
for _ in range(int(input())):
input()
nums = [int(x) for x in input().split()]
new_ar = list(zip(nums,[i for i in range(len(nums))]))
new_ar.sort()
maxx = new_ar[0][1]
minn = new_ar[0][1]
s="1"
for j in range(1,len(new_ar)):
if(new_ar[j][1]>maxx):
maxx ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Oliver and Nova are true lovers. Inspite of knowing that Nova will die Oliver married her at the lake where they met. But they had a conflict about even and odd numbers. Nova likes the odd numbers and Oliver prefers even. One day they went to a ... | ```python
import math
def lcm(a, b):
return (a*b)//gcd(a, b)
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
for _ in range(int(input())):
n = int(input())
na = math.ceil((2*n)/math.acos(-1))
nb = ((n+1)//2)**2
nlcm = lcm(na, nb)
oa = math.ceil(n/2)
ob = (... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef would like go shopping to buy ingredients for his special dish. The local grocery store has some special discount offers. If you want to buy some set of ingredients you will pay for all ingredients except the cheapest one. Chef would like t... | ```python
from itertools import permutations as p
def disc(a,b):
for ai in a:
for bi in b:
if ai==bi:
return False
return True
for i in range(eval(input())):
n = eval(input())
arr = list(map(int,input().split()))
perms = list(p(arr))
m = eval(input())
offer = {}
for i in range(m):
dup = list(map(int... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There is a directed graph with N vertices and N edges. The vertices are numbered 1, 2, ..., N.
The graph has the following N edges: (p_1, 1), (p_2, 2), ..., (p_N, N), and the graph is weakly connected. Here, an edge from Vertex u to Vertex v is ... | ```python
import sys
sys.setrecursionlimit(10**6)
n = int(input())
p = list(map(int, input().split()))
c = [[] for _ in range(n)]
is_leaf = [True for _ in range(n)]
for i in range(n):
p[i] -= 1
c[p[i]].append(i)
is_leaf[p[i]] = False
if sum(is_leaf) == 0:
if n%2 == 0:
print("POSSIBLE")
else:
print("IMPOSSIBLE... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Humpy, the little elephant, has his birthday coming up. He invited all his cousins but doesn’t know how many of them are really coming as some of them are having exams coming up. He will only get to know how many of them are coming on the day of... | ```python
# your code goes here
from sys import stdin, stdout
n = int(stdin.readline())
while n:
n -= 1
k, l, e = map(int, stdin.readline().strip().split(' '))
a = map(int, stdin.readline().strip().split(' '))
x = float(l) / float(e + sum(a))
if x - int(x):
stdout.write("NO\n")
else:
stdout.write("YES\n")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a tree rooted at node $1$ with $N$ vertices. The $i$$th$ vertex initially has value $A_i (1 \leq i \leq N)$. You are also given $Q$ queries.
In each query you are given a vertex $V$. Let $S = \{ S_1 , S_2 , ... S_x \} $ denote th... | ```python
from collections import defaultdict as dd,deque as dq
def opbfs(u,vis,ll,parr):
q=dq([(u,0)])
uu=u
su=0
while q:
u,lol=q.pop()
par=parr[u]
if(lol%2==0):
vis[u]=1
su+=ll[u-1]
ll[u-1]=0
for j in d[u]:
if(j!=par):
q.appendleft((j,lol+1))
ll[uu-1]=su
def bfs(height,d,parr):
q=dq([... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
An area named Renus, is divided into $(N \times M)$ cells. According to archaeological survey the area contains huge amount of treasure. Some cells out of $(N \times M)$ cells contain treasure. But problem is, you can't go to every cell as some ... | ```python
t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().split()]
mat=[]
ans=[]
for i in range(n+2):
l=[]
p=[]
for j in range(m+2):
l.append(0)
p.append(1000000000)
mat.append(l)
ans.append(p)
y=int(input())
for i in range(y):
a,b=[int(x) for x in input().split()]
mat[a][b]=1
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Dhote and Shweta went on a tour by plane for the first time.Dhote was surprised by the conveyor belt at the airport.As Shweta was getting bored Dhote had an idea of playing a game with her.He asked Shweta to count the number of bags whose indiv... | ```python
t=int(input())
for _ in range(t):
size=int(input())
li=list(map(int,input().split()))
c = 0
for i in li:
if(i >=len(li)/2):
c += 1
print(c)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
-----General Statement:-----
Given the actual high and low temperatures for the day and the normal high and low temperatures for that day, calculate the average difference from normal.
-----Input:-----
The first line of the data set for this pr... | ```python
# cook your dish here
for _ in range (int(input())):
x1,y1,x2,y2=map(int,input().split())
av1=(x1+y1)/2
av2=(x2+y2)/2
if(av1>av2):
print(av1-av2," DEGREE(S) ABOVE NORMAL")
else:
print(av2-av1," DEGREE(S) BELOW NORMAL")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Ho, Ho, Ho!
It's Christmas time and our friendly grandpa Santa Claus is busy distributing gifts to all the nice children. With the rising population, Santa's workload every year gets increased and he seeks your help to wrap the gifts with fancy ... | ```python
# cook your dish here
def read_i_l(l=False):
m = list(map(int, input().strip().split(" ")))
if l:
return list(m)
else:
return m
def i():
return int(input().strip())
T = i()
L = []
"""for current in range(T):
line = ""
for i in range(current):
line+=str((T-i)%10)... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Everybody is worried about Rakesh as the boy does not have much knowledge about the real world. He can not go from one place to another on his own. It's high time he learned to explore the city. He is going to a relative's house situated on the ... | ```python
try:
t=int(input())
for i in range(t):
print("Case {}:".format(i+1), end=" ")
m, n = map(int,input().split())
x, y = map(int,input().split())
l = int(input())
a=input()
destx = a.count("R")-a.count("L")
desty = a.count("U")-a.count("D")
#print(destx, desty)
if (destx<0 or destx>m) or (de... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $k$ torches. One torch can be crafted using one stick and one coal.
Hopefully, you've met a very handsome wandering trader who has two trade o... | ```python
for haaghfj in range(int(input())):
x,y,k = list(map(int,input().split()))
print(k + (y * k + k - 1 +x-2) // (x - 1))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There are N pinholes on the xy-plane. The i-th pinhole is located at (x_i,y_i).
We will denote the Manhattan distance between the i-th and j-th pinholes as d(i,j)(=|x_i-x_j|+|y_i-y_j|).
You have a peculiar pair of compasses, called Manhattan Com... | ```python
N, a, b = list(map(int, input().split())); a -= 1; b -= 1
P = []
Q = []
for i in range(N):
x, y = list(map(int, input().split()))
P.append((x-y, x+y, i))
Q.append((x+y, x-y, i))
d = max(abs(P[a][0] - P[b][0]), abs(P[a][1] - P[b][1]))
*parent, = list(range(N))
def root(x):
if x == parent[x]:
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The chef was not happy with the binary number system, so he designed a new machine which is having 6 different states, i.e. in binary there is a total of 2 states as 0 and 1. Now, the chef is confused about how to correlate this machine to get a... | ```python
from sys import stdin, stdout
#from math import gcd as g
#a,b = map(int, stdin.readline().split())
#l1 = list(map(int, stdin.readline().split()))
l = [1,6,7]
c = 1
for x in range(3,100001):
if x%2==1:
a = l[c]*6
l.append(a)
else:
l.append(a+1)
c+=1
n = int(... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You have a sequence $a$ with length $N$ created by removing some elements (possibly zero) from a permutation of numbers $(1, 2, \dots, N)$. When an element is removed, the length of the sequence doesn't change, but there is an empty spot left wh... | ```python
from itertools import permutations
for _ in range(int(input())):
N,K=list(map(int,input().split()))
arr=list(map(int,input().split()))
arr1=[]
arr2=[]
for i in range(1,len(arr)+1):
arr1.append(i)
indexzero=[]
for i in range(0,len(arr)):
if(arr[i]==0):
indexzero.append(i)
else:
arr2.append(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.