_id
stringlengths 2
5
| partition
stringclasses 2
values | text
stringlengths 5
289k
| language
stringclasses 1
value | meta_information
dict | title
stringclasses 1
value |
---|---|---|---|---|---|
d501 | train | class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
pre_op = '+'
stack = [0]
cur_num = 0
digits = '0123456789'
s += '#'
for c in s:
if c == ' ':
continue
if c in digits:
cur_num = cur_num * 10 + int(c)
continue
if pre_op == '-':
cur_num *= -1
elif pre_op == '*':
cur_num *= stack.pop()
elif pre_op == '/':
if cur_num == 0:
return None
pre_num = stack.pop()
flag = 1 if pre_num > 0 else -1
cur_num = abs(pre_num) // cur_num * flag
stack.append(cur_num)
pre_op = c
cur_num = 0
return sum(stack)
| PYTHON | {
"starter_code": "\nclass Solution:\n def calculate(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/basic-calculator-ii/"
} | |
d502 | train | class Solution:
def shortestPalindrome(self, s):
if len(s)<2:
return s
if len(s)==40002:
return s[20000:][::-1]+s
for i in range(len(s)-1,-1,-1):
if s[i]==s[0]:
j=0
while j<(i+1)//2 and s[i-j]==s[j]:
j+=1
if j>=(i+1)//2:
return s[i+1:][::-1]+s | PYTHON | {
"starter_code": "\nclass Solution:\n def shortestPalindrome(self, s: str) -> str:\n ",
"url": "https://leetcode.com/problems/shortest-palindrome/"
} | |
d503 | train | class Solution(object):
def minMalwareSpread(self, graph, initial):
# 1. Color each component.
# colors[node] = the color of this node.
N = len(graph)
colors = {}
c = 0
def dfs(node, color):
colors[node] = color
for nei, adj in enumerate(graph[node]):
if adj and nei not in colors:
dfs(nei, color)
for node in range(N):
if node not in colors:
dfs(node, c)
c += 1
# 2. Size of each color.
# size[color] = number of occurrences of this color.
size = collections.Counter(colors.values())
# 3. Find unique colors.
color_count = collections.Counter()
for node in initial:
color_count[colors[node]] += 1
# 4. Answer
ans = float('inf')
for x in initial:
c = colors[x]
if color_count[c] == 1:
if ans == float('inf'):
ans = x
elif size[c] > size[colors[ans]]:
ans = x
elif size[c] == size[colors[ans]] and x < ans:
ans = x
return ans if ans < float('inf') else min(initial) | PYTHON | {
"starter_code": "\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/minimize-malware-spread/"
} | |
d504 | train | class Solution:
def arrangeWords(self, text: str) -> str:
p=text.split(' ')
final=''
j=sorted(p,key=len)
temp=' '.join(j)
if temp[0]>='a' and temp[0]<='z':
s=temp[0].swapcase()
final=final+s[0]
else:
final=final+temp[0]
for i in range(1,len(temp)):
if temp[i]>='A' and temp[i]<='Z':
s=temp[i].swapcase()
final=final+s[0]
else:
final=final+temp[i]
return final
| PYTHON | {
"starter_code": "\nclass Solution:\n def arrangeWords(self, text: str) -> str:\n ",
"url": "https://leetcode.com/problems/rearrange-words-in-a-sentence/"
} | |
d505 | train | class Solution:
def reverseParentheses(self, s: str) -> str:
stack = []
curr = ''
for c in s:
if c=='(':
stack.append(curr)
curr = ''
stack.append('(')
elif c==')':
stack.append(curr)
curr = ''
aux = ''
while stack and stack[-1]!='(':
aux=stack.pop()+aux
stack.pop()
stack.append(aux[::-1])
else:
curr+=c
if curr:
stack.append(curr)
return ''.join(stack) | PYTHON | {
"starter_code": "\nclass Solution:\n def reverseParentheses(self, s: str) -> str:\n ",
"url": "https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/"
} | |
d506 | train | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
if not s: return s
l=0
r=0
res=''
for i,c in enumerate(s):
if c=='(':
l+=1
if c==')':
if l==r:
continue
else:
r+=1
res+=c
s=res
l=0
r=0
res=''
for i in range(len(s)-1,-1,-1):
c=s[i]
if c==')':
r+=1
if c=='(':
if l==r:
continue
else:
l+=1
res=c+res
return res | PYTHON | {
"starter_code": "\nclass Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n ",
"url": "https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/"
} | |
d507 | train | class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
base = "0123456789"
plus = "+"
minus = "-"
sum = 0
flag = 1
bit = 0
INT_MAX = 2147483647
INT_MIN = -2147483648
if not str:
return 0
if len(str) == 0:
return 0
for letter in str.strip():
if letter in plus:
if bit == 0:
bit = 1
continue
else:
break
elif letter in minus:
if bit == 0:
bit = 1
flag = -1
continue
else:
break
elif letter not in base:
break;
else:
sum *= 10
sum += int(letter)
sum *= flag
if(sum > INT_MAX):
return INT_MAX
if(sum < INT_MIN):
return INT_MIN
return sum
| PYTHON | {
"starter_code": "\nclass Solution:\n def myAtoi(self, s: str) -> int:\n ",
"url": "https://leetcode.com/problems/string-to-integer-atoi/"
} | |
d508 | train | class Solution:
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.singleNonDuplicateUtil(nums, 0, len(nums)-1)
def singleNonDuplicateUtil(self, nums, l, r):
if l < r:
mid = int((l + r) * 0.5)
if mid-1>=0 and nums[mid-1]!=nums[mid]:
mid=mid-1
if (mid - l + 1) % 2 == 0:
l = mid + 1
else:
r = mid
return self.singleNonDuplicateUtil(nums, l, r)
else:
return nums[l] | PYTHON | {
"starter_code": "\nclass Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n ",
"url": "https://leetcode.com/problems/single-element-in-a-sorted-array/"
} | |
d509 | train | from heapq import heapify, heappush, heappop
import sys
input = sys.stdin.readline
def solve():
N, Q = list(map(int, input().split()))
events = []
for i in range(N):
S, T, X = list(map(int, input().split()))
events.append((S-X-0.5, 1, X))
events.append((T-X-0.5, 0, X))
for i in range(Q):
D = int(input())
events.append((D, 2, i))
events.sort()
anss = [-1] * Q
PQ = []
isClosed = dict()
for tm, tp, x in events:
if tp == 0:
isClosed[x] = 0
elif tp == 1:
isClosed[x] = 1
heappush(PQ, x)
else:
while PQ:
if isClosed[PQ[0]] == 1:
anss[x] = PQ[0]
break
heappop(PQ)
print(('\n'.join(map(str, anss))))
solve()
| PYTHON | {
"starter_code": "",
"url": "https://atcoder.jp/contests/abc128/tasks/abc128_e"
} | |
d510 | train | import sys
sys.setrecursionlimit(10**6)
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n, m = map(int, input().split())
ans = [-1]*n
uf = UnionFind(n)
g = [[] for i in range(n)]
for i in range(m):
u, v, c = map(int, input().split())
if not uf.same(u-1, v-1):
uf.union(u-1, v-1)
g[u-1].append((v-1, c))
g[v-1].append((u-1, c))
def dfs(i):
for to, c in g[i]:
if ans[to]==-1:
if ans[i] == c:
if c == 1:
ans[to] = c+1
else:
ans[to] = c-1
else:
ans[to] = c
dfs(to)
ans = [-1]*n
ans[0] = 1
dfs(0)
if -1 in ans:
print('No')
return
ans = [a for a in ans]
print(*ans, sep='\n')
| PYTHON | {
"starter_code": "",
"url": "https://atcoder.jp/contests/arc108/tasks/arc108_c"
} | |
d511 | train | 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 x == '1':
y, z = int(y) - 1, ord(z) - 97
p = bisect_left(dic[s[y]], y)
dic[s[y]].pop(p)
dic[z].insert(bisect_left(dic[z], y), y)
s[y] = z
else:
res = 0
y, z = int(y) - 1, int(z) - 1
for i in range(26):
p = dic[i][bisect_left(dic[i], y)]
if p <= z:
res += 1
print(res) | PYTHON | {
"starter_code": "",
"url": "https://atcoder.jp/contests/abc157/tasks/abc157_e"
} | |
d512 | train | 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=" ")
| PYTHON | {
"starter_code": "",
"url": "https://atcoder.jp/contests/abc171/tasks/abc171_e"
} | |
d513 | train | 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 range(18) :
if 2 ** K >= N :
break
# dfs
parent = [[-1] * N for _ in range(K)]
rank = [-1 for _ in range(N)]
rank[0] = 0
queue = [0]
while queue :
cur = queue.pop()
for nex, _, _ in path[cur] :
if rank[nex] < 0 :
queue.append(nex)
parent[0][nex] = cur
rank[nex] = rank[cur] + 1
# doubling
for i in range(1, K) :
for j in range(N) :
if parent[i-1][j] > 0 :
parent[i][j] = parent[i-1][parent[i-1][j]]
# lca
def lca(a, b) :
if rank[a] > rank[b] :
a, b = b, a
diff = rank[b] - rank[a]
i = 0
while diff > 0 :
if diff & 1 :
b = parent[i][b]
diff >>= 1
i += 1
if a == b :
return a
for i in range(K-1, -1, -1) :
if parent[i][a] != parent[i][b] :
a = parent[i][a]
b = parent[i][b]
return parent[0][a]
# Queryの先読み
schedule = [[] for _ in range(N)]
for i in range(Q) :
x, y, u, v = map(int, input().split())
x, u, v = x-1, u-1, v-1
l = lca(u, v)
schedule[u].append((i, 1, x, y))
schedule[v].append((i, 1, x, y))
schedule[l].append((i, -2, x, y))
ret = [0] * Q
C = [0] * (N-1)
D = [0] * (N-1)
def dfs(cur, pre, tot) :
for i, t, c, d in schedule[cur] :
ret[i] += t * (tot - D[c] + C[c] * d)
for nex, c, d in path[cur] :
if nex == pre :
continue
C[c] += 1
D[c] += d
dfs(nex, cur, tot + d)
C[c] -= 1
D[c] -= d
dfs(0, -1, 0)
for i in range(Q) :
print(ret[i]) | PYTHON | {
"starter_code": "",
"url": "https://atcoder.jp/contests/abc133/tasks/abc133_f"
} | |
d514 | train | import bisect
import sys
sys.setrecursionlimit(10**7)
def dfs(v):
pos=bisect.bisect_left(dp,arr[v])
changes.append((pos,dp[pos]))
dp[pos]=arr[v]
ans[v]=bisect.bisect_left(dp,10**18)
for u in g[v]:
if checked[u]==0:
checked[u]=1
dfs(u)
pos,val=changes.pop()
dp[pos]=val
n=int(input())
arr=[0]+list(map(int,input().split()))
g=[[] for _ in range(n+1)]
for _ in range(n-1):
a,b=map(int,input().split())
g[a].append(b)
g[b].append(a)
ans=[0]*(n+1)
checked=[0]*(n+1)
checked[1]=1
dp=[10**18 for _ in range(n+1)]
changes=[]
dfs(1)
for i in range(1,n+1):
print(ans[i]) | PYTHON | {
"starter_code": "",
"url": "https://atcoder.jp/contests/abc165/tasks/abc165_f"
} | |
d515 | train | m = int(input())
n = int(input())
print(m-n) if m>n else print(m+n) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/DIFFSUM"
} | |
d516 | train | # cook your dish here
def modular_pow(base, exponent, modulus):
result = 1
while exponent > 0:
if(exponent %2 == 1):
result = (result * base) % modulus
exponent = exponent//2
base = (base * base)%modulus
return result
def passesMillerRabinTest(n, a):
s = 0
d = n-1
while(d%2 == 0):
s += 1
d >>= 1
x = modular_pow(a, d, n)
if(x == 1 or x == n-1):
return True
for ss in range(s - 1):
x = (x*x)%n
if(x == 1):
return False
if(x == n-1):
return True
return False
primeList = (2, 3,5,7,11,13,17,19, 23,29, 31,37)
def isPrime(n):
for p in primeList:
if n%p == 0:
return n == p
for p in primeList:
if passesMillerRabinTest(n, p) == False:
return False
return True
t = int(input())
for tt in range(t):
n = int(input())
if(n == 2):
print(2)
continue
if n%2 == 0:
n -= 1
while True:
if(isPrime(n)):
print(n)
break
n -= 2
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/WITMATH"
} | |
d517 | train | # cook your dish here
def count(k,n,m):
sum1=(m*(m+1))//2
sum2=(m*(m-1))//2
ct=0
for i in range(n):
for j in range(n):
if i<j and k[i]>k[j]:
ct+=sum1
elif j<i and k[i]>k[j]:
ct+=sum2
return ct
test=int(input())
for _ in range(test):
n,m=map(int,input().split())
k=list(map(int,input().split()))
print(count(k,n,m))
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/INVYCNT"
} | |
d518 | train | # cook your dish here
def offset(l, flag):
x = 0
# print(l)
for i in range(1, len(l)):
temp = []
for j in range(i):
v = getbig(l[i], l[j], fs)
if v > 1:
temp.append(v)
if flag:
x += 2**v - 2
else:
x -= 2**v - 2
x += offset(temp, not flag)
return x
def getbig(v1, v2, factors):
x = 1
for f in factors:
while v1%f == 0 and v2%f == 0:
v1//=f
v2//=f
x*=f
return x
def prime_factors(n):
i = 2
factors = set()
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.add(i)
if n > 1:
factors.add(n)
return factors
n,m = map(int, input().split())
if n == 1:
print(1)
else:
fs = prime_factors(n)
fs.discard(n)
ans = 2**n-2
temp = []
for v in fs:
v = n//v
temp.append(v)
ans -= 2**v - 2
# print(ans)
ans += offset(temp, True)
# print(fs)
print(ans%m) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/INOIPRAC/problems/INOI1502"
} | |
d519 | train | for _ in range(int(input())):
N=int(input())
if N%2==0:
print(N//2+1)
else:
print((N-1)//2+1) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/PBK12020/problems/ITGUY20"
} | |
d520 | train | # cook your dish here
import bisect
n, k1, *l = map(int, input().split())
v_l, b_l = l[:n], l[n:]
b_inv = {key:[] for key in range(2*k1)}
for i in range(n):
b_l[i] -= 1
b_inv[b_l[i]].append(i)
dp = [[0 for _ in range(n)] for _ in range(n)]
for k in range(1, n):
for j in range(n-2, -1, -1):
if j+k >= n:
continue
dp[j][j+k] = max(dp[j][j+k], dp[j][j+k-1])
if b_l[j+k] >= k1:
left = bisect.bisect_right(b_inv[b_l[j+k]-k1], j)
if b_l[j+k] >= k1:
for i in b_inv[b_l[j+k]-k1][left:]:
if i > j+k:
break
if i > j:
dp[j][j+k] = max(dp[j][j+k], dp[j][i-1]+dp[i][j+k])
if b_l[j+k]-k1 == b_l[j]:
if j+k-1 < n:
dp[j][j+k] = max(dp[j][j+k], v_l[j+k]+v_l[j]+dp[j+1][j+k-1])
else:
dp[j][j+k] = max(dp[j][j+k], v_l[j+k]+v_l[j])
print(dp[0][-1]) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/INOIPRAC/problems/INOI1602"
} | |
d521 | train | # cook your dish here
t=int(input())
for i in range(t):
n=input()
if(n=='b' or n=='B'):
print('BattleShip')
elif(n=='c' or n=='C'):
print('Cruiser')
elif(n=='d' or n=='D'):
print('Destroyer')
else:
print('Frigate') | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/FLOW010"
} | |
d522 | train | from math import *
from collections import *
import sys
input=sys.stdin.readline
t=int(input())
while(t):
t-=1
n=int(input())
a=list(map(int,input().split()))
p,q=map(int,input().split())
s=0
a.sort()
for i in range(n//2):
x=a[i]
x1=a[n-i-1]
if(x==p or x1==p):
s1=abs(x-x1)
s2=q
s+=abs(atan2(s1,s2))
elif(x<p and x1>p):
s1=abs(p-x)
ex=atan2(s1,q)
s1=abs(p-x1)
ex1=atan2(s1,q)
ex+=ex1
s+=abs(ex)
else:
if(p<x):
s1=abs(p-x)
ex=atan2(s1,q)
s1=abs(p-x1)
ex1=atan2(s1,q)
ex=ex1-ex
s+=abs(ex)
else:
s1=abs(p-x)
ex=atan2(s1,q)
s1=abs(p-x1)
ex1=atan2(s1,q)
ex=ex-ex1
s+=abs(ex)
print(s)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CAPTBIRD"
} | |
d523 | train | 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())
co=0
ans=0
for i in range(1,n):
ans+=n//i
if n%i==0:
ans-=1
print(ans)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/SPRT2020/problems/GOATRIP"
} | |
d524 | train | f = 5003*[0]
modn = 1000000007
def qPow(a, b):
nonlocal modn
res = 1
while b > 0:
if (b & 1) == 1:
res = res * a % modn
a = a * a % modn
b = b >> 1
return res
def getF():
nonlocal f
f[0] = 1
for i in range(1, 5001):
f[i] = f[i-1] * i
def __starting_point():
getF()
T = int(input())
while T > 0:
T = T - 1
n, k = list(map(int,input().split()))
lis = list(map(int, input().split()))
lis = sorted(lis)
res = 1
for i in range(n):
zhi = f[n-1]//f[k-1]//f[n-k]
if i >= k-1:
zhi = zhi - f[i]//f[k-1]//f[i+1-k]
if n-i-1 >= k-1:
zhi = zhi - f[n-i-1]//f[k-1]//f[n-i-k]
zhi = zhi % (modn-1)
# print(zhi)
res = res * qPow(lis[i], zhi) % modn
print(res)
__starting_point() | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/NMNMX"
} | |
d525 | train | arr = list(input())
n = len(arr)
ans = list()
#for i in arr:
#ans.append(ord(i)-96)
li = ['b','d','f','h','j','l','n','p','r','t','v','x','z']
s = set(arr)
temp = s.intersection(li)
for _ in range(int(input())):
x,y = list(map(int,input().split()))
li = list(temp)
#s = set()
c=0
for i in range(x-1,y):
if arr[i] in li:
c+=1
li.remove(arr[i])
if len(li)==0:
break
print(c)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/STRG2020/problems/TOTCARS"
} | |
d526 | train | # cook your dish here
for t in range(int(input())):
a,b,c=map(int,input().split())
p=(c//a)*a+b
if p<=c:
print(p)
else:
print(((c//a)-1)*a+b) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CCOD2020/problems/MOTU001"
} | |
d527 | train | #include<sdg.h>
for _ in range(int(input())):
s=input()
n=len(s)
if n==1:
if s[0].isalpha(): print("-32")
else: print(0)
else:
num,ch=0,0
p,q=0,0
c=1
x=s[0]
ans=""
for i in range(1,n):
if s[i-1]==s[i]:
c+=1
if i==n-1:
ans+=s[i-1]
ch+=1
if c>1:
ans+=str(c)
num+=1
c=1
else:
ans+=s[i-1]
ch+=1
if c>1:
ans+=str(c)
num+=1
c=1
if i==n-1:
ans+=s[i]
ch+=1
#print(ans,num,ch)
sol=(n*8)-((num*32)+(ch*8))
print(sol) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/COPT2020/problems/AUREOLE"
} | |
d528 | train | 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) - get_sum(left - 1, bi_tree)
return ans
def solve(x):
s = set()
res = 1
i = 2
while (i * i <= x):
count = 0
while (x % i == 0):
x = x // i
count += 1
if (count % 2):
s.add(i)
i += 1
if (x > 0):
s.add(x)
return s
n = int(input())
l = [0] + [int(i) for i in input().split()]
bit = [[0 for i in range(n + 1)] for i in range(101)]
for i in range(1, n + 1):
s = solve(l[i])
for j in s:
update(i, 1, bit[j])
q = int(input())
for i in range(q):
k, a, b = [int(i) for i in input().split()]
if (k == 1):
f = 1
for i in range(2, 100):
res = get_range_sum(a, b, bit[i])
if (res % 2):
f = 0
break
if (f):
print("YES")
else:
print("NO")
else:
s = solve(b)
for j in s:
update(a, 1, bit[j]) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/STRT2020/problems/RANPRO"
} | |
d529 | train | # cook your dish here
from sys import stdin,stdout
from collections import deque,defaultdict
from math import ceil,floor,inf,sqrt,factorial,gcd,log
from copy import deepcopy
ii1=lambda:int(stdin.readline().strip())
is1=lambda:stdin.readline().strip()
iia=lambda:list(map(int,stdin.readline().strip().split()))
isa=lambda:stdin.readline().strip().split()
mod=1000000007
for _ in range(ii1()):
n,l=iia()
if n==1:
print(l)
elif n==2:
print(int(log2(10))+1)
else:
print(ceil(l/(n+1)))
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/COPT2020/problems/ANTHUNT"
} | |
d530 | train | import math
for _ in range(int(input())):
n=int(input())
s=int(math.sqrt(n))
ans=0
for i in range(1,s+1):
ans+=(n//i)
ans=ans*2-(s*s)
g=math.gcd(n*n,ans)
print(str(ans//g)+"/"+str(n*n//g)) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/COOLGUYS"
} | |
d531 | train | # cook your dish here
# cook your dish here
import numpy as np
import sys
def findSeq(n, s, k, m, M):
midInd = n // 2
seqs = []
for ind in range(midInd + 2, midInd - 3, -1):
if ind >= n or ind < 0:
continue
seq = genBestSeq(n, ind, m, M, s)
if seq is not -1 and testSeq(k, seq):
seqs.append(list(seq))
if len(seqs) == 0:
return -1
return min(seqs)
#def findSeq(n, s, k, m, M):
# midInd = n // 2
# if k <= midInd: #and (n % 2 == 1 or s < m * midInd + M * (n - midInd)):
# return genBestSeq(n, midInd + 1, m, M, s)
# elif k > midInd + 1 and n % 2 == 1:
# return -1
# return genBestSeq(n, midInd, m, M, s)
def genBestSeq(n, diffInd, m, M, s):
#inc = M - m - 1
arr = np.full((n,), m)
arr[diffInd:] += 1
#remainder = s - np.sum(arr)
#if remainder < 0:
# return -1
#nFull, remainder = divmod(remainder, inc)
#if nFull > n or (nFull == n and remainder > 0):
# return -1
#addingInd = n - nFull -1
#arr[addingInd + 1:] += inc
#arr[addingInd] += remainder
#return arr
s = s - np.sum(arr)
if s < 0:
return -1
inc = M - m - 1
ind = n - 1
while (ind >= 0):
z = min(inc, s)
arr[ind] += z
s -= z
ind -= 1
if s != 0:
return -1
return arr
def testSeq(k, seq):
seq = sorted(seq)
n = len(seq)
if n % 2 == 1:
median = seq[n // 2]
else:
median = (seq[n // 2 - 1] + seq[n // 2]) / 2
seq.pop(n % k)
seq.pop(k - 1)
return (median != seq[(n - 2) // 2])
def __starting_point():
nCases = int(input())
answers = []
#ks = []
for i in range(nCases):
#nums = [int(val) for val in input().split()]
#ks.append(nums[2])
#answers.append(findSeq(*nums))
answers.append(findSeq(*(int(val) for val in input().split())))
ans = answers[-1]
if not isinstance(ans, int):
print(*ans, sep=' ')
else:
print(ans)
#for i, ans in enumerate(answers):
#for ans in answers:
# if isinstance(ans, np.ndarray):
# print(*ans, sep=' ')
# else:
# print(ans)
__starting_point() | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/HACKFU"
} | |
d532 | train | # cook your dish here
n=int(input())
counts=dict()
z=0
upper=None
for i in range(0,n):
a,h= [int(num) for num in input().split()]
counts[a]=h
for key,count in counts.items():
c=0
x=key-count
y=key+count
c1=0
c2=0
for j in counts.keys():
if j==key:
continue
else:
if x<=j<=key:
c1=0
break
else:
c1=1
for j in counts.keys():
if j==key:
continue
else:
if key<=j<=y:
c2=0
break
else:
c2=1
if c2==0 and c1==1:
if upper is None:
z=z+c1
upper=key
else:
if x>=upper:
z=z+c1
upper=key
else:
z=z+c2
upper=key
elif c2==1 and c1==0:
if upper is None:
z=z+c2
upper=y
else:
if upper<=key:
z=z+c2
upper=y
else:
z=z+c1
upper=y
elif c2==1 and c1==1:
if upper is None:
z=z+c1
upper=key
else:
if x>=upper:
z=z+c1
upper=key
else:
if upper<=key:
z=z+c2
upper=y
else:
z=z+0
upper=y
else:
z=z+0
upper=key
if len(counts)==1:
print(1)
else:
print(z) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/COTH2020/problems/STKGAME"
} | |
d533 | train | n=int(input())
modulo=15746
num=[1,1]
for i in range(2,n+1):
num.append((num[i-1]+num[i-2])%modulo)
print(num[n]) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/IARCSJUD/problems/TILES01"
} | |
d534 | train | # cook your dish here
for _ in range(int(input())):
m,n=list(map(int,input().split()))
a=[int(i) for i in input().split()]
l=-1
for i in range(n-1,-1,-1):
if a[i]==m:
l=i
break
f=-1
for i in range(0,n):
if a[i]==m:
f=i
break
print(l-f)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/PBK32020/problems/ITGUY33"
} | |
d535 | train | def detect_triangle(adj):
for x in range(len(adj)):
for y in adj[x]:
if not set(adj[x]).isdisjoint(adj[y]):
return True
for _ in range(int(input())):
n,m=list(map(int,input().split()))
graph=[[] for i in range(n)]
for i in range(m):
u,v=list(map(int,input().split()))
graph[u-1].append(v-1)
graph[v-1].append(u-1)
h=[]
for i in range(len(graph)):
h.append(len(graph[i]))
h1=max(h)
if h1>=3:
print(h1)
continue
if detect_triangle(graph):
print(3)
continue
print(h1) # cook your dish here
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/ANTMAT"
} | |
d536 | train | def C(n):
return n*(n-1)//2
def sol():
equal, mini = False, min(N,M)
total_ways = 2*C(N * M)
if N==M:
equal = True
ways = 0
if not equal:
ways = (N*C(M)+M*C(N))
diag = 0
for i in range(2, mini+1):
diag += 2*C(i)
for i in range(mini+1,max(N,M)):
diag += C(mini)
diag *= 2
ways += diag
ways *= 2
else:
ways = (N*C(M)+M*C(N))
diag = 0
for i in range(2, mini):
diag += 2*C(i)
diag += C(mini)
diag *= 2
ways += diag
ways *=2
safe = total_ways - ways
l, r, t, d = Y-1, M-Y, X-1, N-X
safe_add, to_remove = 0, 0
for i in range(1,N+1):
for j in range(1, M+1):
if i==X or j==Y or abs(i-X)==abs(j-Y):
continue
else:
to_remove += 1
if l>0 and r>0 and t>0 and d>0:
dtl, dtr, dbl, dbr = min(l,t), min(r,t), min(l,d), min(r,d)
safe_add += dtl*dbr*2 + dtr*dbl*2
safe_add += t*d*2
safe_add += l*r*2
elif l>0 and r>0:
safe_add += l*r*2
elif t>0 and d>0:
safe_add += t*d*2
safe += safe_add - to_remove*2
return safe
T = int(input())
for _ in range(T):
N, M, X, Y = [int(x) for x in input().split()]
print(sol()) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CHQUEENS"
} | |
d537 | train | # cook your dish here
t=int(input())
for i in range(t):
(n,k)=tuple(map(int,input().split()))
print(k//n) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CYBV"
} | |
d538 | train | n,k=[int(x) for x in input().split()]
a=[int(x) for x in input().split()]
ans=0
for i in range(n-1):
for j in range(i+1,n):
if(abs(a[i]-a[j])>=k):
ans+=1
print(ans)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/ZCOPRAC/problems/ZCO15002"
} | |
d539 | train | # cook your dish here
n=int(input())
for i in range(n):
S, SG, FG, D, T = map(int, input().split())
speed = (D*180)/T + S
if abs(SG-speed) == abs(FG-speed):
print('DRAW')
elif abs(SG-speed) > abs(FG-speed):
print('FATHER')
else:
print('SEBI') | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/SEBIHWY"
} | |
d540 | train | # By Prathmesh Maurya
t=eval(input())
while(t!=0):
t-=1
n=eval(input())
if n%2 == 0:
print(n*4)
elif n%4==3:
print(n)
else:
print(n*2)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/LOCAUG16/problems/BSQUARE"
} | |
d541 | train |
for __ in range(int(input())):
n,m=map(int,input().split())
arr=list(map(int,input().split()))
s=set(arr)
mex=-1
ele=1
for i in range(1,n+1):
if i not in s:
mex = i
break
if m>mex:
print(-1)
elif m==mex:
print(n)
else:
c=arr.count(m)
print(n-c)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/MAXMEX"
} | |
d542 | train | for i in range(int(input())):
n = int(input())
c = list(map(int, input().split()))
d = {}
d[0] = -1
parity = 0
ans = 0
for i in range(n):
parity ^= 1 << (c[i]-1)
for t in range(30):
x = parity^(1<<t)
if(x in d.keys()):
ans = max(ans, i - d[x])
if parity not in d.keys():
d[parity] = i
print(ans//2) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/LEQEX"
} | |
d543 | train | # cook your dish here
import sys
import math
def main(grid):
ans=0
for i in range(len(grid)):
for j in range(len(grid[0])):
first_point=grid[i][j]
for k in range(j+1,len(grid[0])):
second_point=grid[i][k]
if first_point==second_point:
dist=k-j
if i+dist<len(grid):
thrid_point=grid[i+dist][j]
fourth_point=grid[i+dist][k]
if second_point==thrid_point and second_point==fourth_point:
ans+=1
return ans
test=int(input())
for _ in range(test):
n,m=input().split()
n=int(n)
arr=[]
for b in range(n):
arr.append(list(input()))
print(main(arr)) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/GARDENSQ"
} | |
d544 | train | # cook your dish here
for _ in range(int(input())):
tr=int(input())
trl=list(map(int,input().split()))
dr = int(input())
drl = list(map(int, input().split()))
ts = int(input())
tsl = list(map(int, input().split()))
ds = int(input())
dsl = list(map(int, input().split()))
for item in tsl:
if item in trl:
res=1
continue
else:
res=0
break
for item1 in dsl:
if item1 in drl:
res1=1
continue
else:
res1=0
break
if res==1 and res1==1:
print("yes")
else:
print("no")
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/TRUEDARE"
} | |
d545 | train | # cook your dish here
def decode(L,S):
str_2=""
lst=[]
for i in range(L//4):
str_1 = "abcdefghijklmnop"
S_1=S[(i*4):(4*(i+1))]
for j in range(4):
if(S_1[j]=="1"):
str_1=str_1[len(str_1)//2:len(str_1)]
else:
str_1 = str_1[0:len(str_1) // 2]
str_2=str_2+str_1
print(str_2)
T=int(input())
for i in range(T):
L=int(input())
S=input()
decode(L,S)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/DECODEIT"
} | |
d546 | train | for _ in range(int(input())):
n,k = list(map(int,input().split()))
array = []
tot = []
for _ in range(n):
temp = list(map(int,input().split()))
aa = temp[0]
del(temp[0])
temp.sort()
temp.insert(0,aa)
array.append(temp)
dic = {}
array.sort(reverse=True)
for i in array:
del(i[0])
for i in range(1,k+1):
dic[i] = False
count = 0
for i in array:
count += 1
# print(count,tot)
for j in i:
if(dic[j]==True):
pass
else:
tot.append(j)
dic[j]=True
if(len(tot)==k):
break
if(len(tot)!=k):
print("sad")
elif(count!=n):
print("some")
else:
print("all") | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/DISHLIFE"
} | |
d547 | train | # cook your dish here
test=int(input())
for _ in range(test):
n=int(input())
n=list(bin(n))
ans=n.count('1')
print(ans-1) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/SMTC2020/problems/BBALLS"
} | |
d548 | train | import sys
t = int(input())
def g(a,b):
if (a > b):
tmp = a
a = b
b = tmp
if (b == a):
return 0
if (b % a == 0):
return int(b/a)-1
r = g(b%a,a)
q = int(b/a)
if (r >= q):
return q-1
else:
return q
def mex(x):
n = len(list(x.keys()))
for i in range(n):
if (i not in x):
return i
return i
def g2(a,b):
if (a == b):
return 0
if (a > b):
tmp = a
a = b
b = tmp
if (b % a == 0):
return int(b/a)-1
q = int(b/a)
x = {}
r = b % a
for i in range(q):
x[g2(r+i*a,a)] = True
return mex(x)
#print(str(g(6,33))+" "+str(g2(6,33)))
while (t):
n = int(input())
x = 0
while (n):
line = input().split()
a = int(line[0])
b = int(line[1])
x ^= g(a,b)
n -= 1
if (x):
sys.stdout.write("YES\n")
else:
sys.stdout.write("NO\n")
#print(str(g(a,b)) + " " + str(g2(a,b)))
t -= 1 | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/GAMEAAM"
} | |
d549 | train | # cook your dish here
for i in range(int(input())):
n=int(input())
p=1
l=n-1
for j in range(n):
for k in range(l):
print(" ",end='')
for k in range(p):
print("*",end='')
print()
for k in range(l):
print(" ",end='')
for k in range(p):
print("*",end='')
print()
p+=2
l-=1
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/PTRN2020/problems/ITGUY42"
} | |
d550 | train | import sys
num=int(sys.stdin.readline())
s=sys.stdin.readline().split()
sky=list(map(int,s))
sky.reverse()
cuts=0
change=0
t=False
i=1
while i<len(sky):
if sky[i]<=sky[i-1]:
for j in range(i-1,-1,-1):
if sky[j]<=sky[i]-(i-j):
break
else:
change+=sky[j]-(sky[i]-(i-j))
if change>=sky[i]:
change=sky[i]
t=True
break
cuts+=change
if t:
del sky[i]
t=False
i-=1
else:
for j in range(i-1,-1,-1):
if sky[j]<sky[i]-(i-j):
break
else:
sky[j]=sky[i]-(i-j)
i+=1
change=0
print(cuts) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/IGNS2012/problems/IG04"
} | |
d551 | train |
def main():
t = int(input())
while (t):
m, n = map(int, input().split())
a , b= bin(m)[2:],bin(n)[2:]
#print(a,b)
max = m^n
if len(a)>len(b):
diff =len(a)-len(b)
b= ("0"*diff)+b
#print(b)
elif len(a)<len(b):
diff =len(b)-len(a)
a= ("0"*diff)+a
#print(a)
ll = len(b)
count= 0
for i in range(ll-1):
s= b[ll-1] + b
s= s[:ll]
tt= m^ int(s,2)
#print(m,s,tt)
if tt>max:
max =tt
count= i+1
b=s
print(count,max)
t-=1
def __starting_point():
main()
__starting_point() | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CHPTRS01/problems/GAMENUM"
} | |
d552 | train | t = int(input())
for _ in range(t):
s = [x for x in input()]
freq = {}
for i in s:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
flag = 0
for keys, values in freq.items():
if(values >= 2):
flag = 1
break
if(flag == 0):
print("no")
else:
print("yes") | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/LIKECS01"
} | |
d553 | train | def main():
T = int(input())
for t in range(T):
N,K = map(int, input().split())
W = list(map(int, input().split()))
W.sort()
if 2*K > N:
K = N - K
kid = sum(W[:K])
dad = sum(W[K:])
diff = dad - kid
print(diff)
def __starting_point():
main()
__starting_point() | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/MAXDIFF"
} | |
d554 | train | def eq_solve(v0, v1, u0, u1):
den = u0 - v0
num = u1 - v1
if den != 0:
return num / den
return 1
def solve(p, q, r, a, b, c, rs):
if p == a and q == b and r == c:
return rs
if rs >= 2:
return 3
res = 3
adds = [a - p, b - q, c - r]
muls = []
if p != 0:
muls.append(a / p)
if q != 0:
muls.append(b / q)
if r != 0:
muls.append(c / r)
muls.append(eq_solve(p, a, q, b))
muls.append(eq_solve(p, a, r, c))
muls.append(eq_solve(q, b, r, c))
msks = 2 ** 3
for msk in range(msks):
for add in adds:
np = p
nq = q
nr = r
if (msk & 1) > 0:
np += add
if (msk & 2) > 0:
nq += add
if (msk & 4) > 0:
nr += add
res = min(res, solve(np, nq, nr, a, b, c, rs + 1))
for mul in muls:
np = p
nq = q
nr = r
if (msk & 1) > 0:
np *= mul
if (msk & 2) > 0:
nq *= mul
if (msk & 4) > 0:
nr *= mul
res = min(res, solve(np, nq, nr, a, b, c, rs + 1))
return res
t = int(input())
while t > 0:
p, q, r = map(int, input().split())
a, b, c = map(int, input().split())
z = solve(p, q, r, a, b, c, 0)
print(z)
t -= 1 | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/TTUPLE"
} | |
d555 | train | from math import log10
from decimal import Decimal
def solve(n,k):
mod=10**k
x=Decimal(n)
y=x*(x.log10())%1
p=str(pow(10,y))
c=0
first=''
for v in p:
if c==k:
break
if v==".":
continue
first+=v
c+=1
last=str(pow(n,n,mod)).zfill(k)
return (first,last)
queries=[]
for _ in range(int(input())):
n,k=list(map(int,input().split( )))
queries.append((n,k))
for n,k in queries:
print("%s %s"%(solve(n,k)))
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/A4"
} | |
d556 | train | t = eval(input())
for i in range(t):
n = eval(input())
a = list(map(int, input().split()))
cnt = 2
cnt1 = 2
ll = len(a)
if ll < 3:
cnt1 = ll
else:
for j in range(2,ll):
if a[j-1] + a[j-2] == a[j]:
cnt += 1
cnt1 = max(cnt1, cnt)
else:
cnt1 = max(cnt1, cnt)
cnt = 2
print(cnt1) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/LOCAPR16/problems/ACDEMY"
} | |
d557 | train |
z = int(input())
i = 0
while i < z:
n = int(input())
p = int(n**(0.5))
if p*(p+1) < n:
p += 1
# print("P", p)
x, y = 0, 0
q = 0
flag = True
if p*(p+1) == n:
# print("Even steps, nice")
q = p
else:
# remaining steps
q = p-1
flag = False
if q%2 :
# odd
x -= ((q+1)//2)
y += ((q+1)//2)
else :
x += (q//2)
y -= (q//2)
if flag:
print(x, y)
else:
# remaining steps
l = q*(q+1)
t = p*(p+1)
diff = t-l
# print(x, y)
if x < 0:
# left
if n-l >= diff//2:
y *= (-1)
l += (diff//2)
x += (n-l)
else :
y -= (n-l)
else:
# right
if n-l >= diff//2:
y *= (-1)
y += 1
l += (diff//2)
x -= (n-l)
else :
y += (n-l)
# print("Remaining steps: ", n-l)
print(x, y)
i+=1 | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/DECO2020/problems/DECOSNKE"
} | |
d558 | train | # cook your dish here
for t in range(int(input())):
n,m=[int(x)for x in input().rstrip().split()]
s=[]
for p in range(n):
s.append(10)
for c in range(m):
i,j,k=[int(x)for x in input().rstrip().split()]
for q in range(i-1,j):
s[q]=s[q]*k
print(sum(s)//n)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CMR12121/problems/ELPF"
} | |
d559 | train | from queue import PriorityQueue
m,n=list(map(int,input().split()))
rr=[]
cc=[]
speed={'S':3,'O':2,'F':1}
visited=set()
dp=[]
def qwerty(cur,x,y,f):
if f==0:
gg=rr[x][1]+y*rr[x][0]
while gg<cur:
gg+=(2*(n-1))*rr[x][0]
return gg-cur+rr[x][0]
elif f==1:
gg=rr[x][1]+(2*(n-1)-y)*rr[x][0]
while gg<cur:
gg+=(2*(n-1))*rr[x][0]
return gg-cur+rr[x][0]
elif f==2:
gg=cc[y][1]+x*cc[y][0]
while gg<cur:
gg+=(2*(m-1))*cc[y][0]
return gg-cur+cc[y][0]
elif f==3:
gg=cc[y][1]+(2*(m-1)-x)*cc[y][0]
while gg<cur:
gg+=(2*(m-1))*cc[y][0]
return gg-cur+cc[y][0]
dirx=[0, 0, 1, -1]
diry=[1, -1, 0, 0]
for i in range(m):
o=[x for x in input().split()]
o[0]=speed[o[0]]
o[1]=int(o[1])
rr.append(o)
for i in range(n):
o=[x for x in input().split()]
o[0]=speed[o[0]]
o[1]=int(o[1])
cc.append(o)
sx,sy,stt,dx,dy=list(map(int,input().split()))
sx-=1
sy-=1
dx-=1
dy-=1
for i in range(m):
dp.append([10**9]*n)
dp[sx][sy]=stt
pq = PriorityQueue()
pq.put((stt, sx, sy))
while not pq.empty():
#print(dp)
(t,cxx,cyy)=pq.get()
if (cxx,cyy) in visited:
continue
visited.add((cxx,cyy))
for i in range(len(dirx)):
nxx=cxx+dirx[i]
nyy=cyy+diry[i]
if nxx>=0 and nxx<m and nyy>=0 and nyy<n and (nxx,nyy) not in visited:
coo=qwerty(dp[cxx][cyy],cxx,cyy,i)
if coo+dp[cxx][cyy]<dp[nxx][nyy]:
dp[nxx][nyy]=coo+dp[cxx][cyy]
pq.put((dp[nxx][nyy],nxx,nyy))
print(dp[dx][dy])
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/IARCSJUD/problems/METRO"
} | |
d560 | train | import math
import copy
try:
import psyco
psyco.full()
except ImportError:
pass
def isSharp(ang):
return ang > math.pi/4 + 0.00001
def unitVector(p2, p1):
d0 = p2[0] - p1[0]
d1 = p2[1] - p1[1]
d = math.sqrt(d0*d0 + d1*d1)
if d != 0:
return [d0/d, d1/d]
return [0, 0]
def compVectors(P):
V = []
for i in range(1,len(P)):
v = unitVector(P[i], P[i-1])
if v[0] == 0 and v[1] == 0:
return None
V.append(v)
return V
def angle(v2, v1):
d = v2[0]*v1[0] + v2[1]*v1[1]
if d > 1:
d = 1
if d < -1:
d = -1
return math.acos(d)
def compAngles(V):
A = []
for i in range(len(V)-1):
A.append(angle(V[i+1], V[i]))
return A
def updateAngles(i, P, V, A):
if i-1 >= 0:
V[i-1] = unitVector(P[i], P[i-1])
if i+1 < len(P):
V[i] = unitVector(P[i+1], P[i])
if i-2 >= 0:
A[i-2] = angle(V[i-1], V[i-2])
if i-1 >= 0 and i+1 < len(P):
A[i-1] = angle(V[i], V[i-1])
if i+2 < len(P):
A[i] = angle(V[i+1], V[i])
def checkMoves(check, P, V, A, filled):
for i in check:
if i < 0 or i >= len(P):
break
x, y = P[i]
for j in range(51):
for k in range(51):
P[i][0] = j
P[i][1] = k
if str(P[i]) in filled:
continue
updateAngles(i, P, V, A)
fixed = True
if i-2 >= 0:
if isSharp(A[i-2]):
fixed = False
if i-1 >= 0 and i-1 < len(A):
if isSharp(A[i-1]):
fixed = False
if i < len(A):
if isSharp(A[i]):
fixed = False
if fixed:
return True
P[i] = [x, y]
updateAngles(i, P, V, A)
return False
def canFix(first, last, P, V, A, filled):
d = last - first
if d > 2:
return False
if d == 2:
check = [first+2]
if d == 1:
check = [first+1, first+2]
if d == 0:
check = [first, first+1, first+2]
if checkMoves(check, P, V, A, filled):
return True
return False
T=int(input())
for i in range(T):
N=int(input())
P=[]
V=[]
filled={}
for i in range(N):
P.append(list(map(int,input().split())))
filled[str(P[i])] = 1
V = compVectors(P)
A = compAngles(V)
blunt = True
first = -1
last = -1
for i in range(len(A)):
if isSharp(A[i]):
blunt = False
last = i
if first < 0:
first = i
if blunt:
print('yes yes')
else:
if canFix(first, last, P, V, A, filled):
print('no yes')
else:
print('no no') | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/TAXITURN"
} | |
d561 | train | # cook your dish here
for i in range(int(input())):
N=int(input())
ALICE=list(map(int,input().split()))
BOB=list(map(int,input().split()))
ALICE[ALICE.index(max(ALICE))]=0
BOB[BOB.index(max(BOB))]=0
if sum(ALICE)<sum(BOB):
print("Alice")
elif sum(BOB)<sum(ALICE):
print("Bob")
else:
print("Draw") | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CO92JUDG"
} | |
d562 | train | def find_combinations(list, sum):
if not list:
if sum == 0:
return [[]]
return []
return find_combinations(list[1:], sum) + \
[[list[0]] + tail for tail in
find_combinations(list[1:], sum - list[0])]
for tc in range(int(input())):
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
a.sort()
if len(find_combinations(a,k))==0:
print("NO")
else:
print("YES")
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CFSN2015/problems/LINSUB"
} | |
d563 | train | # cook your dish here
n,m=map(int,input().split())
L=[]
for i in range(n):
s=input()
L.append(s)
cost=[]
h2=[0]*(m+1)
cost.append(h2)
for i in range(n):
h=[0]
for j in range(m):
if(L[i][j]=='0' and (i+j)%2!=0):
h.append(1)
elif(L[i][j]=='1' and (i+j)%2==0):
h.append(1)
else:
h.append(0)
cost.append(h)
pre=[]
h2=[0]*(m+1)
pre.append(h2)
for i in range(1,n+1):
h=[0]
c=0
for j in range(1,m+1):
c+=cost[i][j]
c2=c
if(i>0):
c2+=pre[i-1][j]
h.append(c2)
pre.append(h)
bs=[0]*((m*n)+10)
for i in range(1,n+1):
for j in range(1,m+1):
for k in range(1,min(m,n)+1):
if(i-k>=0 and j-k>=0):
c=pre[i][j]-pre[i-k][j]-pre[i][j-k]+pre[i-k][j-k]
c=min(c,(k*k)-c)
bs[c]=max(bs[c],k)
mx=bs[0]
for i in range(1,len(bs)):
mx=max(mx,bs[i])
bs[i]=mx
Q=int(input())
q=[int(x) for x in input().split()]
for i in range(0,len(q)):
qr=min(m*n,q[i])
print(bs[qr])
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/SURCHESS"
} | |
d564 | train | # cook your dish here
for i in range(int(input())):
N = int(input())
l = list(map(int, input().split()))
for j in range(int(input())):
q1, q2 = map(int, input().split())
temp = l[q1 - 1 : q2]
print(sum(temp)) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/ARYS2020/problems/GOLDTRIP"
} | |
d565 | train | for _ in range(int(input())):
n,k=list(map(int,input().split()))
c=list(map(int,input().split()))
count=1
for i in range(n):
if i+1<n:
if c[i]-c[i+1]>=k or c[i+1]-c[i]>=k:
continue
else:
count+=1
c[i],c[i+1]=c[i+1],c[i]
print(count)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/COMS1501/problems/CM1503"
} | |
d566 | train | def f(a,y,index,sorted_pos):
#print(a,y,index,sorted_pos)
n=len(a)
low=0
high=n-1
L,R=0,0
l,r=0,0
while(low<=high):
mid=(low+high)//2
#print(low,high,mid)
if(a[mid]== y):
break
elif(mid > index[y]):
high=mid-1
L+=1
#print("L")
if(a[mid] <y):
l+=1
#print(" l ")
else:
low=mid+1
R+=1
#print("R")
if(a[mid]>y):
r+=1
#print("r")
x=sorted_pos[y]
#print(L,R,l,r,x,n-x-1)
if(R>x or L> n-x-1):
print("-1")
else:
print(max(l,r))
def fun():
test=int(input())
for t in range(test):
n,q=list(map(int,input().split()))
arr=list(map(int,input().split()))
index= dict()
for i in range(n):
index[arr[i]]=i
sorted_pos=dict()
a=sorted(arr)
for i in range(n):
sorted_pos[a[i]]=i
for x in range(q):
y=int(input())
f(arr,y,index,sorted_pos)
fun()
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/FAKEBS"
} | |
d567 | train | t=int(input())
for _ in range (t):
str1=input()
str2=input()
res='No'
for i in str1:
if i in str2:
res='Yes'
break
print(res)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/STRPALIN"
} | |
d568 | train | # cook your dish here
import sys
import math
def main(arr):
for i in range(1,len(arr)-1):
if arr[i]==arr[i-1] and arr[i]==arr[i+1]:
return "Yes"
return "No"
test=int(input())
for _ in range(test):
b=int(input())
arr=list(map(int,input().split()))
print(main(arr))
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/MAKEART"
} | |
d569 | train |
test=int(input())
for t in range(test):
n= int(input())
adj=[[] for i in range(n+1)]
for _ in range(n-1):
a,b=list(map(int,input().split()))
adj[a].append(b)
adj[b].append(a)
#print(adj)
root=1
q,s=[root],set([root])
for x in q:
adj[x]= [p for p in adj[x] if p not in s]
q.extend(adj[x])
s.update(adj[x])
#print(adj)
ans=True
if(n<4):
ans=False
for i in range(n+1):
if(len(adj[i]) %3!=0):
ans=False
if(ans):
print("YES")
for i in range(n+1):
while(len(adj[i])):
print(i,adj[i][0],adj[i][1],adj[i][2])
adj[i].pop(0)
adj[i].pop(0)
adj[i].pop(0)
else:
print("NO")
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/TREE3"
} | |
d570 | train | from math import sqrt
for _ in range(int(input())):
n = int(input())
x = int(sqrt(2 * n))
while x * (x+1) // 2 <= n:
x += 1
while x * (x+1) // 2 > n:
x -= 1
n -= x * (x+1) // 2
print(n)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/ENCD2020/problems/ECAPR203"
} | |
d571 | train | # cook your dish here
from collections import deque, defaultdict
from math import sqrt, ceil,factorial
import sys
import copy
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()
for _ in range(int(input())):
s=input()
if len(s)>6:
ans=0
rem=len(s)-6
ans+=factorial(len(s))
ans-=2*(factorial(len(s)-2))
ans+=factorial(rem+2)
print(ans)
else:
if 'k' in s and 'r' in s and 'a' in s and 's' in s and 'h' in s and 'i' in s:
ans = 0
rem = len(s) - 6
ans += factorial(len(s))
ans -= 2 * (factorial(len(s) - 2))
ans += factorial(rem + 2)
print(ans)
else:
if 'k' in s and 'a' in s and 'r' in s:
ans=0
rem=len(s)-3
ans+=factorial(len(s))
ans-=factorial(rem+1)
print(ans)
continue
if 's' in s and 'h' in s and 'i' in s:
ans = 0
rem = len(s) - 3
ans += factorial(len(s))
ans -= factorial(rem + 1)
print(ans)
continue
print(factorial(len(s)))
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/INDC2021/problems/AYUKAR"
} | |
d572 | train | #! /usr/bin/env python
from sys import stdin
from functools import reduce
def gcd(a,b):
while b!=0:
a,b=b,a%b
return a
def gcdl(l):
return reduce(gcd, l[1:],l[0])
def __starting_point():
T=int(stdin.readline())
for case in range(T):
numbers=list(map(int, stdin.readline().split()[1:]))
g=gcdl(numbers)
numbers=[n/g for n in numbers]
print(" ".join([str(x) for x in numbers]))
__starting_point() | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/COOK04/problems/RECIPE"
} | |
d573 | train | for _ in range(int(input())):
a,o,g=map(int,input().split())
while g>0:
if a<o:
a+=1
g-=1
elif o<a:
o+=1
g-=1
else:
break
print(abs(a-o)) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/FRUITS"
} | |
d574 | train | 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) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CHN05"
} | |
d575 | train | for t in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
s=0
l=[]
for i in range(n):
if (a[i]<0):
e=i
ss=sum(a[s:e])
l.append((ss,e-s,n-s))
s=i+1
e=n
ss=sum(a[s:e])
l.append((ss,e-s,n-s))
x=max(l)
s=n-x[2]
e=x[1]+s
for i in range(s,e):
print(a[i], end=' ')
print("") | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CDBU2015/problems/CDBSTR06"
} | |
d576 | train | for _ in range(int(input())):
st=input().replace("=","")
if not len(st):print(1)
else:
cu=mx=1
for j in range(1,len(st)):
if st[j]==st[j-1]:cu+=1
else:mx=max(mx,cu);cu=1
print(max(mx+1,cu+1))
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CHEFSIGN"
} | |
d577 | train | for _ in range(int(input())):
S = input()
n = len(S)
a = n - S.count('a')
print(2 ** n - 2 ** a) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CFW32020/problems/OMGO"
} | |
d578 | train | knows=input()
n=eval(input())
while n!=0:
n=n-1
word=input()
for x in word:
ctr=0
for y in knows:
if x==y:ctr=ctr+1;break
if ctr==0:print('No');break
else: print('Yes') | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/LTIME39/problems/ALPHABET"
} | |
d579 | train | # cook your dish here
for i in range(int(input())):
n,b=map(int,input().split())
ans=round(n/(2*b))*(n-b*round((n/(2*b))));
print(ans) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CALC"
} | |
d580 | train | t=int(input())
def check():
pref = [0]*n
pref[0]=a[0]
suff = [0]*n
suff[-1]=a[-1]
for i in range (1,n):
pref[i] = pref[i-1]|a[i]
suff[n-i-1] = suff[n-i]|a[n-i-1]
if suff[1]==k:
return 0
elif pref[n-2]==k:
return n-1
else:
for i in range (1,n-1):
if pref[i-1]|suff[i+1] == k:
return i
return -1
while(t):
t-=1
n,k=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
ans = []
arr = [0]*n
for i in range (n):
if k|a[i] != k:
a[i] = a[i-1]|a[(i+1)%(n)]
ans.append(i+1)
arr[i]=1
x = 0
count = 0
for i in range (n):
x|=a[i]
if x!= k:
print(-1)
else:
y = check()
if y == -1:
print(-1)
else:
for i in range (y,n+y):
if arr[i%n]==0:
arr[i%n]==1
ans.append((i%n)+1)
print(*ans) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/RECNDORO"
} | |
d581 | train | 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 = 998244353
def inp(): return stdin.readline().strip()
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def smp(): return map(str, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def remadd(x, y): return 1 if x%y else 0
def ceil(a,b): return (a+b-1)//b
def isprime(x):
if x<=1: return False
if x in (2, 3): return True
if x%2 == 0: return False
for i in range(3, int(sqrt(x))+1, 2):
if x%i == 0: return False
return True
for _ in range(int(inp())):
n = int(inp())
for i in range(n):
for j in range(n):
if i==0 or i==n-1 or j==0 or j==n-1 or i==j or i+j==n-1:
print(1, end="")
else:
print(" ", end="")
print() | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/PTRN2021/problems/ITGUY54"
} | |
d582 | train | # 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") | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/IC32016/problems/HBB"
} | |
d583 | train | import sys
import bisect as bi
import math
from collections import defaultdict as dd
input=sys.stdin.readline
##sys.setrecursionlimit(10**7)
def cin():
return list(map(int,sin().split()))
def ain():
return list(map(int,sin().split()))
def sin():
return input()
def inin():
return int(input())
for _ in range(inin()):
s=sin().strip();q=inin();a=ain();n=len(s);store=[0]*n;store1=[-1]*n;f=0;d=dd(int)#input wgera
store[0]=1 if s[0]=='(' else -1
d[store[0]]=1
for i in range(1,n):
if(s[i]=='('):
store[i]=store[i-1]+1
d[store[i]]=i+1
else:
store[i]=store[i-1]-1
if(d[store[i-1]]):
store1[d[store[i-1]]-1]=i+1
post=[-1]*n;
if(n==1 or(n==2 and s!="()")):f=1 # corner case
for i in range(n-2,-1,-1):
if(s[i]=='('): #dekhna h ki agla agr ( h toh -1 hi rhega wrna wo jo stored tha uppr
if(store1[i]!=-1):post[i]=store1[i] #wo iska ans ho jayega
else:post[i]=post[i+1] #jo iske agle ka answer hoga wahi iska hoga
for i in a:
if(f):print(-1) #cond ki jaroorat nhi thi pr tasalli (>_<)
else:print(post[i-1]) #wrna uska ans print kra do
##n=m=0
##s=''
##t=''
##dp=[]
##def solve(inds,indt,k,cont):
## ans=-999999999999999
## print(dp)
## if(k<0):return 0
## elif(inds>=n and indt>=m):return 0
## elif(dp[inds][indt][k][cont]!=-1):return dp[inds][indt][k][cont]
## else:
## if(indt<m):ans=max(ans,solve(inds,indt+1,k,0))
## if(inds<n):ans=max(ans,solve(inds+1,indt,k,0))
## if(s[inds]==t[indt]):
## ans=max(ans,solve(inds+1,indt+1,k-1,1)+1)
## if(cont):ans=max(ans,solve(inds+1,indt+1,k,1)+1)
## dp[inds][indt][k][cont]=ans
## return ans
## n,m,k=cin()
## s=sin().strip()
## t=sin().strip()
## dp=[[[[-1]*2 for i in range(k)] for i in range(m+1)] for i in range(n+1)]
## c=0
## for i in dp:
## for j in i:
## for l in j:
## c+=1
## print(l,c)
## print(solve(0,0,k,0))
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/COLE2020/problems/CLBRKT"
} | |
d584 | train | n=int(input())
for i in range(n):
t=int(input())
m=list(map(int,input().split()))
p,q=0,0
if t==1:
if m[0]>=0:
print('YES')
else:
print('NO')
else:
for i in m:
if i<0:
q+=i
else:
p+=i
if p>=abs(q):
print('YES')
else:
print('NO') | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/WATMELON"
} | |
d585 | train | for z in range(int(input())):
s = input()
n = len(s)
i = 0
while i<n and s[i]=='1':
i+=1
if i==0:
print(0)
else:
k = 0
while i<n and s[i]=='0':
i+=1
k+=1
print(k)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CHIL2020/problems/BININSC"
} | |
d586 | train | import functools
def gcd(x,y):
if(y == 0):
return x
return gcd(y, x%y)
for _ in range(int(input())):
n, m= map(int, input().split())
p = list(map(int, input().split()))
ans = functools.reduce(lambda x,y: gcd(x, y), p)
if(ans <= n):
print(n-ans)
else:
f = [1]
for k in range(ans//2, 1, -1):
if ans %k == 0:
if k<=n:
f.append(k)
if ans//k <= n:
f.append(ans//k)
res = n-max(f)
print(res) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CIRCHAOS"
} | |
d587 | train | # cook your dish here
for t in range(int(input())):
n,k=map(int,input().split())
a=[]
sr=[]
for i in range(k):
x,y=input().split()
y=int(y)
a.append([10**10-y,x])
sr.append(sorted(x))
for i in range(n-k):
x,y=input().split()
y=int(y)
x=sorted(x)
for j in range(k):
if x==sr[j]:
a[j][0]-=y
break
a.sort()
for i in a:
print(i[1],abs(i[0]-10**10)) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/BLAS2020/problems/TM"
} | |
d588 | train | n=int(input())
a=list(map(int,input().split()))
c=[]
for i in range(len(a)):
if a[i]==2:
c.append(1)
else:
c.append(a[i]^2)
print(*c) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/INRO2021/problems/COUPLING"
} | |
d589 | train | def gcd(a, b):
if a == 0:
return b
return(gcd(b % a, a))
t = int(input())
for T in range(t):
n = int(input())
l = [int(x) for x in input().split()]
ang = []
for i in range(1, n):
ang.append(l[i] - l[i - 1])
ang.append(360 - (l[-1] - l[0]))
ang.sort()
if ang == ang[::-1]:
print(0)
continue
g = ang[0]
for i in range(1, n):
g = gcd(g, ang[i])
total = 360 // g - len(ang)
print(total)
## print(g, ang, total)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CUTPIZ"
} | |
d590 | train | # cook your dish here
for i in range(int(input())):
s = input()
m = 0
p = 0
d = 0
l = []
for i in range(len(s)):
if(s[i] == "."):
m = m+1
elif(s[i] == "#"):
l.append(m)
m=0
for i in range(len(l)):
if(l[i]>p):
p = l[i]
d = d+1
print(d)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/ATTIC"
} | |
d591 | train | for _ in range(int(input())):
n,x,m = map(int,input().split())
a = list(map(int,input().split()))
for _ in range(m):
for i in range(1,n):
a[i] = a[i] + a[i-1]
print(a[x-1]%(10**9+7)) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/STROPR"
} | |
d592 | train | for _ in range(int(input())):
N = input()
num = list(N)
s=0
for n in num:
if n.isnumeric():
s+=int(n)
#print(s)
x=(10-s%10)%10
print(int(N)*10+int(x)) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/CORS2020/problems/JOJO"
} | |
d593 | train | import sys
def mex(S,W,C,start,end):
"""Returns Nim-number of S[start:end]"""
key=(start,end)
try:
return C[key]
except KeyError:
pass
A=set()
for s in range(start,end):
for e in range(start+1,end+1):
if S[s:e] not in W: continue
A.add(mex(S,W,C,start,s)^mex(S,W,C,e,end))
a=0
while a in A: a+=1
C[key]=a
return a
a=sys.stdin
#a=open('astrgame.txt','r')
T=int(a.readline())
for t in range(T):
S=a.readline().strip()
N=int(a.readline())
W=set([a.readline().strip() for n in range(N)])
print('Teddy' if mex(S,W,{},0,len(S)) else 'Tracy')
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/DEC10/problems/ASTRGAME"
} | |
d594 | train | # cook your dish here
# cook your dish here
for i in range(int(input())):
a=list(map(int,input().split()))
x=input()
t=0
for i in range(ord('a'),ord('z')+1):
if chr(i) not in x:
t+=a[i-97]
print(t) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/MATPAN"
} | |
d595 | train | def solve(a,n):
max1=curr=a[0]
for i in range(1,n):
curr=max(a[i],curr+a[i])
max1=max(max1,curr)
return max1
n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
print(sum(a)-solve(a,n)+solve(a,n)/k)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/SMALLARR"
} | |
d596 | train | def binarySearch(arr, l, r, x):
mid=0
while l <= r:
mid = l + (r - l)//2;
if arr[mid] == x:
return mid+1
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
if mid!=len(arr):
if arr[mid]<x:
return mid+1
return mid
s=input()
strt=[]
end=[]
plc=[]
landr=[]
l2r=[]
lr=[]
ans=0
n=len(s)
if n!=1:
for i in range(n):
strt.append([])
end.append([])
landr.append([0]*n)
l2r.append([0]*n)
for i in range(n):
for j in range(n):
if i-j<0 or i+j>=n:
break
if (s[i-j]==s[i+j]):
if i-j-1>=0:
strt[i-j-1].append(2*j+1)
if i+j+1<n:
end[i+j+1].append(2*j+1)
else:
break
for i in range(n):
for j in range(n):
if i-j<0 or i+j+1>=n:
break
if (s[i-j]==s[i+j+1]):
if i-j-1>=0:
strt[i-j-1].append(2*j+2)
if i+j+2<n:
end[i+j+2].append(2*j+2)
else:
break
for i in range(n):
end[i].sort()
strt[i].sort()
for i in range(n-1):
for j in range(i+1,n):
if s[i]==s[j]:
lr.append([i,j])
if i>0 and j<n-1:
landr[i][j]=landr[i-1][j+1]+1
else:
landr[i][j]=1
for i in lr:
tempans=1
l=i[0]
r=i[1]
length=r-l-1
tempans+=binarySearch(strt[l],0,len(strt[l])-1,length)
tempans+=binarySearch(end[r],0,len(end[r])-1,length)
l2r[l][r]=tempans
for i in range(n):
for j in range(n):
ans+=l2r[i][j]*landr[i][j]
print(ans) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/KLPM"
} | |
d597 | train | import sys
from random import choice,randint
inp=sys.stdin.readline
out=sys.stdout.write
flsh=sys.stdout.flush
sys.setrecursionlimit(10**9)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def MI(): return map(int, inp().strip().split())
def LI(): return list(map(int, inp().strip().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines().strip()]
def LI_(): return [int(x)-1 for x in inp().strip().split()]
def LF(): return [float(x) for x in inp().strip().split()]
def LS(): return inp().strip().split()
def I(): return int(inp().strip())
def F(): return float(inp().strip())
def S(): return inp().strip()
def pf(s): return out(s+'\n')
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def main():
from math import ceil
t = I()
l = []
for _ in range(t):
n,k=MI()
if n==0:
k-=1
ans = ((k)*((k+1)))%mod
l.append(ans)
else:
# if k==1:
# ans = ((((n)*((n-1)))%mod)+ n%mod)%mod
# l.append(ans)
# else:
# k-=1
# lr = (n%mod+((ceil(k/2)%mod))%mod
# ans = ((lr*((lr-1))%mod
# if k%2!=0:
# ans= (ans%mod + n%mod)%mod
# else:
# ans = ((ans%mod)+((lr+n)%mod))%mod
# l.append(ans)
if k%2!=0:
lr = k//2
l.append(((n*n)%mod+(lr*((2*n)%mod))%mod+(lr*(lr+1))%mod)%mod)
else:
lr = k//2
l.append(((n*n)%mod + (lr*(2*n)%mod)%mod + (lr*(lr-1))%mod)%mod)
for i in range(t):
pf(str(l[i]))
def __starting_point():
main()
__starting_point() | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/RC122020/problems/RECNDNUM"
} | |
d598 | train | # cook your dish here
t = int(input())
for _ in range(t):
n = int(input())
a = []
b = []
for i in range(n):
x,y = list(map(int, input().split()))
a.append(x)
b.append(y)
b.sort()
xcor = []
xcor.append(a[1]-a[0])
xcor.append(a[n-1]-a[n-2])
for i in range(1,n-1):
xcor.append(a[i+1]-a[i-1])
xcor.sort()
ans = 0
#print(xcor)
#print(b)
for i in range(n):
ans = ans + xcor[i]*b[i]
print(ans)
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/BIGRES"
} | |
d599 | train | n, k = list(map(int, input().split()))
A = list(map(int, input().split()))
maximum = max(A)
minimum = min(A)
if k == 0:
for i in A:
print(i, end=' ')
elif k&1:
for i in A:
print(maximum - i, end=' ')
else:
for i in A:
print(i - minimum, end=' ')
| PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/MAY14/problems/RRSTONE"
} | |
d600 | train | from collections import deque
t=int(input())
for i in range(t):
n=int(input())
N=[i for i in range(1, n+1)]
w=list(map(int, input().split()))
max_sweetness=max(w)
sizes=[]
cnt=0
for i in range(n):
if w[i]!=max_sweetness:
cnt+= 1
else:
sizes.append(cnt)
cnt=0
if cnt!=0:
sizes[0]=(cnt+sizes[0])
res=0
for i in range(len(sizes)):
res+=max(sizes[i]-n//2+1, 0)
print(res) | PYTHON | {
"starter_code": "",
"url": "https://www.codechef.com/problems/CHCBOX"
} |