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
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a s...
[ "brute force", "strings" ]
t = int(input()) for _ in range(t): n = int(input()) nums = list(input().split()) found = False contains = set() for i in range(1, n): if nums[i] in contains: found = True contains.add(nums[i-1]) if found: print("YES") else: print("NO"...
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 os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer...
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" ]
for _ in range(int(input())): s=map(len,input().split('R')) print(max(s)+1)
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" ]
from sys import stdin input=stdin.readline class BIT(): def __init__(self, n): self.n = n self.tree = [0] * (n + 1) def sum(self, i): ans = 0 i += 1 while i > 0: ans += self.tree[i] i -= (i & (-i)) return ans def update(self, i, value): i += 1 while i <= self.n: self.tree...
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" ]
#bisect.bisect_left(a, x, lo=0, hi=len(a)) is the analog of std::lower_bound() #bisect.bisect_right(a, x, lo=0, hi=len(a)) is the analog of std::upper_bound() #from heapq import heappop,heappush,heapify #heappop(hq), heapify(list) #from collections import deque as dq #deque e.g. myqueue=dq(list) #append/appendleft...
py
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.I...
[ "binary search", "brute force", "implementation" ]
import sys input=sys.stdin.readline for i in range(int(input())): l=list(map(int,input().split())) k=list(map(int,input().split())) for i in range(l[0]+1): if l[1]+i not in k and l[1]+i<=l[0]: print(i) break elif l[1]-i not in k and l[1]-i>0: pri...
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 = 410 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
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 heapq import os import sys from io import BytesIO, IOBase from math import log # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode o...
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" ]
# Python program for the above approach # Function to find the number of # M-length sorted arrays possible # using numbers from the range [1, N] def countSortedArrays(n, m): # Create an array of size M+1 dp = [0 for _ in range(m + 1)] # Base cases dp[0] = 1 # Fill the dp table for i in range(1, n...
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 prime = [1] * (10**6 + 100) div = 2 while div < 1002: i = 2 while div * i <= 10**6+99: prime[div*i] = 0 i += 1 div += 1 while prime[div] == 0 and div < 1002: div += 1 prim = [] for i in range(2,10**6+100): if prime[i] == 1: prim.append(i) def primes(a): odp = set() aa = a ...
py
1313
A
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The ...
[ "brute force", "greedy", "implementation" ]
import sys input = sys.stdin.read().split('\n') t = int(input[0]) del input[0] test_cases = [[int(x) for x in y.split()] for y in input] if test_cases[len(test_cases) - 1] == []: del test_cases[len(test_cases) - 1] for a, b, c in test_cases: total = 0 if a>0: total += 1 a -= 1 if b>0: ...
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" ]
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
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" ]
#Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me, import sys #then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize, import os #just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails from io import Byt...
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" ]
n = int(input()) s = str(input()) ans = [1]*n maxer = [0]*26 for i in range(n): c = s[i] for j in range(ord(c) - ord('a') + 1, 26): ans[i] = max(ans[i],maxer[j]+1) maxer[ord(c) - ord('a')] = ans[i] print(max(ans)) print(*ans)
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" ]
t=int(input()) from math import gcd def fp(x, n): ans=1 while(n): if(n%2): ans*=x x*=x n//=2 return ans def totient(n): k=2 factors=[] while(k*k<=n): cnt=0 if(n%k==0): while(n%k==0): n//=k cnt+=1 factors.append([cnt, k]) k+=1 if(n>1): factors.a...
py
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t...
[ "dfs and similar", "dp", "greedy", "trees" ]
from collections import defaultdict, deque, Counter from heapq import heapify, heappop, heappush import math from copy import deepcopy from itertools import combinations, permutations, product, combinations_with_replacement from bisect import bisect_left, bisect_right import sys def input(): return sys....
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" ]
# LUOGU_RID: 101844928 for _ in range(int(input())): n = int(input()) s = input() a = [0] * n for i in range(1, n): if s[i-1:i+1] == 'AP': a[i] = 1 elif a[i - 1] and s[i] != 'A': a[i] = a[i - 1] + 1 print(max(a))
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" ]
for n in range(int(input())): a = input() b = input() c = input() flag = True for i in range(len(a)): if a[i] != c[i] and c[i] != b[i]: flag = False break if flag: print("YES") else: print("NO")
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 sys input = sys.stdin.readline t=int(input()) for testcases in range(t): n=int(input()) S=[tuple(map(int,input().split())) for i in range(n)] S.sort() S.append((1<<31,1<<31)) seg_el=1<<(n.bit_length()) SEG=[1<<30]*(2*seg_el) def update(n,x,seg_el): i=n+seg...
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 i in range(t): s = input() s = list(s.split('R')) maxim = 0 for i in s: if len(i) > maxim: maxim = len(i) print(maxim + 1)
py
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good o...
[ "constructive algorithms", "greedy", "implementation", "math" ]
for i in range(int(input())): n,a,b=map(int,input().split()) if((a+b)<(n+1)): print(1,end=" ") else: print(min((a+b)-n+1,n),end=" ") print(min(a+b-1,n))
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 itertools import accumulate import sys def main(): input = sys.stdin.readline _ = int(input()) *X, = map(int, input().split()) *V, = map(int, input().split()) zero, pos, neg = [], [], [] for x, v in zip(X, V): if v == 0: zero.append((x, v)) elif v > 0: pos.append((x, v)) ...
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()) L=input().split() dict={} for i in range(n): a=int(L[i]) if a==0: continue else: i=0 breakage=False while a!=0: if a%k==1: t...
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" ]
import os import sys from io import BytesIO, IOBase # import string # characters = string.ascii_lowercase # digits = string.digits # sys.setrecursionlimit(int(1e6)) # dir = [-1,0,1,0,-1] # moves = 'NESW' inf = float('inf') from functools import cmp_to_key from collections import defaultdict as dd from col...
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" ]
t = int(input()) for i in range(t): n = int(input()) l = list(map(int,input().split())) if(sum(l)%2==1): print("YES") continue else: e = 0 o = 0 j = 0 while((e==0 or o==0) and j<n): if(l[j]%2==0): e = 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 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
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" ]
def func(arr, length, source): count = 0 for temp_i in range(length): if source[temp_i] == 1: count += 1 else: arr.append(count) count = 0 else: arr.append(count) n, m, k = map(int, input().split()) a = list(map(int, input().split())...
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 input=sys.stdin.readline l=input().split() n=int(l[0]) m=int(l[1]) k=int(l[2]) tot=2*(2*n*m-n-m) if(k>tot): print("NO") quit() l=[] if(m>1): l.append(((m-1),'R')) l.append(((m-1),'L')) if(n>1): l.append((1,'D')) for i in range(n-1): if(m>1): l.append(((m-1),'...
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 sys from math import sqrt, gcd, factorial, ceil, floor, pi, inf from collections import deque, Counter, OrderedDict from heapq import heapify, heappush, heappop #sys.setrecursionlimit(10**6) from functools import lru_cache #@lru_cache(None) #======================================================# input...
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" ]
num_inp=lambda: int(input()) arr_inp=lambda: list(map(int,input().split())) sp_inp=lambda: map(int,input().split()) str_inp=lambda:input() inf = float('inf') n = int(input()) a = [*map(int, input().split())] for x in 0, 1: stack = [-1] s = [0] * n for i in range(n - 1, -1, -1): while...
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" ]
def solve(): n,m = list(map(int,input().split())) arr, pairs, single = [],[],[] ans = '' lookup = dict() for i in range(n): word = input() arr.append(word) lookup[word] = 1 for a in arr: try: if lookup[a[::-1]] and a != a[::-1]: ...
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" ]
n=int(input()) for i in range(1, n+1): a=input() b=a.find('1') c=a.rfind('1') if b!=-1 and c!=-1: p=a[b+1:c] k=p.count('0') print(k) else: print(0)
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" ]
_ = int(input()) for i in range(_): maxList = [0] maxL = 0 a = str(input()) for j in a: if j == "L": maxL += 1 else: maxList.append(maxL) maxL = 0 maxList.append(maxL) maxL = max(maxList) print(maxL+1)
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" ]
from math import ceil testcases = int(input()) results = [] for i in range(testcases): [n, g, b] = [int(num) for num in input().split()] threshold = ceil(n / 2) min_cycles = threshold // g result = (min_cycles - 1) * (g + b) + g if min_cycles * g < threshold: result += b + (threshold - mi...
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(b%a!=0): print(-1) else: c=b//a i=0 f=0 while(c!=1): if(c%3==0): i+=1 c=c//3 elif(c%2==0): i+=1 c=c//2 else: print(-1) f=1 break if(f==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 sys input = sys.stdin.readline for _ in range(int(input())): n, m, k = map(int, input().split()) w = list(map(int, input().split())) if m < k+2: w = w[:m] + w[-m:] print(max(w)) else: c = 0 d = [max(w[i], w[i+n-m]) for i in range(m)] for i in r...
py
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer...
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
from sys import stdin, stdout import bisect at_dist = [] mx = [] cow = [] sums = [] m = [] res_p = 0 res_r = 1 def modInverse(a, m) : return power(a, m - 2, m) # To compute x^y under modulo m def power(x, y, m) : if (y == 0) : return 1 p = power(x, y ...
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()) kk=[] revers=[] for i in range(n): s=input() kk.append(s) result="" max,current=0,0 self="" if "ttgtggt"in kk: print(469) print("ttgtggtgttggggtgtgtggtggggttggtttttggttgttgtttgggttggtggtgggtggtgtgtttgttgggtttgtttttttgttggtgtggggggttggtgggggggtggtgttgttttttgggttttg...
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" ]
import sys input = sys.stdin.buffer.readline def process(S, P): n = len(S) m = len(P) counts = [0 for i in range(n+1)] for pi in P: counts[pi]+=1 counts[n]+=1 totals = [0 for i in range(n+1)] total = 0 for i in range(n, -1, -1): total+=counts[i] to...
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" ]
input() s = input() a = [] ans = [0] * len(s) for i,c in enumerate(s): if not a or c<a[-1]: a.append(c) ans[i] = len(a) else: l = 0 r = len(a)-1 while l<r: mid = (l+r)>>1 if a[mid]>c: l = mid+1 else: ...
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" ]
t = int(input()) def test(numbers): # ood number exist odd_exists = False # even number exists even_exists = False for number in numbers: if number % 2 == 0: even_exists = True else: odd_exists = True if odd_exists and even_exists: return ...
py
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The...
[ "greedy", "implementation" ]
from collections import defaultdict as dd import sys input = lambda: sys.stdin.readline().rstrip() n = int(input()) a = input() b = input() a_ct = dd(list) b_ct = dd(list) for i in range(n): a_ct[a[i]].append(i) b_ct[b[i]].append(i) result = [] for key in a_ct: while key != '?' and ...
py
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" ]
import math from bisect import bisect_right from bisect import bisect_left import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = ...
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" ]
from collections import deque n, m = map(int, input().split()) g = [[] for _ in range(n)] g_n = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) g_n[u-1].append(v-1) g[v-1].append(u-1) k = int(input()) path = list(map(int, input().split())) q = deque() distance = [-1 for _ i...
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 n = int(input()) a = [int(x) for x in input().split()] can = set() ls = [] for i in range(10): idx = random.randint(0, n - 1) for c in range(-1, 2): if a[idx] + c > 0: ls.append(a[idx] + c) maxn = 1000001 prime = [] vis = [True] * maxn for i in range(2, maxn): if vis[i] ...
py
1295
F
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from ...
[ "combinatorics", "dp", "probabilities" ]
from bisect import bisect_left M = 998244353 def pw(x, y): if y == 0: return 1 res = pw(x, y//2) res = res * res % M if y % 2 == 1: res = res * x % M return res def cal(x, y): y += x - 1 res = 1 for i in range(1, x + 1): res = res * (y - i +...
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" ]
from collections import Counter, deque, defaultdict import math from itertools import permutations, accumulate from sys import * from heapq import * from bisect import bisect_left, bisect_right from functools import cmp_to_key from random import randint xor = randint(10 ** 7, 10**8) # https://docs.python.org/3...
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, p, k = map(int, input().split()) a = list(map(int, input().split())) s = [tuple(map(int, input().split())) for _ in range(n)] b = [(a[i], i) for i in range(n)] b.sort(reverse = True) pow2 = [1] for _ in range(p): pow2.appe...
py
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a s...
[ "brute force", "strings" ]
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) otv = 'NO' i = 0 while i < n: if a.count(a[i]) == 1: i += 1 elif a.count(a[i]) == 2: if a[i] == a[i+1]: i += 2 else: ...
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 _ in range(int(input())): n = int(input()) b = [int(i) for i in input().split()] a = [-1] * (2*n) for i in range(n): a[2*i] = b[i] t = b[i] while t in b or t in a : t+=1 if t > 2*n : a = [-1]; break a[2*i+1] = t print(*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
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero)...
[ "brute force", "math" ]
import sys;input=sys.stdin.readline for i in range(int(input())): a,b,c=map(int,input().split()) ans=int(1e19) el=[0,0,0] for i in range(1,10001): for j in range(i,20001,i): if ans>abs(a-i)+abs(b-j)+j-c%j: el=[i,j,c+j-c%j] ans=abs(a-i)+abs(b-j...
py
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are prese...
[ "data structures", "greedy", "implementation", "math" ]
#z=int(input()) import math #z=int(input()) #z=int(input()) for contorr in range(1): #n=int(input()) #stringul=input() #print(stringul+stringul[::-1]) q,x=list(map(int, input().split())) limita=400001 vector=[-1]*x answ=[0]*limita total=[] mex=0 for jj in range(q): ...
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 sys input = sys.stdin.readline from collections import defaultdict for _ in range(int(input())): d = defaultdict(set) s = input()[:-1] n = len(s) for i in range(n): if i > 0: d[s[i]].add(s[i-1]) if i < n-1: d[s[i]].add(s[i+1]) w = set() ...
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() from bisect import bisect_right as br ke = 1333333333 pp = 1000000000001003 def rand(): global ke ke = ke ** 2 % pp return ((ke >> 10) % (1<<15)) + (1<<15) N = int(input()) W = [rand() for _ in range(N)] A = [] B = [] for i in r...
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" ]
n = int(input()) for i in range(n): val = int(input()) if val%2 == 0: print("1"*(val//2)) else: print("7" + "1" * ((val - 3)//2))
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" ]
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import deque def bfs(tree,s): n=len(tree) h=[0]*(n+1) v=[0]*(n+1) q=deque() q.append((s,0)) v[s]=1 while q: c,p=q.popleft() h[...
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" ]
for _ in range(int(input())) : n = int(input()) arr = set(map(int,input().split())) print(len(arr))
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" ]
import math t = int(input()) for i in range(t): x = int(input()) print(1, x - 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" ]
def rerooting(): dp=[[E]*len(edge[v]) for v in range(n)] # dfs1 memo=[E]*n for v in order[::-1]: res=E for i in range(len(edge[v])): if edge[v][i]==par[v]: continue dp[v][i]=memo[edge[v][i]] res=merge(res,f(dp[v][i],edge[v][i])) memo[v]=g(res,v) # df...
py
1292
E
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much...
[ "constructive algorithms", "greedy", "interactive", "math" ]
import sys n, L, minID = None, None, None s = [] def fill(id, c): global n, L, s, minID L -= (s[id] == 'L') s = s[0:id] + c + s[id+1:] minID = min(minID, id) def query(cmd, str): global n, L, s, minID print(cmd, ''.join(str)) print(cmd, ''.join(str), file=sys.stderr) sys.stdout.flush() if (cmd...
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" ]
# from collections import Counter, defaultdict, deque import os import sys # from math import gcd, ceil, sqrt # from bisect import bisect_left, bisect_right # import math, bisect, heapq, random # from functools import lru_cache, reduce, cmp_to_key # from itertools import accumulate, combinations, permutations f...
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())+1 while t := t-1: n,g,b=[int(x) for x in input().split()] if n<=g: print( n ) continue mid=(n+1)//2 fb,re=mid//g,mid%g comb=(b*(fb-1)) ans= 0 if re != 0: comb+=b ans+=re ans=mid+comb comb=n-mid-comb if comb >0: ...
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" ]
from sys import stdin,stdout input = stdin.readline # from math import inf # from collections import Counter # from heapq import heapify,heappop,heappush # from time import time # from bisect import bisect, bisect_left n,m = map(int,input().split()) a = list(map(int,input().split())) ans = 1 if n > 100...
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" ]
#!/usr/bin/env python3 n = int(input()) for _ in range(n): n, m, k = [int(i) for i in input().split()] arr = [int(i) for i in input().split()] total_pop = m - 1 max_val = None pop_num_r0 = min(k, m-1) for left_r0 in range(pop_num_r0+1): _arr = arr[left_r0:len(arr)-pop_num_r0+left_r0] ...
py
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vac...
[ "greedy", "implementation" ]
for _ in range(int(input())): n, d = map(int, input().split()) arr = list(map(int, input().split())) total = arr[0] i = 1 while d > 0 and i < n: new = min(d//i, arr[i]) total += new d = d - (new * i) i += 1 print(total)
py
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have t...
[ "games", "two pointers" ]
def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) ...
py
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letter...
[ "brute force", "dp", "math", "strings" ]
import pdb s=input() num1=[0 for i in range(26)] num2=[[0 for i in range(26)] for j in range(26)] for i in range(len(s)): for j in range(26): num2[j][(ord(s[i])-97)]+=num1[j] num1[(ord(s[i])-97)]+=1 result=max(num1) # pdb.set_trace() for i in range(26): for j in range(26): ...
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 # Sieve sieve_primes = [] PRIME_LIMIT = int(1e6) sieve = [False for i in range(0,PRIME_LIMIT)] for i in range(2,PRIME_LIMIT): if not sieve[i]: sieve_primes.append(i) for j in range(i*i, PRIME_LIMIT, i): sieve[j]=True # Input n = int(input()) arr=list(map(int...
py
1286
A
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all th...
[ "dp", "greedy", "sortings" ]
import bisect import heapq import sys from types import GeneratorType from functools import cmp_to_key from collections import defaultdict, Counter, deque import math from functools import lru_cache from heapq import nlargest from functools import reduce import random from operator import mul inf = float("i...
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" ]
n = int(input()) beauty = list(map(int, input().split())) dic = {} for i in range(n): dic[i-beauty[i]] = dic.get(i-beauty[i], 0) + beauty[i] print(max(dic.values()))
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" ]
MAX = 1_000_005 min_p_factor = [0] * MAX pr = [] pid = {1: 0} for i in range(2, MAX): if not min_p_factor[i]: min_p_factor[i] = i pr.append(i) pid[i] = len(pid) for p in pr: if p > min_p_factor[i] or i * p >= MAX: break min_p_factor[i * p] = p n = int(input()...
py
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good o...
[ "constructive algorithms", "greedy", "implementation", "math" ]
import re import functools import random import sys import os import math from collections import Counter, defaultdict, deque from functools import lru_cache, reduce from itertools import accumulate, combinations, permutations from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush from...
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" ]
# UCSD fa22 Week 5 import sys from collections import Counter, defaultdict input = sys.stdin.readline flush = sys.stdout.flush iil = lambda: [int(x) for x in input().split()] YES:str = "YES" NO:str = "NO" string: str = input()[:-1] left, right = 0, len(string) - 1 dels:list[int] = [] dir = 0 while left < right: w...
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" ]
for _ in range(int(input())): line = input() s, f = -1, -1 for i in range(len(line)): if line[i] == '1': if s < 0: s = i f = i print(line[s:f].count('0'))
py
1299
E
E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,…,pnp1,p2,…,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 …… akak.I...
[ "interactive", "math" ]
def ask(a): if len(a) == 1: return True print('?', len(a), *a) return input() != '0' def main(): n = int(input()) a = [None] * (n + 1) is_odd = [False] * (n + 1) pos = [None] * (n + 1) #find 1 and n one_yet = False for i in range(1, n + 1): 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
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" ]
#Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me, import sys #then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize, import os #just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails from io import Byt...
py
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.I...
[ "binary search", "brute force", "implementation" ]
for i in range(int(input())): l=list(map(int,input().split())) k=list(map(int,input().split())) for i in range(l[0]+1): if l[1]+i not in k and l[1]+i<=l[0]: print(i) break elif l[1]-i not in k and l[1]-i>0: print(i) break
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" ]
from sys import stdin input = stdin.readline def solve(root , bit): if(trie[root] == [-1 , -1]):return 0 if(trie[root][0] != -1 and trie[root][1] == -1): ans = solve(trie[root][0] , bit - 1) elif(trie[root][0] == -1 and trie[root][1] != -1): ans = solve(trie[root][1] , bit - 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" ]
import sys input=sys.stdin.buffer.readline n, m = map(int, input().split()) a = [int(i) - 1 for i in input().split()] ans1 = [i + 1 for i in range(n)] ans2 = [-1 for i in range(n)] for i in set(a): ans1[i] = 1 N = 1 while N < n + m: N <<= 1 st = [0 for i in range(N << 1)] pos = [i + m for i in range(n)] ...
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" ]
from collections import Counter n = int(input()) b = list(map(int, input().split())) b1 = b.copy() dct = {} for i in range(n): b1[i] -= (i + 1) for i, item in enumerate(b1): if item in dct: dct[item] += b[i] else: dct[item] = b[i] l = list(dct.values()) l.sort(reverse=True) pri...
py
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is t...
[ "bitmasks", "greedy" ]
from sys import stdin input = stdin.readline inp = lambda : list(map(int,input().split())) d = dict() for i in range(31): d[(1 << i)] = i def answer(): count = [0 for i in range(61)] for i in range(m): count[d[a[i]]] += 1 if(sum(a) < n):return -1 ans = 0 for i in ...
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
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" ]
def main(): n = int(input()) a = readIntArr() st = [] # store (total, l, r) for i, x in enumerate(a): st.append((x, i, i)) while len(st) >= 2: total2, l2, r2 = st.pop() total1, l1, r1 = st.pop() if total1 / (r1 - l1 + 1) >= (tot...
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" ]
t = int(input()) for _ in range(t): n, a = int(input()), [int(i) for i in input().split()] z, s = sum(i == 0 for i in a), sum(a) res = z + (z + s == 0) print(res)
py
1325
D
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1...
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
# LUOGU_RID: 92931723 u,v=input().split() u=int(u);v=int(v) delta=v-u if(delta<0 or delta%2==1):print(-1) elif(delta==0): if(u==0): print('0') else: print('1','\n',u,sep='') else: d2=delta//2 if((d2&u)): print('3','\n',d2,' ',d2,' ',u,sep='') else: print('2\n',d2,' ',d2^u,sep='')
py
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusiv...
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
#https://codeforces.com/problemset/problem/1325/C #1500 from collections import defaultdict n = int(input()) #node2cnt = defaultdict(int) node2cnt = [0] * (n+1) edges = [] for i in range(n-1): u, v = map(int, input().split()) u -= 1 v -= 1 edges.append([u, v]) node2cnt[u] += 1 nod...
py
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assu...
[ "dp", "implementation" ]
import sys from collections import * input = sys.stdin.readline from math import * def mrd(): return [int(x) for x in input().split()] def rd(): return int(input()) MAXN = 2 * 10**5 + 5 INF = 10**16 * 2 mod = 10**9 + 7 #----------------------------------------------------------------------------------# def solve(): ...
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" ]
import sys input = sys.stdin.readline n, m = map(int, input().split()) g = [input()[:-1] for _ in range(n)] d = set(g) c = 0 q = ord('S') + ord('E') + ord('T') for i in range(n-1): for j in range(i+1, n): x = [] for k in range(m): if g[i][k] == g[j][k]: ...
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 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
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vac...
[ "greedy", "implementation" ]
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
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is t...
[ "bitmasks", "greedy" ]
import sys, math import heapq from collections import deque from bisect import bisect_left, bisect_right input = sys.stdin.readline pop = heapq.heappop push = heapq.heappush # input def ip(): return int(input()) def sp(): return str(input().rstrip()) def mip(): return map(int, input().split()) ...
py
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letter...
[ "brute force", "dp", "math", "strings" ]
#bisect.bisect_left(a, x, lo=0, hi=len(a)) is the analog of std::lower_bound() #bisect.bisect_right(a, x, lo=0, hi=len(a)) is the analog of std::upper_bound() #from heapq import heappop,heappush,heapify #heappop(hq), heapify(list) #from collections import deque as dq #deque e.g. myqueue=dq(list) #append/appendleft...
py
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagram...
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = [0] + list(input().rstrip()) q = int(input()) c0 = [0] * 26 c = [list(c0)] for i in s[1:]: c0[i - 97] += 1 c.append(list(c0)) ans = [] for _ in range(q): l, r = map(int, input().split()) if s[l] ^ s[r] or l...
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" ]
__author__ = 'Darren' def solve(): t = int(input()) while t: run() t -= 1 def run(): def check_condition_1(): record = {} common, first, second = None, -1, -1 found = False for i in range(3): for j in range(2): ...
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 zz=1 sys.setrecursionlimit(10**5) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') di=[[-1,0],[1,0],[0,1],[0,-1]] def fori(n): return [fi() for i in range(n)] def inc(d,c,x=1): d[c]=d[c]+x if c in d else x def ii(): return inpu...
py
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t...
[ "dfs and similar", "dp", "greedy", "trees" ]
from sys import stdin input = stdin.readline inp = lambda : list(map(int,input().split())) from collections import deque """ it is obv that two vertices are the end points of the tree diameter we can try all third vertices """ def dfs(p , want_update): s = [[p , -1 , 0]] best = -1 w...
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" ]
for t in range(int(input())): n,m=map(int,input().split()) print("YES" if n%m==0 else "NO")
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" ]
#!/usr/bin/env python3 import math import sys input = lambda: sys.stdin.readline().rstrip("\r\n") from bisect import bisect_left as bs def test_case(): n, m = map(int, input().split()) a = list(map(int, input().split())) p = set(map(lambda x: int(x)-1, input().split())) while True: ...
py