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
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfe...
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
from collections import deque import sys n,m,k = map(int,sys.stdin.readline().split()) a = list(map(int,sys.stdin.readline().split())) g = [[] for _ in range(n+1)] for _ in range(m): x,y = map(int,sys.stdin.readline().split()) g[x].append(y) g[y].append(x) def bfs(start): hold = [0]*...
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" ]
a= int(input()) b = input() print(a+1)
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 = map(int,input().split()) s = input().split() t = input().split() q = int(input()) for z in range(q): x = int(input()) - 1 print(s[x % n] + t[x % 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 def bfs(i,j): q=deque([(i,j)]) while q: i,j=q.popleft() for a,b,d in [(i+1,j,'U'),(i-1,j,'D'),(i,j+1,'L'),(i,j-1,'R')]: if a==-1 or a==n or b==-1 or b==n or v[a][b]: continue if m[a][b]==m[i][j]: v[a][...
py
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo...
[ "data structures", "divide and conquer", "implementation", "sortings" ]
from sys import stdin input=lambda :stdin.readline()[:-1] class segtree(): def __init__(self,init,func,ide): self.n=len(init) self.func=func self.ide=ide self.size=1<<(self.n-1).bit_length() self.tree=[self.ide for i in range(2*self.size)] for i in range(self.n): self.tree[se...
py
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arrange...
[ "dfs and similar", "greedy", "implementation" ]
import string def solve(): G=int(input()) for H in range(G): E=input().strip();A=[];A.append(E[0]);C=0;D=set(A);F=False for B in E[1:]: if C>0 and B==A[C-1]:C-=1 elif C<len(A)-1 and B==A[C+1]:C+=1 elif C==len(A)-1 and B not in D:A.append(B);D.add(B);C+=1 elif C==0 and B not in D:A=[B]+A;D.add...
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
1295
D
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.I...
[ "math", "number theory" ]
import math def __gcd(a,b): return (a if b == 0 else __gcd(b,a % b)) def phi(val): ret = 1 for i in range(2,int(math.sqrt(val)) + 1): if val % i == 0: c = 0 while val % i == 0: val //= i c += 1 ret *= (i - 1) ...
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" ]
import sys readline = sys.stdin.readline class UF(): def __init__(self, num): self.par = [-1]*num self.weight = [0]*num def find(self, x): stack = [] while self.par[x] >= 0: stack.append(x) x = self.par[x] for xi in stack: s...
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" ]
print(sum([1/i for i in range(1,int(input())+1)]))
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" ]
import sys a,b=map(int,input().split()) cnt=0 if(b==a): print(0) sys.exit() if(b==0 or a==0): print(-1) sys.exit() if(a>b): print(-1) sys.exit() divi=b//a while(divi%2==0): divi=divi//2 cnt+=1 while(divi%3==0): divi=divi//3 cnt+=1 if(b%a!=0): cnt=-1 if(di...
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
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" ]
import math def functie_divizori(numar): dictionar={} matrice=[] if numar==1: a=[1]*2 a.append(0) a.append(0) matrice.append(a) else: for j in range(1,math.floor(numar**(1/2))+1): # print("j=",j) if numar%j==0: tupleta=[] # print(dictionar) ...
py
1325
F
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph w...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
import sys if __name__=="__main__": n,m=sys.stdin.readline().strip().split(" ") n=int(n) m=int(m) part=int((n-1)**0.5+1) d={} e={} for i in range(m): x,y=sys.stdin.readline().strip().split(" ") y=int(y) x=int(x) if x not in e: e[x]=[] if y not in e: e[y]=[] e[x].append(y) e[y].append(x) ...
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" ]
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().spl...
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" ]
#! /bin/env python3 # perhaps... Life is full of puzzles def main(): n, q = map(int, input().split(' ')) v = [[0 for i in range(n+5)] \ for j in range(3)] # solve c = 0 for _ in range(q): x, y = map(int, input().split(' ')) s = v[x][y] cnt = 0 ...
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" ]
def solve(): for _ in range(int(input())): a, b, x, y = map(int, input().split()) num1 = x * b num2 = y * a num3 = (a - x - 1) * b num4 = (b - y - 1) * a print(max(num1, num2, num3, num4)) solve()
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 random def transformare_baza(numar,baza): vector_transformare=[0]*40 transformare="" while numar>=baza: rest=numar%baza numar=numar//baza transformare+=str(rest) transformare+=str(numar) noua_baza=transformare[::-1] nou_string=(40-len(noua_baza))*'0' noua_baza=nou_strin...
py
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossib...
[ "greedy" ]
for i in range(int(input())): n=int(input()) arr=list(map(int,input().split())) a=[] i=0 t=0 while(len(a)!=(2*n)): if(t==0): r=arr[i] a.append(arr[i]) if (r+1 not in arr) and (r+1 not in a): a.append(r+1) i+=1 ...
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" ]
for _ in range(int(input())): N,K = map(int,input().split()) A = list(map(int,input().split())) check = [0]*101 ans = 'Yes' for i in A: for b in range(61,-1,-1): if K**b<=i: i -= K**b check[b] += 1 if i!=0: ans = "No" ...
py
1325
B
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longe...
[ "greedy", "implementation" ]
t=int(input()) for _ in range(t): n=int(input()) a=set(map(int,input().split())) print(len(a))
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
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of...
[ "implementation", "strings" ]
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
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" ]
import random, sys, os, math, gc from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations, product from heapq import nsmallest, nlargest, heapify, heappop, heappush from io import BytesIO, IOBase from copy ...
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 input = sys.stdin.buffer.readline from collections import deque def countingSort(arr, exp1): n = len(arr) output = [0] * (n) count = [0] * (10) for i in range(0, n): index = arr[i] // exp1 count[index % 10] += 1 for i in range(1, 10): count[i] += ...
py
1285
D
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, whe...
[ "bitmasks", "brute force", "dfs and similar", "divide and conquer", "dp", "greedy", "strings", "trees" ]
def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) def binary(n): return bin(n)[2:] def calculate_answer(numbers, position): # If we check all the...
py
1301
E
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be des...
[ "binary search", "data structures", "dp", "implementation" ]
import io, os import sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n,m,q=map(int,input().split()) C=[input().strip() for i in range(n)] ATABLE=[[0]*m for i in range(n)] for i in range(n-1): for j in range(m-1): if C[i][j]==82 and C[i+1][j]==89 and C[i][j+1]==71 and C[i+1][j+1...
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 # Testing out some really weird behaviours in pypy class RangeQuery: def __init__(self, data, func=min): self.func = func self._data = _data = [list(data)] i, n = 1, len(_data[0]) while 2 * i <= n: prev = _data[-1] _data.append([func(p...
py
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of ...
[ "bitmasks", "dp", "greedy", "sortings" ]
import sys input = sys.stdin.buffer.readline def process(A, S, k): n = len(A) p = len(S[0]) pairs = [] for x in range(2**p-1, -1, -1): b = sum(map(int, bin(x)[2:])) for j in range(p): if x&(2**j)==0: pairs.append([x, j, b]) A2 = [] for i...
py
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo...
[ "data structures", "divide and conquer", "implementation", "sortings" ]
class BIT: def __init__(self, n): self.n = n self.bit = [0]*(self.n+1) # 1-indexed def init(self, init_val): for i, v in enumerate(init_val): self.add(i, v) def add(self, i, x): # i: 0-indexed i += 1 # to 1-indexed while i <= self.n: ...
py
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of...
[ "implementation", "strings" ]
I=input exec(int(I())*"print('NYOE S'[all(y in x for*x,y in zip(I(),I(),I()))::2]);")
py
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons ...
[ "brute force" ]
# Thank God that I'm not you. from collections import Counter, deque import heapq import itertools import math import random import sys from types import GeneratorType; def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else:...
py
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distrib...
[ "constructive algorithms", "greedy", "implementation", "math" ]
import math n,m=map(int,input().split()) good=1 if n%2==0: if m>(n/2)*(n/2-1): print(-1) good=0 if n%2==1: if m>((n-1)/2)**2: print(-1) good=0 arr=[] leftover=0 if good==1: if n==1: print(1) else: if int(math.sqrt(m))*(int(math.sqrt(m))+1)<=m: ...
py
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array m...
[ "constructive algorithms", "sortings" ]
t = int(input()) for _ in range(t): n = input() a = list(map(lambda x: int(x), input().split())) a.sort() a = list(reversed(a)) for i in a:print(i , end=" " if len(a) > 1 else "") print("")
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" ]
def solve(): s, t = input(), input() st1, st2 = set(s), set(t) for k in st2: if k not in st1: print(-1); return n, m = len(s), len(t) dp = [[n]*26 for _ in range(n+1)] for i in range(n-1, -1, -1): dp[i] = dp[i+1][:] dp[i][ord(s[i])-ord('a')] = i ...
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" ]
import sys import io, os input = sys.stdin.buffer.readline #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) A = [list(map(int, input().split())) for i in range(n)] #B = [[0]*m for i in range(n)] #for i in range(n): #for j in range(m): #B[i][j] = i*m+j ...
py
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, a...
[ "greedy" ]
n = int(input()) a = list(map(int , input().split())) b = list(map(int , input().split())) k = 0 k1 = 0 for i in range(0 , len(a)): if a[i] > b[i]: k += 1 if a[i] < b[i]: k1 += 1 if k == 0: print(-1) exit() k1 = k1 // k + 1 print(k1)
py
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "...
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
n,m=map(int,input().split()) c=False c=set() rez=0 h=[] for i in range (n): l=input() if l[::-1] in c: c.remove(l[::-1]) h.append(l) rez+=2*m else: c.add(l) s=rez//m//2-1 t=None for i in c: if i[::-1] == i: rez+=m t=i break pr...
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" ]
from sys import stdin input = stdin.readline for case in range(int(input())): n, m = map(int, input().split()) prev_min, prev_max, prev_t, ans = m, m, 0, True for line in range(n): t, l, h = map(int, input().split()) theo_min, theo_max = prev_min - (t - prev_t), prev_max + (t - prev_t) ...
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 input = sys.stdin.buffer.readline from collections import deque def countingSort(arr, exp1): n = len(arr) output = [0] * (n) count = [0] * (10) for i in range(0, n): index = arr[i] // exp1 count[index % 10] += 1 for i in range(1, 10): count[i] += ...
py
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse...
[ "brute force", "dp", "greedy", "implementation" ]
for _ in[0]*int(input()): n=input() a=[*map(int,input().split())] if a[0]%2==0: print('1\n1') elif n=='1': print(-1) elif a[1]%2==0: print('1\n2') else: print('2\n1 2')
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 deque,Counter,OrderedDict from math import * import sys import random from bisect import * from functools import reduce from sys import stdin from heapq import * import copy import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines...
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 heapq import sys input = sys.stdin.buffer.readline def process(A, T): d = {} n = len(A) for i in range(n): a = A[i] t = T[i] if a not in d: d[a] = [] d[a].append(t) curr = [] curr_S = 0 m = min(d) answer = 0 L = sorted...
py
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, a...
[ "greedy" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) r = list(map(int, input().split())) b = list(map(int, input().split())) c1, c2 = 0, 0 for i, j in zip(r, b): if not i ^ j: continue if i: c1 += 1 else: c2 += 1 if not c1: ...
py
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so so...
[ "binary search", "greedy", "ternary search" ]
# 13:58- import sys input = lambda: sys.stdin.readline().rstrip() for _ in range(int(input())): N = int(input()) A = list(map(int, input().split())) l,r = float('inf'),-1 m = 0 cur = 0 for i in range(N): if A[i]!=-1: cur = A[i] if i-1>=0: if A[i-1]==-1: l = min(l,A[i]) r =...
py
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (in...
[ "combinatorics", "dp" ]
mod=int(1e9+7) def read(): return [int(i) for i in input().split()] def main(): n,m=read() dp=[[0 for i in range(n+2)] for i in range(n+2)] for i in range(1,n+1): for j in range(i,n+1): dp[i][j]=1 for _ in range(m-1): for i in range(1,n+1): for j in range(n,i-1,-1): dp[i][j]=(dp[i][...
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 from math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm from collections import deque, Counter, OrderedDict, defaultdict from heapq import heapify, heappush, heappop #sys.setrecursionlimit(10**5) from functools import lru_cache #@lru_cache(None) #=====================================...
py
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of...
[ "implementation", "strings" ]
result="" for i in range(0,int(input())): a=input() b=input() c=input() flag=True n=0 for k in range(0,len(a)): if (a[k]==c[k]) or (b[k]==c[k]): n+=1 elif (a[k]==b[k]): n+=2 else: flag=False break if flag and n<=len(a): result+="YES\n" else: result+="NO\n" print(result....
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" ]
import math import random #n,m,k=list(map(int, input().split())) #cazuri=int(input()) n,a,b,k=list(map(int,input().split())) bloc=list(map(int,input().split())) #n=500000 #bloc=[] #for z in range(n): # bloc.append(random.randint(1,10**9)) cate=0 suma=a+b resturi=[] for i in range(n): rest=bloc...
py
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are righ...
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
from collections import defaultdict, deque import heapq import sys input = sys.stdin.readline def bfs(s): q = deque() q.append(s) ans = [0] * (n - 1) d = defaultdict(lambda : 0) d[s] = r while q: i = q.popleft() for j, c in G[i]: if not ans[c]: ...
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" ]
import os import sys from io import BytesIO, IOBase from collections import Counter import math as mt BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" no...
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" ]
n = int(input()) nums = list(map(int, input().split())) ans = float('-inf') idx = 0 for piv in range(len(nums)): tot = nums[piv] m = tot for i in range(piv-1, -1, -1): m = min(m, nums[i]) tot += m m = nums[piv] for i in range(piv+1, len(nums)): m = min(m, nums...
py
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip...
[ "math" ]
t = int(input()) for i in range(t): n, g, b = map(int, input().split()) ng = (n + 1) // 2 tg = ng // g * (b + g) if ng % g == 0: tg -= b else: tg += ng % g print(max(n, tg))
py
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard 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 a...
[ "data structures", "dp" ]
import sys, collections, math,bisect input = sys.stdin.readline n = int(input()) s = input().rstrip('\n') max_v = 0 dp = [0] * 26 ans = [0] * n for i in range(n): temp = 0 for j in range(26): if j > ord(s[i]) - ord('a'): temp = max(dp[j],temp) ans[i] = temp + 1 max_v =...
py
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distrib...
[ "constructive algorithms", "greedy", "implementation", "math" ]
# https://codeforces.com/problemset/problem/1305/E def gen_sequence(size, balance): result = [] for i in range(1, size + 1): triple_count = (i - 1) >> 1 if triple_count <= balance: result.append(i) balance -= triple_count else: break if len(resu...
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 math 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 def S(): return sys.stdin.readline().split() def I(): return [int(i) for i in sys.stdin.readline().split()] def I...
py
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse...
[ "brute force", "dp", "greedy", "implementation" ]
for _ in range(int(input())): n = int(input()) lis = list(map(int,input().split())) summ = 0 oc=0 for i in range(n): if lis[i]%2==0: oc=0 print(1,i+1,sep = "\n") break else: oc+=1 if oc==2: print(2) ...
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 import math from collections import * from functools import cmp_to_key mod=998244353 def get_ints(): return map(int, sys.stdin.readline().strip().split()) #test=int(input()) #while test: #test-=1 n=int(input()) a=list(get_ints()) t=-float("inf") f=[0 for i in range(n)] for i in range(n): ...
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 io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import defaultdict,deque def bfs(node): vis[node]=1 q=deque([node]) order.append(node) while q: cur=q.popleft() for j in edge[cur]: if vis[j]==0: child[cur].a...
py
1295
A
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit...
[ "greedy" ]
for i in range(int(input())): a = int(input()) if(a%2==0): print("1"*(a//2)) else: print('7'+'1'*((a-3)//2))
py
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all studen...
[ "implementation" ]
for _ in range(int(input())): n, m = list(map(int, input().split(' '))) a = sum(list(map(int, input().split(' ')))) print(a) if a < m else print(m)
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
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" ]
print(sum(1/(i+1)for i in range(int(input()))))
py
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A t...
[ "brute force", "constructive algorithms", "trees" ]
for tests in range(int(input())): n, d = map(int,input().split()) upper_bound, lower_bound, lv = n * (n - 1) // 2, 0, 0 for i in range(1, n + 1): if not(i & (i - 1)): lv += 1 lower_bound += lv - 1 if not(d in range(lower_bound, upper_bound + 1)): print("NO") ...
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" ]
from math import gcd max_val = 10**5+1 # Se leen los datos n = input() arr = [ int(i) for i in input().split()] #Lista de Listas que contendrá los divisores de cada uno de los números en el intervalo [1,max_val] div = [[] for _ in range(max_val)] #Lista que contendrá el precalculo de la función de Mobius en el inte...
py
13
E
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. ...
[ "data structures", "dsu" ]
import sys input = sys.stdin.readline n, m = map(int, input().split()) p = list(map(int, input().split())) BLOCK_LENGTH = 400 block = [i//BLOCK_LENGTH for i in range(n)] jumps = [0] * n end = [0] * n for i in range(n - 1, -1, -1): nex = i + p[i] if nex >= n: jumps[i] = 1 end[...
py
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A t...
[ "brute force", "constructive algorithms", "trees" ]
t=int(input()) import math as m def print_tree(l): t=[{'p':None, 'c':[]} for i in range(sum(l))] l2={i:[] for i in range(len(l))} j=0 for i in range(sum(l)): l2[j].append(i+1) if len(l2[j])==l[j]: j+=1 for i in range(1,len(l)): p=0 for n in l2[i]: ...
py
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you sepa...
[ "data structures", "divide and conquer" ]
import sys readline = sys.stdin.readline from itertools import accumulate class Lazysegtree: #RAQ def __init__(self, A, intv, initialize = True, segf = min): #区間は 1-indexed で管理 self.N = len(A) self.N0 = 2**(self.N-1).bit_length() self.intv = intv self.segf = ...
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" ]
a=input() print(len(input())+1)
py
1304
D
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog⁡n) time for a sequence of length nn. He wants to test himself if he can implement it correctly,...
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
import sys input = sys.stdin.readline t = int(input()) ans = [] for _ in range(t): n, s = input().rstrip().split() n = int(n) s = list(s) x = [0] for i in range(n - 1): if s[i] == ">": x.append(i + 1) x.append(n) p = [0] * n u = 1 for i in range(l...
py
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+...
[ "dfs and similar", "sortings" ]
for _ in range(int(input())): n, m = map(int, input().split()) arr = list(map(int, input().split(' '))) nums = list(map(int, input().split(' '))) while True: flag = False for i in range(m): if arr[nums[i] - 1] > arr[nums[i]]: arr[nums[i] - 1], arr[nums[i...
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" ]
t = int(input()) for i in range(t): n = int(input()) *a, = map(int, input().split()) *b, = map(int, input().split()) a.sort() b.sort() print(*a) print(*b)
py
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array m...
[ "constructive algorithms", "sortings" ]
############################## # author: oneku # # trying to solve problems # ############################## # Bismillah import sys import os from functools import reduce from io import BytesIO, IOBase from typing import List from bisect import bisect, bisect_left, bisect_right # from ...
py
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shape...
[ "brute force", "data structures", "implementation" ]
n=int(input().split()[0]) s=set() r=0 for _ in[0]*n: t=*map(ord,input()), for x in s:r+=(*(u^(u!=v)*(66^v)for u,v in zip(x,t)),)in s s|={t} print(r//2)
py
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tr...
[ "binary search", "dp", "greedy", "strings" ]
for i in range(int(input())): a,b,p=map(int, input().split()) ro=str(input()) road=list(ro) l=len(road) node=[] bol=(road[-1]=="A") if bol: cou=0 node.append([l-1,1]) else: cou=1 node.append([l-1,0]) for j in range(l-1,0,-1): if r...
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" ]
T = int(input()) for _ in range(T): n = int(input()) A = sorted(list(map(int, input().split()))) B = sorted(list(map(int, input().split()))) print(*A) print(*B)
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
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 sys import stdin from math import ceil inp = stdin.readline h, n = map(int, inp().split()) arr = [int(x) for x in inp().split()] change = sum(arr) ma = 0 count = 0 poi = [] hp = [] for i, c in enumerate(arr): count += c if count < ma: poi.append(i) hp.append(count) ...
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" ]
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): n,m,k = map(int,input().split()) if k > 4*n*m-2*m-2*n: print('NO') exit() print('YES') if n == 1: step = [(m-1,'R'),(m-1,'L')] elif m == 1: ...
py
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse...
[ "brute force", "dp", "greedy", "implementation" ]
import os os.system("cls") # clear screen # Debug mode (color output green) if os.getcwd().endswith("codeforces_py"): from colorama import Fore, Style import builtins def print(*args, **kwargs): builtins.print(Fore.GREEN, end="") builtins.print(*args, **kwargs) builtins.p...
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" ]
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, in...
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" ]
# ЛАсСД 6 - Небоскребы def up_east(aaa,n): st=[0] bbb=[0]*(n+2) xxx=[0] for i in range (1,n+1): a=aaa[i] if a>=aaa[st[-1]] : bbb[i]=bbb[i-1]+a else: while a<aaa[st[-1]] : #st всегда не пуст!!! j=st.pop() j=st[-1] ...
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 import math input = sys.stdin.readline sys.setrecursionlimit(10 ** 4 + 5) test = False mod1, mod2 = 10 ** 9 + 7, 998244353 inf = 10 ** 16 + 5 lim = 10 ** 5 + 5 def test_case(): x0, y0, ax, ay, bx, by = map(int, input().split()) xs, ys, t = map(int, input().split()) x, y = [x0], [y0] w...
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 input = sys.stdin.buffer.readline from collections import deque def radix_sort(a): l = len(a) mx = max(a) m = 0 while mx > 0: mx = mx // 10 m += 1 for i in range (m): b = [[] for _ in range (10)] e = pow(10, i) for j in 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" ]
import math n = int(input()) for i in range(1,int(n**0.5)+1): if n%i==0: if math.gcd(n//i,i) == 1: res = i print(res,n//res)
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" ]
# ======== author: kuanc (@kuantweets) | created: 08/04/22 01:25:01 ======== # from sys import stdin, stderr, stdout, setrecursionlimit from bisect import bisect_left, bisect_right from collections import defaultdict, deque, Counter from itertools import accumulate, combinations, permuta...
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 input = sys.stdin.buffer.readline from functools import reduce def __flatten(A): return reduce(lambda x, y: x+y, A) def radix(a): digits = len(str(max(a))) for i in range (digits): b = [[] for _ in range (10)] e = pow(10, i) for j in a: num = (j/...
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" ]
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
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s...
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
import sys input = sys.stdin.readline from heapq import heappop, heappush for _ in range(int(input())): n = int(input()) s = input()[:-1] h = [] for i in range(n): heappush(h, (s[i:] + s[:i][::-1], i+1) if (n-i) & 1 else (s[i:] + s[:i], i+1)) a, b = heappop(h) print(a) p...
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" ]
from collections import deque, defaultdict import sys input = sys.stdin.readline def bfs(s): q = deque() q.append(s) visit = [0] * (n + 1) visit[s] = 1 parent[s] = -1 e[s] = -1 while q: i = q.popleft() for j, c in G[i]: if not visit[j]: ...
py
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn l...
[ "binary search", "data structures", "hashing", "sortings" ]
import sys input = lambda: sys.stdin.readline().rstrip() ke = 133333333 pp = 1000000000001003 def rand(): global ke ke = ke ** 2 % pp return ((ke >> 10) % (1<<20)) + (1<<20) N = int(input()) W = [rand() for _ in range(N)] AL, AR, BL, BR = [], [], [], [] for i in range(N): a, b, c, ...
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" ]
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
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) b = list(map(int, input().split())) l = pow(10, 6) s = [0] * l for i in range(n): s[b[i] - i] += b[i] ans = max(s) print(ans)
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" ]
from sys import stdin input=lambda :stdin.readline()[:-1] n,a,b,k=map(int,input().split()) h=list(map(int,input().split())) ans=0 c=[] for i in h: r=i%(a+b) if 0<r<=a: ans+=1 continue if r==0: r+=a+b c.append((r+a-1)//a-1) c.sort() for i in c: if k>=i: ans+=1 k-=i pr...
py
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo...
[ "data structures", "divide and conquer", "implementation", "sortings" ]
from collections import deque, defaultdict, Counter from heapq import heappush, heappop, heapify from math import inf, sqrt, ceil, log2 from functools import lru_cache from itertools import accumulate, combinations, permutations, product from typing import List from bisect import bisect_left, bisect_right import...
py
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (in...
[ "combinatorics", "dp" ]
n, m = list(map(int, input().split())) MOD = 10**9 + 7 # since indexes are 0 based, we will use n+1 and m+1 in the dp arrays. dp_a = [[0 for _ in range(n)] for _ in range(m)] dp_b = [[0 for _ in range(n)] for _ in range(m)] # setting the base state for j in range(0, n): dp_a[0][j] = 1 # populating the...
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" ]
''' Case 1: All L is ignored Case 2: All R is ignored LRLR Range from [-2,2] positions = 2--2 + 1 Count R and L print(R+L + 1) ''' n=int(input()) s = input().strip() L = 0 R = 0 for c in s: if c == "L": L += 1 else: R += 1 print(R + L + 1)
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 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
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 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
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" ]
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**5 + 1)] # def SieveOfEratosthenes(n): # p = 2 # while (p * p <...
py