contest_id stringclasses 33
values | problem_id stringclasses 14
values | statement stringclasses 181
values | tags listlengths 1 8 | code stringlengths 21 64.5k | language stringclasses 3
values |
|---|---|---|---|---|---|
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)L... | [
"brute force",
"math",
"number theory"
] | def helper(l,i,t,x):
global ans,lans
if i>=len(l):
return
if max(t,x)<ans:
ans=max(t,x)
lans[0]=t
lans[1]=x
helper(l,i+1,t*l[i],x//l[i])
helper(l,i+1,t,x)
n=int(input())
l=[]
t=n
i=1
while t%2==0:
i*=2
t//=2
l.append(i)
j=3
while j*j<=t:
... | py |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algori... | [
"data structures",
"greedy",
"sortings"
] | import os, sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop
from functools import lru_cache
from itertools import accumulate
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(I... | py |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko... | [
"implementation",
"strings"
] | n,m=[int(i) for i in input().split()]
s=[z for z in input().split()]
t=[z for z in input().split()]
q=int(input())
for j in range(q):
y=int(input())
y1=(y%n)-1
y2=(y%m)-1
print(s[y1]+t[y2]) | py |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both... | [
"constructive algorithms",
"greedy",
"number theory"
] | for i in range(int(input())):
print(1,int(input())-1)
| py |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.... | [
"data structures",
"implementation"
] | t = int(input())
for q in range(t):
n = int(input())
s = input().strip()
l, r = 0, n
p = (0,0)
d = {p:1}
i = 1
for v in s:
if v == 'L':
p = (p[0]-1, p[1])
elif v == 'R':
p = (p[0]+1, p[1])
elif v == 'U':
p = (p[0], p[1... | py |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord... | [
"greedy",
"implementation",
"sortings"
] | t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
l1 = []
l2 = []
for i in range(0, 2 * n, 2):
l1.append(arr[i])
l2.append(arr[i + 1])
if n % 2 == 1:
print(abs(l1[n // 2] - l2[n // 2]))
else:
... | py |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong 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 memor... | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | for a0 in range(int(input())):
n,k = map(int,input().split())
a,b = k,k
t,l,r = [0 for i in range(n)],[0 for i in range(n)],[0 for i in range(n)]
for i in range(n):
t[i],l[i],r[i] = map(int,input().split())
t.insert(0,0)
for i in range(n):
b+=t[i+1] - t[i]
a-=t[i... | py |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are an... | [
"greedy",
"implementation"
] | a = int(input())
for i in range(a):
q = int(input())
s = input()
if "A" not in s:
print(0)
else:
w = s.index("A")
d = []
e = 0
for j in range(w, q):
if s[j] == "A":
d.append(e)
e = 0
else:
... | py |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she cam... | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | import sys
from array import array
input = lambda: sys.stdin.buffer.readline().decode().strip()
inp = lambda dtype: [dtype(x) for x in input().split()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
Mint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, []
for _ in range(1):
M... | py |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array o... | [
"data structures"
] | import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists... | py |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to ... | [
"implementation"
] | n = int(input())
for i in range(n):
a,b,x,y = map(int,input().split())
print(max(b*(a-1-x),b*(x),a*(b-1-y),a*y)) | py |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are cor... | [
"greedy"
] | from collections import Counter
n = int(input())
s = input()
count = Counter(s)
open = closed = 0
if count['('] != count[')']:
print(-1)
else:
res = 0
balance = 0
prev = ''
for i in range(len(s)):
if s[i] == '(':
balance += 1
else:
balance -= 1
if ba... | py |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going... | [
"constructive algorithms",
"graphs",
"implementation"
] | def loopRight(path):
path.append('DUR')
def loopLeft(path):
path.append('DUL')
def straightRight(path,n):
path.append('R'*(n-1))
def straightLeft(path,n):
path.append('L'*(n-1))
def main():
n,m,k=readIntArr()
if k>4*n*m-2*n-2*m:
print('NO')
return
#... | py |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO... | [
"data structures",
"dsu",
"implementation"
] | n,q=map(int,input().split())
lava=[[0]*n for _ in[0,0]]
pairs=0
for _ in[0]*q:
x,y=map(lambda s:int(s)-1,input().split())
delta=1-2*(lava[x][y]==1)
lava[x][y]=1-lava[x][y]
for dy in range(-1,2):
if 0<=y+dy<n and lava[1-x][y+dy]==1:pairs+=delta
if not pairs:print('YES');continue
print('NO') | py |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a... | [
"implementation",
"math"
] | for i in range(int(input())):
n = int(input())
arr = [int(_) for _ in input().split()]
val = 0
val += arr.count(0)
if arr.count(0) > 0:
if sum(arr) + val == 0:
val += 1
if sum(arr) + val == 0:
val += 1
print(val)
| py |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of ... | [
"implementation",
"math"
] | a,b=map(int,input().split())
if a==b:
print(0)
elif (a>b):
print(-1)
else:
c=0
x=b/a
while(x%2==0):
x/=2
c+=1
while(x%3==0):
x/=3
c+=1
print(c if x==1 else -1) | py |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are cor... | [
"greedy"
] | import bisect
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().s... | py |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifical... | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.py'
#
# Created by: PyQt5 UI code generator 5.15.7
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
n = 0
s = input()
l = []
ppiont = 0... | py |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey... | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | import sys, random
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18
LI = lambda : list(map(int, input().split()));... | py |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. ... | [
"math",
"number theory",
"probabilities"
] | import random
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def the_sieve_of_eratosthenes(n):
s = [1] * (n + 1)
x = []
for i in range(2, n + 1):
if s[i]:
x.append(i)
for j in range(i, n + 1, i):
s[j] = 0
retur... | py |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to ... | [
"implementation"
] | for i in range(int(input())):
a, b, x, y = map(int, input().split())
print(max(max(y, b - 1 - y) * a, max(x, a - 1 - x) * b)) | py |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are differen... | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | import sys
import math
import bisect
import heapq
import string
from collections import defaultdict,Counter,deque
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return l... | py |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) an... | [
"geometry",
"greedy",
"math",
"number theory"
] | t = int(input())
for i in range (t):
n, m = map(int, input().split())
if(n % m == 0):
print('yes')
else:
print('no') | py |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going... | [
"constructive algorithms",
"graphs",
"implementation"
] | import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
from itertools import permutations
from operator import itemgetter
# sys.setrecursionlimit(2*10**5+1000... | py |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constru... | [
"data structures",
"dp",
"greedy"
] | import sys
def get_vals(n, arr, rev):
if rev:
arr.reverse()
st = []
vals = [0 for i in range(n)]
for i in range(n):
while len(st) != 0 and arr[st[-1]] >= arr[i]:
st.pop()
vals[i] = (i + 1) * arr[i] if len(st) == 0 else (i - st[-1]) * arr[i] + vals[st[... | py |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algori... | [
"data structures",
"greedy",
"sortings"
] | from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from time import time
from itertools import permutations as per
from heapq import heapify,heappush,heappop,heappushpop
input=stdin.readline
R=lambda:map(int,inp... | py |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, yo... | [
"greedy",
"math",
"number theory"
] | t = int(input())
#prime sieve
MAX = 32000 #sqrt(10**9)
primeSieve = [True]*MAX
primes = []
primeSieve[0] = primeSieve[1] = False
for i in range(2,MAX):
if primeSieve[i] == True:
primes.append(i)
for j in range(i*i, MAX, i):
primeSieve[j] = False
for _ in range(t):
n =... | py |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constru... | [
"data structures",
"dp",
"greedy"
] | import heapq
def findLess(n,array):
stack=[]
ans = []
for x in range(n):
if not stack:
stack.append(x)
ans.append(-1)
else:
while stack and array[stack[-1]]>array[x]:
stack.pop()
if not stack:
ans.append(-1)
... | py |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P... | [
"geometry"
] | def half(L,i,j): return ((L[i][0]+L[j][0])/2,(L[i][1]+L[j][1])/2)
def solv(n):
if n%2: return 'NO'
L = [list(map(int,input().split())) for _ in range(n)]
h = n//2
X = [half(L,i,i+h) for i in range(h)]
for i in range(1,h):
if X[i][0]!=X[0][0] or X[i][1]!=X[0][1]: return 'NO'
ret... | py |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by... | [
"geometry",
"greedy",
"math"
] | T = int(input())
for _ in range(T):
N, X = map(int, input().split())
A = list(map(int, input().split()))
m = max(A)
if X in A:
print(1)
else:
print(max(2, (X + m - 1) // m))
| py |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n b... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | from collections import deque
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(i, j):
return i * n + j
def bfs(sx, sy):
q = deque()
q.append((sx, sy))
ans[sx][sy] = "X"
z = f(sx, sy)
while q:
i, j = q.popleft()
for di, dj, _ , ... | py |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of... | [
"dfs and similar",
"dsu",
"graphs"
] | from sys import stdin
class disjoinSet(object):
def __init__(self,n):
self.father = [x for x in range(0,n+1)]
self.rank = [0 for x in range(0,n+1)]
def setOf(self, x):
if(self.father[x] != x):
self.father[x] = self.setOf(self.father[x])
return self.father[... | py |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11)... | [
"implementation"
] | n = int(input())
a = input().split()
l, r = 0, n-1
while l < r and a[l] == '1':
l += 1
while l < r and a[r] == '1':
r -= 1
max_t = l + n - 1 - r
curr_t = 0
for i in range(l, r+1):
if a[i] == '1':
curr_t += 1
else:
max_t = max(max_t, curr_t)
curr_t = 0
... | py |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e.... | [
"binary search",
"greedy",
"implementation"
] | n,m,k=map(int,input().split())
a=[len(i)for i in input().replace(' ','').split('0')if len(i)>0]
b=[len(i)for i in input().replace(' ','').split('0')if len(i)>0]
d=[(i,k//i)for i in range(1,int(k**0.5)+1)if k%i==0]
d+=[(j,i)for i,j in d if i!=j]
c=0
for x,y in d:c+=sum(i-x+1 for i in a if x<=i)*sum(j-y+1 for j in ... | py |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer numb... | [
"math"
] | # ⠀⠀⠀⠀⠀⠀⠀⠀⣠⠞⠁⠀⠀⠀⠀⠀⢠⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⢳⣤⣤⣀⣀⠀⠀
# ⣶⣶⣶⣶⣾⠟⣩⠟⠁⠀⠀⢀⠎⠀⠀⡰⠋⠀⠀⠀⠀⡴⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣄⠙⠿⣷
# ⣿⣿⣿⠏⢉⡾⠃⠀⠀⠀⢀⠆⠀⠀⠰⠁⠀⠀⠀⠀⡜⠁⠀⠀⠀⣰⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⢿⣧⠀⢸
# ⣿⣿⠉⣰⡟⠁⠀⠀⠀⢠⠎⠀⠀⠀⠀⠀⠀⠀⠀⢰⠁⠀⠀⡰⢱⠃⠀⠀... | py |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate... | [
"binary search",
"brute force",
"math",
"ternary search"
] | # Read the number of test cases
t = int(input())
# Process each test case
for _ in range(t):
# Read the number of days before the deadline and the number of days the program runs
n, d = map(int, input().split())
# Check if Adilbek can fit in n days
if d <= n:
print("YES")
else:
# Check... | py |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer numb... | [
"math"
] | for i in range(int(input())):
a=int(input())
print(int(a//0.9)) | py |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position... | [
"math"
] | n=int(input())
s=input()
s=s[:n]
print(n+1) | py |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It... | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | t = int(input())
for _ in range(t):
s = input()
consec = 0
biggest = 0
for i in range(len(s)):
if s[i] == "R":
consec = 0
else:
consec += 1
if consec > biggest:
biggest = consec
print(biggest+1) | py |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going... | [
"constructive algorithms",
"graphs",
"implementation"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m, k = map(int, input().split())
ans = "YES" if k <= 4 * n * m - 2 * n - 2 * m else "NO"
print(ans)
if ans == "NO":
exit()
ans = []
if n == 1:
f = min(m - 1, k)
k -= f
ans.append(" ".join((str(f), "R")))
... | py |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a cont... | [
"implementation",
"strings"
] | # LUOGU_RID: 101845216
for _ in range(int(input())):
s = input()
l = 0
while l < len(s) and s[l] == '0':
l += 1
r = len(s)
while r > l and s[r - 1] == '0':
r -= 1
print(r - l - s.count('1')) | py |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array o... | [
"data structures"
] | class SegmentTree():
def __init__(self,arr,func,initialRes=0):
self.f=func
self.N=len(arr)
self.tree=[0 for _ in range(4*self.N)]
self.initialRes=initialRes
for i in range(self.N):
self.tree[self.N+i]=arr[i]
for i in range(self.N-1,0,-1):
... | py |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for an... | [
"brute force",
"greedy",
"math"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
a = list(map(int, input().split()))
pow2 = [1]
for _ in range(30):
pow2.append(2 * pow2[-1])
for i in reversed(pow2):
c = 0
for j in range(n):
if i & a[j]:
c += 1
k ... | py |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the ... | [
"math"
] | import sys
input = sys.stdin.readline
output = sys.stdout.write
def main():
tests = int(input().rstrip())
for i in range(tests):
list_ = list(map(int, input().rstrip().split()))
coins = list_.pop(-1)
list_.sort()
dif = (list_[2] - list_[1]) + (list_[2] - list_[0])
... | py |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the p... | [
"brute force",
"data structures",
"implementation"
] | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, functools, copy,statistics
inf = float('inf')
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readl... | py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun... | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase
"""def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)"""
"""def pw(a,b):
result=1
while(b>0):
if(b%2==1): result*=a
... | py |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. ... | [
"math",
"number theory",
"probabilities"
] | # TESTING EDITORIAL SUBMISSION FOR TEST CASE 105
import random
n = int(input())
a = list(map(int, input().split()))
limit = min(8, n)
iterations = [x for x in range(n)]
random.shuffle(iterations)
iterations = iterations[:limit]
def factorization(x):
primes = []
i = 2
while i * i <= x:
if x % i ... | py |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are cor... | [
"greedy"
] | n,s,p,a=int(input()),input(),0,0
for i in s:
if i=="(":p+=1
else:p-=1;a+=2 if(p<0)else(0)
print("-1"if p else a) | py |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ... | [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | def solve(s):
res = []
s2 = sorted(s)
rightest = {}
for i,c in enumerate(s2):
rightest[c] = i
for i,c in enumerate(s):
done = [0,0]
for j,c2 in enumerate(s):
if j == i: break
if rightest[c2] > rightest[c]:
done[res[j]] = 1
if done[1] == 0: res.append(1)
eli... | py |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algori... | [
"data structures",
"greedy",
"sortings"
] | """
# ---------------------------------------- fast io ----------------------------------------
import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
sel... | py |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.E... | [
"math"
] | from heapq import heapify, heappop, heappush
from itertools import cycle
from math import sqrt,ceil
import os
import sys
from collections import defaultdict,deque
from io import BytesIO, IOBase
# prime = [True for i in range(5*10**7 + 1)]
# def SieveOfEratosthenes(n):
# p = 2
# while (p * p <... | py |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any othe... | [
"dfs and similar",
"graphs",
"shortest paths"
] | # Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
from collections import deque
def main():
n,m=map(int,input().split())
directgraph=[[] for _ in range(n+1)]
graph=[[] for _ in range(n+1)]
for _ in r... | py |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the n... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | import sys
import math
input = sys.stdin.readline
from functools import cmp_to_key;
def pi():
return(int(input()))
def pl():
return(int(input(), 16))
def ti():
return(list(map(int,input().split())))
def ts():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,inp... | py |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, ... | [
"math",
"strings"
] | import abc
import itertools
import math
from math import gcd as gcd
import sys
import queue
import itertools
from heapq import heappop, heappush
import random
from array import array
from bisect import *
# input = lambda: sys.stdin.buffer.readline().decode().strip()
# inp = lambda dtype: [dtype(x) for x i... | py |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart in... | [
"constructive algorithms",
"math",
"ternary search"
] | from pprint import pprint
import sys
read = sys.stdin.buffer.read
n,m,p, *dat = map(int, read().split())
data = dat[:n]
datb = dat[n:]
for i in range (n):
if data[i]%p != 0:
inda = i
break
for i in range (m):
if datb[i]%p != 0:
indb = i
break
print(indb + inda) | py |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko... | [
"implementation",
"strings"
] | from sys import stdin, stdout
input = stdin.readline
# print = stdout.write
import sys
# sys.setrecursionlimit(int(1e9))
from collections import defaultdict
def ii():
return int(input())
def li():
return list(map(int, input().split()))
def consecutive_ones(arr, n):
count = 0
... | py |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ... | [
"greedy"
] | g = dict()
n = int(input())
a = list(map(int,input().split()))
for i in range(n):
total = 0
for j in range(i,n):
total += a[j]
if total in g:
g[total].append((i + 1,j + 1))
else:
g[total] = [(i+1,j+1)]
ans = 0
res = []
for k in g:
t = -1
tem... | py |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart in... | [
"constructive algorithms",
"math",
"ternary search"
] |
import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
n,m,p = get_ints()
a = get_list()
b = get_list()
i =0
while i<n:
if a[i]%p != 0:
break
i+=1
j =0
while j<m:
if b[j]%p != 0... | py |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11)... | [
"implementation"
] | n = int(input())
a = [int(x) for x in input().split()][:n]
count, max = 0, 0
check1, check2 = False, False
start, end = 0, 0
for i in range(n):
if a[i] == 1:
count += 1
if not check1:
start += 1
else:
count = 0
check1 = True
if count > max: max = count
for i in reversed(range(n)):
if a[i] == 1 and no... | py |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can... | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
xy = [(x0, y0)]
x, y = x0, y0
while True:
x *= ax
x += bx
y *= ay
y += by
if max(x - xs, y - ys) > t:
break
... | py |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. Th... | [
"geometry",
"implementation"
] | import math
r = lambda: map(int,input().split())
def cross(a, b):
return a[0] * b[1] - a[1] * b[0]
def dot(a, b):
return a[0] * b[0] + a[1] * b[1]
def on_line(a, b):
return dot(a, b) > 0 and cross(a, b) == 0 and abs(b[0]) <= abs(5 * a[0]) <= abs(4 * b[0]) and abs(b[1]) <= abs(5 * a[1]) <= abs(4 * b[1])
de... | py |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to ... | [
"implementation"
] | for i in range(int(input())):
a,b,x,y=map(int,input().split())
print(max(max(x,a-1-x)*b,a*max(y,b-1-y))) | py |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e.... | [
"binary search",
"greedy",
"implementation"
] | from collections import defaultdict as dd
import sys
input = lambda: sys.stdin.readline().rstrip()
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a_conts1 = []
b_conts1 = []
cont1 = 0
for i in range(n):
if a[i] == 1:
cont1 += 1
... | py |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. ... | [
"dp",
"sortings"
] | import sys
# sys.setrecursionlimit(int(1e9))
# import random
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce
# from itertools import accumulate,product
from heapq import nsmallest, nlargest, heapify, heappop, heappush
# from bisect import bisect_left,bisect_right
# fr... | py |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positiv... | [
"greedy",
"implementation",
"math"
] | for _ in range(int(input())):
a, b = tuple(int(i) for i in input().split())
if a == b:
print(0)
elif a > b:
print((1, 2)[(a - b) & 1])
else:
print((2, 1)[(b - a ) & 1]) | py |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the n... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | ###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ... | py |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q... | [
"combinatorics",
"greedy",
"math"
] | n=int(input())
a=0
for i in range(n):
a+=1/n
n-=1
print(a)
| py |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifical... | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | ######################################################################################
#------------------------------------Template---------------------------------------#
######################################################################################
import collections
import heapq
import sys
import math... | py |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l... | [
"data structures",
"geometry",
"greedy"
] | import sys
input = sys.stdin.buffer.readline
def process(A):
n = len(A)
curr = [[A[0], 1]]
for i in range(1, n):
ai = A[i]
curr.append([ai, 1])
while len(curr) > 1:
ai, l = curr[-1]
aj, j = curr[-2]
if l*aj >= j*ai:
a... | py |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constructio... | [
"brute force",
"data structures",
"dp",
"greedy"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
n = int(input())
li = list(map(int, input().split()))
max_r = -1
max_r_mid = -1
for mid in range(n):
temp_r = 0
temp_r += li[mid]
max_pv = li[mid]
cur_i = mid
while True:
cur_i -= 1
if cur_i < 0:
... | py |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of ... | [
"implementation",
"math"
] | import math
a=int(input())
r=0
for b in range(2,a):
c=a
while c:r+=c%b;c//=b
a-=2
d=math.gcd(r,a)
print(f'{r//d}/{a//d}') | py |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and re... | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | n = int(input())
s = input()
for maxElement in sorted(list(s), reverse=True):
prev = chr(ord(maxElement)-1)
edited = False
for i in range(len(s)):
if s[i] == maxElement:
if i==0 and i+1<len(s):
if s[i+1] == prev:
s = s[i+1:]
... | py |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i... | [
"dp",
"strings"
] | class NextStringIndex:
def __init__(self, string):
self.INF = 10 ** 9
self.alph = "abcdefghijklmnopqrstuvwxyz"
self.kind = len(self.alph)
self.to_ind = {char: ind for ind, char in enumerate(self.alph)}
self.string = string
self.len_s = len(string)
se... | py |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8... | [
"binary search",
"combinatorics",
"number theory"
] |
import math
def update(x,a):
for m in div[x]:
cnt[m]+=a
def coprime(x):
count = 0
for i in div[x]:
count+=cnt[i]*u[i]
return count
n = int(input())
a = input().split(" ")
ans = 0
b = [False]*1000010
for x in range(n):
a[x] = int(a[x])
ans = max(a[x],ans)
... | py |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (poss... | [
"math"
] | for _ in range(int(input())):
length = int(input())
odd = 0
for number in input().split():
if int(number) & 1:
odd += 1
if odd == 0:
print('NO')
elif odd == length and not length & 1:
print('NO')
else:
print('YES') | py |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal... | [
"greedy",
"sortings"
] | n, a, b, kill = map(int, input().split())
l = []
p = 0
for h in map(int, input().split()):
r = (h - a)%(a+b)
if r <= b:
l.append(r//a + (r % a != 0))
else:
p += 1
l.sort()
s = 0
for i in l:
s += i
if s > kill:
break
p += 1
print(p)
| py |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn 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... | [
"data structures",
"hashing",
"strings"
] | 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)
... | py |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is whi... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | # NOT MY CODE
# https://codeforces.com/contest/1324/submission/73179914
## PYRIVAL BOOTSTRAP
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
# This decorator allows for recursion without actually doing recursion
from types import GeneratorType
def bootstrap(f, stack=[]):
... | py |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO... | [
"data structures",
"dsu",
"implementation"
] | import sys
input = sys.stdin.readline
n, q = map(int, input().split())
w = [[0]*(n+2) for _ in range(2)]
c = 0
for _ in range(q):
i, j = map(int, input().split())
if w[i-1][j] == 0:
w[i-1][j] = 1
for x in [-1, 0, 1]:
if w[2-i][j+x] == 1:
c += 1
else:... | py |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of ... | [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | import sys
input = sys.stdin.buffer.readline
def find_root(root_dict, x):
L = []
while x != root_dict[x]:
L.append(x)
x = root_dict[x]
for y in L:
root_dict[y] = x
return x
def find_path(parent_dict, a, b):
L1 = [a]
L_set = {a: 0}
L2 = [b]
whi... | py |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong 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 memor... | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | import os,sys
from random import randint, shuffle
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math
# Fast... | py |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the followi... | [
"dp",
"greedy",
"strings"
] | import sys
from collections import defaultdict
import bisect
def f(s,t):
A=defaultdict(list)
S=set(s)
T=set(t)
for i in T:
if i not in S:
return -1
n=len(s)
for i in range(n):
A[s[i]].append(i)
i=0
j=0
U=len(t)
ans=1
while j<U:
... | py |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, ... | [
"math",
"strings"
] | import math
import random
from collections import Counter, deque
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import heapq
from copy import deepcopy
def S():
return sys.stdin.readline().split()
def I():
return [int(i) for i i... | py |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) an... | [
"geometry",
"greedy",
"math",
"number theory"
] | def main():
t = int(input())
anss = [False] * t
for it in range(t):
n, m = map(int, input().split())
anss[it] = n % m == 0
for ans in anss:
print('YES' if ans else 'NO')
main()
| py |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the nu... | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | #OMM NAMH SHIVAY
#JAI SHREE RAM
import sys,math,heapq,queue
from functools import cmp_to_key
fast_input=sys.stdin.readline
for _ in range(int(fast_input())):
n,m=map(int,fast_input().split())
zero=n-m
equal=zero//(m+1)
rem=zero%(m+1)
ans=n*(n+1)//2
ans-=rem*(equal+1)*(equal+2)//2 ... | py |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be ... | [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | import io
import os
from collections import Counter, defaultdict, deque
# From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the segment tree with data"""
self._default =... | py |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-... | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | t=int(input())
while(t>0):
n,k=map(int,input().split())
l=list(map(int,input().split()))
bit=[0 for i in range(60)]
for x in l:
for i in range(60):
bit[i] += x%k
x=x//k
ans=True
for i in bit:
if(i>1):
ans=False
... | py |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re... | [
"brute force",
"combinatorics",
"math",
"number theory"
] | import copy
import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
import math
import heapq
import bisect
import collections
def ceil(a, b):
return (a + b - 1) // b
BUFSIZE = 8192
inf = float('inf')
class FastIO(IOBase):
newlines = 0
def _... | py |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the followi... | [
"dp",
"greedy",
"strings"
] | import sys
from bisect import bisect_right, bisect_left
import os
import sys
from io import BytesIO, IOBase
from math import factorial, floor, sqrt, inf
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
... | py |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, yo... | [
"greedy",
"math",
"number theory"
] | t=int(input())
for x in range(t):
n=int(input())
i=2
a=[]
while(len(a)<2 and i*i<n):
if n%i==0:
n=n//i
a.append(i)
i=i+1
if len(a)==2 and n not in a:
print("YES")
print(n,*a)
else:
print("NO")
| py |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between ... | [
"greedy",
"implementation",
"math"
] | # Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
def main():
n,m=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(n)]
ans=0
for i in range(m):
b=Counter()
... | py |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then... | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | import sys
from array import array
from collections import deque
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda dtype: [dtype(x) for x in input().split()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
Mint, Mlong = 2 ** 31 - 1, 2 ** 63 - 1
out, tests = [... | py |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ... | [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | import gc
import heapq
import itertools
import math
from collections import Counter, deque, defaultdict
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import threading
from heapq import *
from fractions import Fraction
import bisect
def S... | py |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-... | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | def solve():
n, k = read_ints()
aseq = read_ints()
amax = max(aseq)
length = 0
while amax > 0:
amax //= k
length += 1
all_powers = []
for i, ai in enumerate(aseq):
ai_copy = ai
powers = []
while ai_copy > 0:
powers.append(a... | py |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)L... | [
"brute force",
"math",
"number theory"
] | x=int(input())
ans=[1,x]
from math import lcm
for i in range(1,int(x**0.5)+1):
if x%i==0:
if lcm(i,x//i)==x:
if max(ans)>max(i,x//i):
ans=[i,x//i]
print(*ans) | py |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart in... | [
"constructive algorithms",
"math",
"ternary search"
] | R = lambda: list(map(int,input().split()));n,m,p=R();a,b=R(),R();i=0;j=0
while a[i]%p==0:i+=1
while b[j]%p==0:j+=1
print(i+j) | py |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this... | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | from collections import deque
import sys
input=sys.stdin.readline
def make_mf():
res=[-1]*(mxa+5)
ptoi=[0]*(mxa+5)
pn=1
for i in range(2,mxa+5):
if res[i]==-1:
res[i]=i
ptoi[i]=pn
pn+=1
for j in range(i**2,mxa+5,i):
i... | py |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constructio... | [
"brute force",
"data structures",
"dp",
"greedy"
] | import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lam... | py |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord... | [
"greedy",
"implementation",
"sortings"
] | numTests = int(input())
for _ in range(numTests):
n = int(input())
bucket1 = []
bucket2 = []
skill = list(map(int, input().split()))
skill.sort()
print(abs(skill[n] - skill[n-1]))
| py |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are an... | [
"greedy",
"implementation"
] | import sys
import math
from collections import defaultdict,Counter,deque
input = sys.stdin.readline
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, ... | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.