source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Alice likes prime numbers. According to Alice, only those strings are nice whose sum of character values at a prime position is prime. She has a string $S$. Now, she has to count the number of nice strings which come before string $S$( including... | ```python
import sys
from collections import defaultdict
from copy import copy
MOD = 10**9 + 7
R = lambda t = int: t(input())
RL = lambda t = int: [t(x) for x in input().split()]
RLL = lambda n, t = int: [RL(t) for _ in range(n)]
# primes up to n
def primes(n):
P = []
n = int(n)
U = [1] * (n+1)
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p_1, p_2, ..., p_{n} for his birthday.
Jeff hates inversions in sequences. An inversion in sequence a_1, a_2, ..., a_{n} is a... | ```python
n = int(input())
inp = input()
seq = inp.split(' ')
seq = [ abs(int(x)) for x in seq ]
Max = max(seq)
nxt = [0] * n
cnt = [0] * n
pos = [n] * (Max+1)
for i in range(n-1, -1, -1):
nxt[i] = pos[seq[i]]
pos[seq[i]] = i
for i in range(0, Max+1):
j = pos[i]
while(j<n):
front = sum(cnt[0:j])... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a graph with $3 \cdot n$ vertices and $m$ edges. You are to find a matching of $n$ edges, or an independent set of $n$ vertices.
A set of edges is called a matching if no two edges share an endpoint.
A set of vertices is called a... | ```python
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
N, M = list(map(int, input().split()))
X = [[] for i in range(3*N)]
for i in range(M):
x, y = list(map(int, input().split()))
x, y = min(x,y), max(x,y)
X[x-1].append((y-1, i+1))
MAT = []
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the... | ```python
def solve(n,a):
tot=0
for i in range(n):
tot+=a[i]
diffs = [] #alla suffix - prefix diffs[i]=prefix-suffix om delas innan element i
diffs.append(-tot)
for i in range(n):
tot-=2*a[i]
diffs.append(-tot)
if tot==0:
return ("YES")
for i in range(... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new num... | ```python
n=int(input())
a=[]
for i in range(n):
a.append(list(map(int,input().split())))
m=int(input())
b=list(map(lambda x:int(x)-1,input().split()))
c=[]
now=0
k=0
ans=[]
for i in range(n):
t=a[i]
last=now
if t[0]==1:
now+=1
if len(c)<100000: c.append(t[1])
if k<m and b[k]==no... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process:
First, prepare Vertex 1, Vertex 2, ..., Vertex N.
For each i=1,2,...,n, perform the following operation:
- If p_i = 1, d... | ```python
import sys
from collections import deque
def diameter(n, links):
q = deque([(0, -1)])
v = 0
while q:
v, p = q.popleft()
q.extend((u, v) for u in links[v] if u != p)
q = deque([(v, -1)])
w = 0
parents = [-1] * n
while q:
w, p = q.popleft()
parents[... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
-----
CHEF N TIMINGS
-----
One day chef was working with some random numbers. Then he found something
interesting. He observed that no 240, 567, 9999 and 122 and called these numbers
nice as the digits in numbers are in increasing order. Also h... | ```python
for _ in range(int(input())):
n=input().rstrip()
n=[ele for ele in n]
l=len(n)
m=10**18+8
ini=1
for i in range(l-1,-1,-1):
if int(n[i])<=m:
if ini==1:
m=int(n[i])
else:
m=max(m,n[i])
else:
m=int(n[i])-1
n[i]=str(m)
for j in range(l-1,i,-1):
n[j]='9'
i=0
while n[i]=='... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.
There are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Prese... | ```python
# Contest: Codeforces Round #593 (Div. 2) (https://codeforces.com/contest/1236)
# Problem: B: Alice and the List of Presents (https://codeforces.com/contest/1236/problem/B)
def rint():
return int(input())
def rints():
return list(map(int, input().split()))
M = 10**9 + 7
n, m = rints()
print(pow((... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consist... | ```python
from collections import defaultdict as dd
from collections import deque
import bisect
import heapq
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
def solve():
n = ri()
output = [0] * (n)
Q = [(-n, 0 ,n - 1)]
for i in range(1, n + 1):
prev = ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Find the minimum area of a square land on which you can place two identical rectangular $a \times b$ houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally, You are given two identical rectangles ... | ```python
T = int(input())
for _ in range(T):
a, b = list(map(int, input().split()))
print(max(max(a, b), min(a, b) * 2)**2)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
For a vector $\vec{v} = (x, y)$, define $|v| = \sqrt{x^2 + y^2}$.
Allen had a bit too much to drink at the bar, which is at the origin. There are $n$ vectors $\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}$. Allen will make $n$ moves. As Allen's sense... | ```python
import random
n = int(input())
v = []
a = []
for i in range(n):
a.append(i)
for _ in range(0, n):
x, y = list(map(int, input().split()))
v.append([x, y, x*x+y*y])
while 1>0:
x = 0
y = 0
ans = [0]*n
random.shuffle(a)
for i in range(n):
if (x+v[a[i]][0])**2+(y+v[a[i]][... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Let's call an array $a_1, a_2, \dots, a_m$ of nonnegative integer numbers good if $a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$, where $\oplus$ denotes the bitwise XOR operation.
For example, array $[1, 2, 3, 6]$ is... | ```python
for nt in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
s=sum(l)
e=l[0]
for i in range(1,n):
e=e^l[i]
if s==2*e:
print(0)
print ()
else:
print(2)
print(e,s+e)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
We all know Gru loves Agnes very much. One day Agnes asked Gru to answer some of her queries. She lined up $N$ minions in a straight line from $1$ to $N$.
You are given an array $A$ which contains the height of minions. Agnes will ask him sever... | ```python
# cook your dish here
for _ in range(int(input())):
n=int(input())
a=[int(x) for x in input().split()]
sum=0
for i in range(n):
if a[i]%2==0:
sum+=1
a[i]=sum
q=int(input())
while q:
l,r=map(int,input().split())
if l!=1:
c=a[r-1]-a[l-2]
else:
c=a[r-1]
if c==0:
print("ODD")
els... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well.
We define a pair of integers (a, b) good, if G... | ```python
from math import sqrt
from fractions import gcd
l, r, x, y = list(map(int, input().split()))
if y % x != 0:
print(0)
return
lo = (l + x - 1) // x
hi = r // x
p = y // x
s = 0
k1 = 1
while k1 * k1 <= p:
k2 = p // k1
if lo <= k1 <= hi and lo <= k2 <= hi and gcd(k1, k2) == 1 and k1 * k2 == p:
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has the string s of length n consisted of digits 4 and 7.
The string s is called balanced
if there exits such integer x (1 ≤ x ≤ n) that the number of digits 4 in substring s[1; x) is equal to the number of digits 7 in substring s(x; n],
wh... | ```python
from math import factorial
def Ncr(n,r):
if r<0:return 0
return factorial(n)/(factorial(n-r)*factorial(r))
def solve(m,n):
modulo=10**9+7
if m==n:
return (Ncr(2*n-1,n-1)+Ncr(2*n-2,n-2))%modulo
elif m>n:
return (Ncr(m+n,n)-Ncr(m+n-2,n-1))%modulo
else:
return (Ncr... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Vietnamese and Bengali as well.
An $N$-bonacci sequence is an infinite sequence $F_1, F_2, \ldots$ such that for each integer $i > N$, $F_i$ is calculated as $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N})$, where $f$ is some function. A XOR $N$-bonacci s... | ```python
# cook your dish here
n,q=map(int,input().split())
ls=[int(i) for i in input().split()]
cur=0
s=[0]
for i in ls:
cur=cur^i
s.append(cur)
for i in range(q):
k=int(input())
print(s[k%(n+1)])
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A reversed arabic no is one whose digits have been written in the reversed order. However in this any trailing zeroes are omitted. The task at hand here is a simple one. You need to add two numbers which have been written in reversed arabic and ... | ```python
n = int(input())
for index in range(0, n):
a, b = list(map(str, input().split()))
a = int(a[::-1])
b = int(b[::-1])
a = str(a + b)
a = int(a[::-1])
print(a)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original charact... | ```python
n, k = map(int, input().split())
a = [0] * n
b = ['0'] * n
c = []
s = input()
for i in range(n):
if k != 0:
if s[i] == '(':
c.append(i)
else:
d = c.pop()
a[i] = 1
a[d] = 1
k -= 2
for i in range(n):
if a[i] == 1:
print(... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Forgotten languages (also known as extinct languages) are languages that are no longer in use. Such languages were, probably, widely used before and no one could have ever imagined that they will become extinct at some point. Unfortunately, that... | ```python
test_case = int(input())
for w in range(test_case):
n, k = map(int,input().split())
l = list(map(str,input().split()))
ans = []
for q in range(k):
l2 = list(map(str,input().split()))
ans.extend(l2[1:])
for i in l:
if i in ans:
print('YES',end=' ')
else:
print('NO',end=' ')
print()# cook yo... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be w_{i}, then 0 < w_1 ≤ w_2 ≤ ... ≤... | ```python
rd = lambda: list(map(int, input().split()))
rd()
a = sorted(rd(), reverse=True)
b = sorted(rd(), reverse=True)
if len(a) > len(b): print("YES"); return
for i in range(len(a)):
if a[i] > b[i]: print("YES"); return
print("NO")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.
Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ... | ```python
q = int(input())
for _ in range(q):
n, m = list(map(int, input().split()))
info = [list(map(int, input().split())) for i in range(n)]
info = sorted(info)
now =(m, m)
time = 0
flag = True
for i in range(n):
t, l, h = info[i]
l_now = now[0] - (t - time)
h_now ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car ... | ```python
import sys
readline = sys.stdin.readline
from collections import Counter
def getpar(Edge, p):
N = len(Edge)
par = [0]*N
par[0] = -1
par[p] -1
stack = [p]
visited = set([p])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a set $S$ and $Q$ queries. Initially, $S$ is empty. In each query:
- You are given a positive integer $X$.
- You should insert $X$ into $S$.
- For each $y \in S$ before this query such that $y \neq X$, you should also insert $y \op... | ```python
# fast io
import sys
def fop(s): sys.stdout.write(str(s)+'\n')
def fip(): return sys.stdin.readline()
fintinp = lambda : int(fip())
def flistinp(func= int): return list(map(func,fip().split()))
def fnsepline(n,func=str): return [func(fip()) for _ in range(n)]
#-------------------code------------------------... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point.
Wet Shark knows Rat ... | ```python
from math import log
from decimal import Decimal
s = ['x^y^z', 'x^z^y', '(x^y)^z', 'y^x^z', 'y^z^x', '(y^x)^z', 'z^x^y', 'z^y^x', '(z^x)^y']
x, y, z = list(map(Decimal, input().split()))
f = []
f += [(Decimal(log(x)) * (y ** z), 0)]
f += [(Decimal(log(x)) * (z ** y), -1)]
f += [(Decimal(log(x)) * (y * z)... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
This year $p$ footballers and $q$ cricketers have been invited to participate in IPL (Indian Programming League) as guests. You have to accommodate them in $r$ rooms such that-
- No room may remain empty.
- A room may contain either only footbal... | ```python
# cook your dish here
MOD = 998244353
fball = [ [0]*101 for _ in range(101) ]
cric = [ [0]*101 for _ in range(101) ]
def calSNum(n, r):
if n == r or r == 1:
fball[r][n] = 1
return
if n > 0 and r > 0 and n > r:
fball[r][n] = (fball[r-1][n-1]%MOD + (r*fball[r][n-1])%MOD )%MOD
return
fball[r][n]... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There are a lot of problems related to the shortest paths. Nevertheless, there are not much problems, related to the shortest paths in average.
Consider a directed graph G, consisting of N nodes and M edges. Consider a walk from the node A to th... | ```python
from collections import defaultdict
import copy
#def dfs(l,r,dct):
def dfs(l,r,dct):
visit=[0 for i in range(n+1)]
arr=[l]
while(arr):
node=arr.pop()
if node==r:return True
visit[node]=1
for lnk in dct[node]:
if not visit[lnk]:
arr.append(lnk)
return False
def ok(mid,cst):
for i,j in edg... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Sandy is a professor at a very reputed institute. The institute mandates that all the lectures be communicated in English. As Sandy is not very good at English(or anything actually) the presentations he displays in class have a lot of spelling m... | ```python
# cook your dish here
from difflib import get_close_matches
import sys, os
def closeMatches(patterns, word):
return get_close_matches(word, patterns, 1, 0.9)[0]
def get_string():
return sys.stdin.readline().strip()
def get_ints():
return map(int, sys.stdin.readline().strip().split())
ans = []
test... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Given a string s. Can you make it a palindrome by deleting exactly one character? Note that size of the string after deletion would be one less than it was before.
-----Input-----
First line of the input contains a single integer T denoting nu... | ```python
for _ in range(int(input())):
s=str(input())
n=len(s)
k=s[::-1]
a,b="",""
for i in range(n):
if s[i]!=k[i]:
a+=s[i+1:]
b+=k[i+1:]
break
else:
a+=s[i]
b+=k[i]
#print(a,b)
if a==a[::-1] or b==b[::-1]:
print("YES")
else:
print("NO")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The EEE classes are so boring that the students play games rather than paying attention during the lectures. Harsha and Dubey are playing one such game.
The game involves counting the number of anagramic pairs of a given string (you can read ab... | ```python
def sort_str(s):
o = []
for c in s:
o.append(c)
o.sort()
return "".join(o)
def find_ana(s):
if len(s) <= 1:
return 0
h = {}
c = 0
for i in range(len(s)):
for j in range(i+1, len(s)+1):
t = sort_str(s[i:j])
if t in h:
c += h... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Today is Chef's birthday. His mom decided to surprise him with a truly fantastic gift: his favourite binary string B. But, unfortunately, all the stocks of binary string B have been sold out, and only a binary string A (A ≠ B) is available in th... | ```python
for j in range(int(input())):
a=input()
b=input()
c,d=0,0
a0=a.count("0")
a1=a.count("1")
if(a0==len(a) or a1==len(a)):
print("Unlucky Chef")
else:
print("Lucky Chef")
for i in range(len(a)):
if(a[i]!=b[i]):
if(a[i]=="0"):
c+=1
else:
d+=1
print(max(c,d))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Raavan gave a problem to his son, Indrajeet, and asked him to solve the problem to prove his intelligence and power. The Problem was like: Given 3 integers, $N$, $K$, and $X$, produce an array $A$ of length $N$, in which the XOR of all elements ... | ```python
# cook your dish here
for _ in range(int(input())):
l,n,x=map(int,input().split())
m=[]
pw1 = (1 << 17);
pw2 = (1 << 18);
if (n == 1) :
m.append(x)
elif (n == 2 and x == 0) :
m.append(-1)
elif (n == 2) :
m.append(x)
m.append(0)
else :
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given Name of chef's friend and using chef's new method of calculating value of string , chef have to find the value of all the names. Since chef is busy , he asked you to do the work from him .
The method is a function $f(x)$ as follows... | ```python
vow = ['a', 'e', 'i','o', 'u']
for _ in range(int(input())):
name = str(input())
tmp = ''
for i in range(len(name)):
if name[i] not in vow and name[i].isalpha():
tmp+='1'
elif name[i] in vow and name[i].isalpha():
tmp+='0'
print( int(tmp, 2)% (10**9 + 7))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
This is the easy version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings $a$ and... | ```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... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
After acquiring an extraordinary amount of knowledge through programming contests, Malvika decided to harness her expertise to train the next generation of Indian programmers. So, she decided to hold a programming camp. In the camp, she held a d... | ```python
for _ in range(int(input())):
n,m=map(int, input().split())
if n==1:
print(0)
elif n==2:
print(m)
else:
print(m*2+n-3)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There is crazy man named P29892P. He always tries to do crazy things as he thinks. One day he invented a machine and named it as ANGEN. The ANGEN is used to perform range operations. The range operation means performing operations on range value... | ```python
VQ = "UAMmSs"
n = int(input())
a = list(map(int, input().split()))
for _ in range(int(input())):
q, x, y = input().split()
if q not in VQ:
print("!!!")
continue
if q == "U":
a[int(x) - 1] = int(y)
continue
l = int(x) - 1
r = int(y)
if q == "A":
print(sum(a[l:r]))
continue
if q == "M":
pri... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef wants you to distribute candies among $N$ kids who are sitting in a circle. However, he wants to make some kids jealous of others. Thus, he wants you to distribute candies in such a way that there is a difference of at least $K$ candies bet... | ```python
# cook your dish here
for _ in range(int(input())):
n,k = [int(v) for v in input().split()]
ans = (n//2)*(k+2)
if n%2 == 0:
ans = ans
else:
ans += 1 + 2*k
print(ans)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Henry and Derek are waiting on a room, eager to join the Snackdown 2016 Qualifier Round. They decide to pass the time by playing a game.
In this game's setup, they write N positive integers on a blackboard. Then the players take turns, startin... | ```python
gb = [0, 1, 2, 2, 3, 3]
ga = [0 for x in range(70)]
gag = [0 for x in range(70)]
ga[0] = 1
gag[0] = 0
for i in range(1, 70):
if i % 4 == 0:
ga[i] = 1.5 * ga[i-1]
gag[i] = 0
else:
ga[i] = 2 * ga[i-1]
gag[i] = gag[i-1] + 1
def g(n):
if n < 6:
return gb[n]
else:
x = n / 6
a = 0
for i, k in... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
This is a simple game you must have played around with during your school days, calculating FLAMES of you and your crush! Given the names of two people, cancel out the common letters (repeated occurrence of a letter is treated separately, so 2A'... | ```python
import sys
def joseph(k, n=6):
if k==0:
k = 1
x = 0
for i in range(2,n+1):
x = (x+k)%i
return x
FLAMES = ['FRIENDS', 'LOVE', 'ADORE', 'MARRIAGE', 'ENEMIES', 'SISTER']
nCase = int(sys.stdin.readline())
for _ in range(nCase):
a = ''.join(sys.stdin.readline().split())
b = ''.join(sys.stdin.readline(... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There'... | ```python
n, m = map(int, input().split())
p, d = [0] * (n + 2), [0] * (n + 2)
for i in range(m):
l, r, x = map(int, input().split())
while l < x:
if d[l]:
k = d[l]
d[l] = x - l
l += k
else:
d[l], p[l] = x - l, x
l += 1
l += 1
r... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are provided with an input containing a number. Implement a solution to find the largest sum of consecutive increasing digits , and present the output with the largest sum and the positon of start and end of the consecutive digits.
Example :... | ```python
l=list(map(int,input()))
t=-1
x=-1
y=-1
for i in range(len(l)):
s=l[i]
a=i+1
b=i+1
for j in range(i+1,len(l)):
if l[i]<l[j]:
s=s+l[j]
b=j+1
else:
break
if s>t:
t=s
x=a
y=b
print(t,end=":")
print(x,y,sep="-")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Toad Zitz has an array of integers, each integer is between $0$ and $m-1$ inclusive. The integers are $a_1, a_2, \ldots, a_n$.
In one operation Zitz can choose an integer $k$ and $k$ indices $i_1, i_2, \ldots, i_k$ such that $1 \leq i_1 < i_2 <... | ```python
import sys
input = sys.stdin.readline
n,m=list(map(int,input().split()))
A=list(map(int,input().split()))
MIN=0
MAX=m
while MIN!=MAX:
x=(MIN+MAX)//2
#print(x,MIN,MAX)
#print()
M=0
for a in A:
#print(a,M)
if a<=M and a+x>=M:
continue
elif a>M and a+x... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test case... | ```python
n = int(input())
l = [0] * n
for x in range(n):
l[x] = int(input())
for i in range(n):
z = 1
for j in range(1,l[i]+1):
for k in range(1,l[i]+1):
print(z,end='')
z += 2
print()
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.
A substring $s[l ... | ```python
s = input()
mx = 0
n = len(s)
for l in range(n):
for r in range(l, n):
if s[l:r+1] != s[l:r+1][::-1]:
mx = max(mx, r - l + 1)
print(mx)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The chef was searching for his pen in the garage but he found his old machine with a display and some numbers on it. If some numbers entered then some different output occurs on the display. Chef wants to crack the algorithm that the machine is ... | ```python
# cook your dish here
T = int(input())
for t in range(T):
N = int(input())
print(int(((N-1)*(N))/2))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Sheldon is a little geek living in Texas. While his friends like to play outside, little Sheldon likes to play around with ICs and lasers in his house. He decides to build N clap activated toggle machines each with one power inlet and one outlet... | ```python
n=int(input())
while n>0:
i=1
a,b=(int(i) for i in input().split())
if (b+1)%(i<<a)==0:
print("ON")
else:
print("OFF")
n=n-1
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A manufacturing project consists of exactly $K$ tasks. The board overviewing the project wants to hire $K$ teams of workers — one for each task. All teams begin working simultaneously.
Obviously, there must be at least one person in each team. F... | ```python
from math import log2;
import bisect;
from bisect import bisect_left,bisect_right
import sys;
from math import gcd,sqrt
sys.setrecursionlimit(10**7)
from collections import defaultdict
inf=float("inf")
# n=int(input())
# n,m=map(int,input().split())
# l=list(map(int,input().split()))
def get_factors(x):
if x... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level... | ```python
n, t = list(map(int,input().split()))
g = [[0.0] * i for i in range(1,n+1)]
for _ in range(t):
g[0][0] += 1.0
for i in range(n):
for j in range(i+1):
spill = max(0, g[i][j] - 1.0)
g[i][j] -= spill
if i < n - 1:
g[i + 1][j] += spill / 2
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in th... | ```python
import sys
input = sys.stdin.readline
from bisect import bisect_right
bin_s = [1]
while bin_s[-1] <= 10 ** 9:
bin_s.append(bin_s[-1] * 2)
def main():
n, q = map(int, input().split())
alst = list(map(int, input().split()))
dp = [[-1, -1] for _ in range(n)]
dp[0] = [alst[0], 0]
for i,... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Karen is getting ready for a new school day!
[Image]
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum... | ```python
s = input()
h = int(s[:2])
m = int(s[3:])
def ispalin(h, m):
s = "%02d:%02d"%(h,m)
return s == s[::-1]
for d in range(999999):
if ispalin(h, m):
print(d)
break
m+= 1
if m == 60:
h = (h+1)%24
m = 0
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns.... | ```python
"""
Codeforces Contest 260 Div 1 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
def main():
n,k = read()
s = set()
for i in range(n): s.add(read(0))
s = list(s)
s.sort()
s = treeify(s)
res = solve(s)
if res == 0: # neither: second player win
print("Second"... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a sequence a_1, a_2, ..., a_{n} of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment a_{i} lies within segment a_{j}.
Segment [l_1, r_1] lies within segment [l_2, r_... | ```python
n = int(input())
a = []
for i in range(1, n + 1):
l, r = list(map(int, input().split()))
a.append([l, -r, i])
a.sort()
hh = a[0][1]
wahh = max(-1, a[0][2])
for i in range(1, n):
if a[i][1] >= hh:
print(a[i][2], wahh)
return
else:
hh = a[i][1]
wahh = a[i][2]
prin... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between... | ```python
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5)
N, Q = map(int, input().split())
path = [[] for _ in range(N)]
for _ in range(N-1) :
a, b, c, d = (int(i) for i in input().split())
path[a-1].append((b-1, c-1, d))
path[b-1].append((a-1, c-1, d))
# doublingに必要なKを求める
for K in ra... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Your are given a string $S$ containing only lowercase letter and a array of character $arr$. Find whether the given string only contains characters from the given character array.
Print $1$ if the string contains characters from the given array... | ```python
t=int(input())
for _ in range(t):
S=set(input().strip())
n=int(input().strip())
a=set(input().strip().split(" "))
g=True
for i in S:
if(i not in a):
g=False
if(g):
print(1)
else:
print(0)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. Yo... | ```python
import sys
input = sys.stdin.readline
rInt = lambda: int(input())
mInt = lambda: map(int, input().split())
rLis = lambda: list(map(int, input().split()))
outs = []
t = rInt()
for _ in range(t):
n, k = mInt()
s = input()
pref = [0]
for c in s:
if c == '1':
pref.append(pre... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Problem description.
Winston and Royce love sharing memes with each other. They express the amount of seconds they laughed ar a meme as the number of ‘XD’ subsequences in their messages. Being optimization freaks, they wanted to find the string ... | ```python
t=int(input())
for i in range(t):
n=int(input())
r=int(n**(.5))
d=n-r*r
m=d%r
print('X'*m+'D'*(m>0)+'X'*(r-m)+'D'*(r+d//r))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.
Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.
Recently, they learned the operation called xor (exclusive OR).What is xor?
For n non-neg... | ```python
n=int(input())
a=list(map(int,input().split()))
X=[]
b=a[0]
for i in range(1,n) :
b^=a[i]
for i in range(n) :
x=b^a[i]
X.append(x)
for i in X :
print(i,end=" ")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
"How did you get the deal,how did he agree?"
"Its's simple Tom I just made him an offer he couldn't refuse"
Ayush is the owner of a big construction company and a close aide of Don Vito The Godfather, recently with the help of the Godfather his... | ```python
for _ in range(int(input())):
n=int(input())
print((2*(pow(n,2)))-n+1)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Edo has got a collection of n refrigerator magnets!
He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door mus... | ```python
from sys import*
#
def check(u, d, l, r):
used = [pointsx[i][1] for i in range(l)]
used += [pointsx[-1 - i][1] for i in range(r)]
used += [pointsy[i][1] for i in range(u)]
used += [pointsy[-1 - i][1] for i in range(d)]
if len(set(used)) > k:
return DOHERA
dx = pointsx[-1 - r][0... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There is a girl named ''Akansha''. She is very fond of eating chocolates but she has a weak immune system due to which she gets cold after eating chocolate during morning, evening and night and can only eat at most $x$ number of chocolate each a... | ```python
for t in range(int(input().strip())):
n = int(input().strip())
x = int(input().strip())
arr = list(map(int, input().strip().split()))
arr.sort()
day = 1
acc = 0
isPossible = True
for a in arr:
acc += 1
if acc > x:
day += 1
acc = 1
if day >= a:
isPossible = False
break
print("Possib... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Shivam owns a gambling house, which has a special wheel called The Wheel of Fortune.
This wheel is meant for giving free coins to people coming in the house.
The wheel of fortune is a game of chance. It uses a spinning wheel with exactly N nu... | ```python
t=int(input())
for _ in range(t):
n=int(input())
arr=list(map(int,input().split()))
d={}
for i in range(n):
if arr[i] in d:
d[arr[i]].append(i)
else:
d[arr[i]]=[i]
q=int(input())
for i in range(q):
m=int(input())
if l... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p_1, p_2, ..., p_{n}. Then the guys take... | ```python
3
import sys
class CumTree:
def __init__(self, a, b):
self.a = a
self.b = b
self.count = 0
if a == b:
return
mid = (a + b) // 2
self.levo = CumTree(a, mid)
self.desno = CumTree(mid+1, b)
def manjsi(self, t):
if... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Little X has n distinct integers: p_1, p_2, ..., p_{n}. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: If number x belongs to set A, then number a - x must also belong to set A. If number ... | ```python
from collections import defaultdict
def solve(n, a, b, xs):
group = [None] * n
id_ = {x: i for i, x in enumerate(xs)}
if a == b:
for x in xs:
if a - x not in id_:
return False
group = [0] * n
else:
for i, x in enumerate(xs):
if g... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
“Jesse, you asked me if I was in the meth business, or the money business… Neither. I’m in the empire business.”
Walter’s sold his stack in Gray Matter Technologies, a company which he deserved half a credit, for peanuts. Now this company is wor... | ```python
# cook your dish here
T=int(input())
for _ in range(T):
n=int(input())
arr=list(map(int,input().split()))
left=[-1 for i in range(n)]
right=[-1 for i in range(n)]
min1=float("inf")
for i in range(n):
min1=min(arr[i],min1+1)
left[i]=min1
min1=float("inf")
for i in range(n-1,-1,-1):
min1=min(arr[i... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given an integer $D$. Find an integer sequence $A_1, A_2, \ldots, A_N$ such that the following conditions are satisfied:
- $1 \le N \le 10^5$
- $1 \le A_i \le 10^5$ for each valid $i$
- $\sum_{i=1}^N \sum_{j=i}^N \left( \mathrm{min}(A_i,... | ```python
# cook your dish here
t=int(input())
for i in range(t):
D=int(input())
P=10**5-2
ans=[]
if(D==0):
ans.append(1)
while(D>0):
P=min(P,D)
ans.append(P+2);
ans.append(P+1);
ans.append(1);
D=D-P;
print(len(ans))
print(*ans,sep=" ",end="\n")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets: the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are pairwise distinct (i.e. all $a_i$ are different), the $i$-th bracelet has a brightness ... | ```python
#list(map(int,input().split()))
t=int(input())
for _ in range(t):
n=int(input())
aa=list(map(int,input().split()))
bb=list(map(int,input().split()))
aa.sort()
bb.sort()
print(*aa)
print(*bb)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Golomb sequence $G_1, G_2, \ldots$ is a non-decreasing integer sequence such that for each positive integer $n$, $G_n$ is the number of occurrences of $n$ in this sequence. The first few elements of $G$ are $[1, 2, 2, 3, 3, 4, 4, 4, 5, \ldot... | ```python
def find_upper_bound(arr,key):
low,high = 0,len(arr)-1
while low<=high:
mid = (low+high)//2
if arr[mid]==key:return mid
elif arr[mid]>key and mid-1>=0 and arr[mid-1]<key:return mid
elif arr[mid]>key:high = mid - 1
else:low = mid + 1
return mid
def get_query(l):
nonlocal prefix_storer,bin_st... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given an array of N integers a1, a2, ..., aN and an integer K. Find the number of such unordered pairs {i, j} that
- i ≠ j
- |ai + aj - K| is minimal possible
Output the minimal possible value of |ai + aj - K| (where i ≠ j) and the n... | ```python
for _ in range(int(input())):
n,k=list(map(int, input().split()))
l=list(map(int, input().split()))
l.sort()
c=0
mn=abs(l[0]+l[1]-k)
for i in range(n-1):
for j in range(i+1, n):
temp=abs(l[i]+l[j]-k)
if temp==mn:
c+=1
elif temp<mn:
mn=temp
c=1
elif l[i]+l[j]-k>mn:... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $p$ of length $n$, and Skynyrd bought an array $a$ of length $m$, consisting of integers from $1$ to $n$.
Lynyrd and Skynyrd became bored, so they asked you $q$ queri... | ```python
import sys
inp = [int(x) for x in sys.stdin.read().split()]
n, m, q = inp[0], inp[1], inp[2]
p = [inp[idx] for idx in range(3, n + 3)]
index_arr = [0] * (n + 1)
for i in range(n): index_arr[p[i]] = i
a = [inp[idx] for idx in range(n + 3, n + 3 + m)]
leftmost_pos = [m] * (n + 1)
next = [-1] * m
for ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout a... | ```python
def main():
n, m = list(map(int, input().split()))
aa = []
for _ in range(n):
row = list(map(int, input().split()))
row.append(0)
aa.append(row)
aa.append([0] * (m + 1))
d1, d2, d3, d4 = ([[0] * (m + 1) for _ in range(n + 1)] for _ in (1, 2, 3, 4))
for i in rang... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange.
Since... | ```python
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 *... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
As we all know, Chef is cooking string for long days, his new discovery on string is the longest common pattern length. The longest common pattern length between two strings is the maximum number of characters that both strings have in common. C... | ```python
from collections import Counter
def solve(A,B):
a = Counter(A)
b = Counter(B)
ans = 0
for i in a:
if i in b:
ans += min(a[i],b[i])
return ans
t = int(input())
for _ in range(t):
A = input()
B = input()
print(solve(A,B)... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Codefortia is a small island country located somewhere in the West Pacific. It consists of $n$ settlements connected by $m$ bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to... | ```python
import heapq
n,m,a,b=map(int,input().split())
graph={i:[] for i in range(n)}
for i in range(m):
u,v,w=map(int,input().split())
graph[u-1].append((v-1,w))
graph[v-1].append((u-1,w))
components=[-1]*n
comp=-1
for i in range(n):
if components[i]==-1:
comp+=1
components[i]=comp
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
A repetition-free number is one in which each digit $\{1,2,3,…,9\}$ appears at most once and the digit $0$ does not appear. A repetition-free number can have at most nine digits, but may also have fewer than nine digits. Some examples of repetit... | ```python
N = int(input())
i = N + 1
flag = 0
for i in range(N+1, 987654321):
a = str(i)
b = list(a)
c = set(a)
if '0' not in b:
if len(b) == len(c):
print(i)
flag += 1
break
if flag < 1:
print(0)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The Gray code (see wikipedia for more details) is a well-known concept.
One of its important properties is that every two adjacent numbers have exactly one different digit in their binary representation.
In this problem, we will give you n non-... | ```python
dic = {}
#num = "1"
#def tonum(num):
# res=0
# for i in range(len(num)):
# res = 2*res + int(num[i])
# return res
#for i in range(64):
# number = tonum(num)
# dic[num] = []
# num = num+"0"
n = int(input())
flag=0
if n >= 68:
inp = input()
print("Yes")
else:
inp = [int(x) for x in input(... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
The chef is very expert in coding, so to keep his password safe from the hackers. He always enters a decoded code of his password. You are a hacker and your work is to find the maximum number of possible ways to unlock his password in encoded fo... | ```python
t = int(input())
while t>0:
s = input().strip()
if not s:
print('NO')
dp = [0 for x in range(len(s) + 1)]
dp[0] = 1
dp[1] = 1 if 0 < int(s[0]) <= 9 else 0
for i in range(2, len(s) + 1):
if 0 < int(s[i-1:i]) <= 9:
dp[i] += dp[i - 1]
if s[i-2:i][0] != '0' and int(s[i-2:i]) <= 26:
dp[i] += dp... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Indian National Olympiad in Informatics 2016
Boing Inc, has N employees, numbered 1 ... N. Every employee other than Mr. Hojo (the head of the company) has a manager (P[i] denotes the manager of employee i). Thus an employee may manage any numb... | ```python
import sys
from collections import defaultdict
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
arr=[int(x) for x in input().split()]
if arr[0]==1:
print(0)
return
p=[None]
for i in range(1,arr[0]+1):
p.append(arr[i])
a=[None]
for i in range(arr[0]+1,2*arr[0]+1):
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Problem description.
Dominic Toretto has taken his crew to compete in this years' Race Wars, a crew-on-crew tournament in which each member of one crew competes with a member of the other crew in a quarter mile drag race. Each win counts as one ... | ```python
testcases = int(input())
for i in range(testcases):
n = int(input())
my = list(map(int,input().split()))
opp = list(map(int,input().split()))
my.sort(reverse = True)
opp.sort(reverse = True)
j = 0
k = 0
while(k < n):
if(my[j] > opp[k]):
j += 1
k += 1
print(j)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array $b$ good, if sum of its elements is divisible by the length of this array. For example, array $[2, 3, 1]$ is good, as sum of its elem... | ```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Let X be the set of all integers between 0 and n-1. Suppose we have a collection S1, S2, ..., Sm of subsets of X. Say an atom A is a subset of X such that for each Si we have either A is a subset of Si or A and Si do not have any common elements... | ```python
# cook your dish here
# cook your dish here
for _ in range(int(input())):
n,m=list(map(int,input().split()))
atomlist = ['']*n
for k in range(m):
s=[]
s.extend(input().split()[1:])
#print(s)
for w in range(n):
if str(w) in s:
atomlist[w]+="1"
else:
atomlist[w]+="0"
#print(atomlist)
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Today, Chef decided to cook some delicious meals from the ingredients in his kitchen. There are $N$ ingredients, represented by strings $S_1, S_2, \ldots, S_N$. Chef took all the ingredients, put them into a cauldron and mixed them up.
In the ca... | ```python
# cook your dish here
t=int(input())
while t>0:
n=int(input())
li=[]
c,o,d,e,h,f=0,0,0,0,0,0
for i in range(0,n):
s=input()
for i in range(len(s)):
if s[i]=='c':
c=c+1
elif s[i]=='o':
o=o+1
elif s[i]=='d':
d=d+1
elif s[i]=='e':
e=e+1
elif s[i]=='h':
h=h+1
elif ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ ... | ```python
import sys
input = sys.stdin.readline
MOD = 987654103
n = int(input())
t = input()
place = []
f1 = []
e1 = []
s = []
curr = 0
count1 = 0
for i in range(n):
c = t[i]
if c == '0':
if count1:
e1.append(i - 1)
if count1 & 1:
s.append(1)
c... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t).
He can move in arbitrary directions with speed 1.
Here, we will consider him as a point without size.
There are N circular barriers deployed on the plan... | ```python
def main():
import sys
input = sys.stdin.readline
import heapq
def dijkstra_heap(s,g,edge):
#始点sから各頂点への最短距離
d = [10**20] * (n+2)
used = [True] * (n+2) #True:未確定
d[s] = 0
used[s] = False
edgelist = []
sx,sy,sr=edge[s][0],edge[s][1],edge[s... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Screen resolution of Polycarp's monitor is $a \times b$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $(x, y)$ ($0 \le x < a, 0 \le y < b$). You can consider columns of pixels to be numbered from $0$ to $a-1$, ... | ```python
from math import *
zzz = int(input())
for zz in range(zzz):
a, b, x, y = list(map(int, input().split()))
print(max(x*b, (a-x-1)*b, y*a, (b - y - 1)*a))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You are given an array A with size N (indexed from 0) and an integer K. Let's define another array B with size N · K as the array that's formed by concatenating K copies of array A.
For example, if A = {1, 2} and K = 3, then B = {1, 2, 1, 2, 1, ... | ```python
def max_sum(arr):
# Finds the maximum sum of sub-arrays of arr
max_till_now = -1000000 #minimum possible number
current_sum = 0
for i in range(len(arr)):
if current_sum < 0:
# If sum of previous elements is negative, then ignore them. Start fresh
# with `curren... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There is a field with plants — a grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$); out of its $NM$ cells, $K$ cells contain plants, while the rest contain weeds. Two cells are adjacent if they have a commo... | ```python
t=int(input())
while(t):
t-=1
d={}
n,m,k=[int(x) for x in list(input().split())]
sum=0
while(k):
k-=1
x,y=[int(x) for x in list(input().split())]
a=[-1,1,0,0]
b=[0,0,-1,1]
for i in range(4):
if((x+a[i],y+b[i]) in d):
sum-=1
else:
sum+=1
d[(x,y)]=1
print(sum)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Scheme? - Too loudly said. Just a new idea. Now Chef is expanding his business. He wants to make some new restaurants in the big city of Lviv. To make his business competitive he should interest customers. Now he knows how. But don't tell anyone... | ```python
r = 1000000007
t = int(input())
for i in range(t):
n = int(input())
print(pow(3,n,r) + pow(-1,n)*3)
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Three numbers A, B and C are the inputs. Write a program to find second largest among them.
-----Input-----
The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains three integers A, B and C... | ```python
# cook your dish here
x=int(input())
for i in range(x):
s=list(map(int,input().split()))
s.sort()
print(s[1])
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Vanja and Miksi really like games. After playing one game for a long time, they decided to invent another game!
In this game, they have a sequence $A_1, A_2, \dots, A_N$ and two numbers $Z_1$ and $Z_2$. The rules of the game are as follows:
- Th... | ```python
import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
#sys.setrecursio... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (x_{i}, y_{i}). All sensors are located at distinct points strictly inside the rectangle.
Opposite corners of the room are located at... | ```python
n, m, k = list(map(int,input().split()))
dm, dp = {}, {}
vis = {}
sensors = []
border = set()
for el in [(0, m), (n, 0), (0, 0), (n, m)]:
border.add(el)
for _ in range(k):
x, y = list(map(int, input().split()))
if not (x - y) in dm:
dm[x - y] = []
dm[x - y].append((x, y))
if not (... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Write a program, which takes an integer N and if the number is less than 10 then display "Thanks for helping Chef!" otherwise print "-1".
-----Input-----
The first line contains an integer T, total number of testcases. Then follow T lines, eac... | ```python
# cook your dish here
for i in range(int(input())):
x=int(input())
if x<10:
print("Thanks for helping Chef!")
else:
print("-1")
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $n$ carrots with lengths $a_1, a_2, a_3, \ldots, a_n$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $k$ rabbits and does not have enough ca... | ```python
import heapq
def sum_sqaure(a, k):
q, r = divmod(a, k)
return q**2 * (k-r) + (q+1)**2 * r
def diff(a, k):
return sum_sqaure(a, k+1) - sum_sqaure(a, k)
n, k = map(int, input().split())
nums = list(map(int, input().split()))
curr = sum(sum_sqaure(a, 1) for a in nums)
Q = [(diff(a, 1), a, 1) for ... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Fennec and Snuke are playing a board game.
On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by... | ```python
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10 ** 6)
def main():
n = int(input())
adj_list = [[] for i in range(n)]
for i in range(n - 1):
a1, b1 = list(map(int, sys.stdin.readline().split()))
adj_list[a1 - 1].append(b1 - 1)
adj_list[b1 - 1].append(a1 - 1)
... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
We have a board with an H \times W grid.
Each square in the grid is painted in black or white. The square at the i-th row from the top and j-th column from the left is black if the j-th character in S_i is #, and white if that character is ..
Sn... | ```python
import sys
def input():
return sys.stdin.readline()[:-1]
H, W = map(int, input().split())
s = [input() for _ in range(H)]
ans = max(H, W)
def max_rect(a):
res = 0
stack = [a[0]]
for i in range(1, W-1):
new_pos = i
while stack and stack[-1] % 10000 >= a[i]:
pos, hght = stack[-1] // 10000, stack[-1... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You have a fence consisting of $n$ vertical boards. The width of each board is $1$. The height of the $i$-th board is $a_i$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fenc... | ```python
3
import math
import os
import sys
DEBUG = 'DEBUG' in os.environ
def inp():
return sys.stdin.readline().rstrip()
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
INF = 10 ** 20
def solve(N, A, B):
dp = {A[0]: 0, A[0] + 1: B[0], A[0] + 2: B[0] * 2}... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Today a plane was hijacked by a maniac. All the passengers of the flight are taken as hostage. Chef is also one of them.
He invited one of the passengers to play a game with him. If he loses the game, he will release all the passengers, otherwis... | ```python
import sys
test_cases = int(input())
for i in range(0,test_cases):
count = input().split()
#print count
count_r = int(count[0])
count_g = int(count[1])
count_b = int(count[2])
k = int(input())
if k is 1:
total = 1
else:
total = 1
if count_r < k:
total = total + count_r
else:
total = t... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Due to the COVID pandemic, there has been an increase in the number of cases if a hospital. The management has decided to clear a large square area for the patients and arrange for beds. But the beds can't be too near to each other.
The area is ... | ```python
res = []
for _ in range(int(input())):
lst = []
flag = 0
n = int(input())
for i in range(n):
lst.append(list(map(int, input().split())))
for i in lst:
for j in range(n-1):
if i[j] == i[j+1] == 1:
res.append("UNSAFE")
flag = 1
break
if flag != 0:
break
for i in range(n-1):
for j... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef had an array A with length N, but some of its elements got lost. Now, each element of this array is either unknown (denoted by -1) or a positive integer not exceeding K.
Chef decided to restore the array A by replacing each unknown element ... | ```python
# cook your dish here
# cook your dish here
MOD = 10 ** 9 + 7
for t in range(int(input())):
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
I, D = [0] * (N + 2), [0] * (N + 2)
for i in range(M):
x, L, R = input().split()
L, R = int(L), int(R)
i... | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef has a binary array in an unsorted manner. Cheffina challenges chef to find the transition point in the sorted (ascending) binary array. Here indexing is starting from 0.
Note: Transition point always exists.
-----Input:-----
- First-line w... | ```python
# cook your dish here
for _ in range(int(input())):
n=int(input())
A=list(map(int,input().split()))
A.sort()
for i in range(len(A)):
if A[i]==1:
print(i)
break
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
You have an array A of size N containing only positive numbers. You have to output the maximum possible value of A[i]%A[j] where 1<=i,j<=N.
-----Input-----
The first line of each test case contains a single integer N denoting the size of the a... | ```python
n = int(input())
a = []
for i in range(n):
a.append(int(input()))
m1 = 0
m2 = 0
for e in a:
if (e > m1):
m2 = m1
m1 = e
elif (e > m2 and e != m1):
m2 = e
ans = 0
for e in a:
temp = m1%e
if (temp>ans):
ans = temp
print(max(m2%m1,ans))
``` | |
open-r1/verifiable-coding-problems-python-10k | Solve the following coding problem using the programming language python:
Chef received a permutation $P_1, P_2, \ldots, P_N$ and also an integer $D$ from his good friend Grux, because Grux was afraid he would forget them somewhere. However, since Grux was just playing with the permutation, it was all shuffled, and Ch... | ```python
import sys
sys.setrecursionlimit(10000000)
def mergeSortInversions(arr):
if len(arr) == 1:
return arr, 0
larr=len(arr)
a = arr[:larr//2]
b = arr[larr//2:]
a, ai = mergeSortInversions(a)
b, bi = mergeSortInversions(b)
c = []
i = 0
j = 0
inversions = 0 + ai + bi
la=len(a)
while i < l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.