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" ]
def solve(): n = int(input()) a = input().split() for i in range(n-2): for j in range(i+2, n): if a[i] == a[j]: print("YES") return print("NO") for _ in range(int(input())): solve() #########################################...
py
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'....
[ "data structures", "implementation" ]
from collections import deque, defaultdict, Counter from heapq import heappush, heappop, heapify from math import inf, sqrt, ceil from functools import lru_cache from itertools import accumulate, combinations, permutations, product from typing import List from bisect import bisect_left, bisect_right import sys ...
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" ]
from sys import stdin input = stdin.buffer.readline t = int(input()) while t: t -= 1 n = int(input()) seg = [] for i in range(n): l, r = map(int, input().split()) seg.append((l, 0, i)) seg.append((r, 1, i)) seg.sort() ans = 0 seq = [] active ...
py
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of ...
[ "implementation", "math" ]
import math a = int(input()) s = 0 for i in range(2, a): tmpA = a while tmpA != 0: s = s + (tmpA % i) tmpA = (tmpA // i) d = math.gcd(s, a-2) print(f"{s//d}/{(a-2)//d}")
py
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q...
[ "combinatorics", "greedy", "math" ]
n = int(input()) print(sum(1 / i for i in range(1, n + 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" ]
t = int(input()) for i in range(t): n, x, y = list(map(int, input().split())) worst = min(n, x + y - 1) best = max(1, x + y - n + 1) print(min(best, worst), worst) ''' '''
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" ]
def zip_sorted(a,b): # sorted by a a,b = zip(*sorted(zip(a,b))) # sorted by b sorted(zip(a, b), key=lambda x: x[1]) return a,b import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) S = lambda : list(map(str,input())) s = S()[:-1] n = len(s) dp = [[0 for i in range(n)] for j in r...
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" ]
def I(): return input().strip() def II(): return int(input().strip()) def LI(): return [*map(int, input().strip().split())] import sys, os, copy, string, math, time, functools, fractions input = sys.stdin.readline from io import BytesIO, IOBase from heapq import heappush, heappop, heapify from bisect import bise...
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" ]
# output = "YES" and `a,b,c` or no # 2 <= a,b,c # a.b.c = n # input: t # n => 2<= n <= 10^9 import math t = int(input()) for _ in range(t): n = int(input()) ans = [] N = math.floor(n ** 0.5) for i in range(2,N): if n % i == 0: n = n // i ans.append(i) if len(ans)...
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, 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
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller ...
[ "math" ]
for _ in range(int(input())): x,y,a,b=[int(_) for _ in input().split()] print((y-x)//(a+b) if (y-x)%(a+b)==0 else -1)
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 math import sys input = sys.stdin.readline def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] def dfs(): glob...
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" ]
t = int(input()) for i in range(t): n = int(input()) mas = list(map(int,input().split())) min1 = 10**9+10 max1 = 0 for i in range(n): if mas[i] == -1: if i == 0: if mas[i+1] != -1: min1 = min(mas[i+1],min1) max1 = max(mas[i+...
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" ]
class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._...
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" ]
# Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase mod=10**9+7 def main(): for _ in range(int(input())): n,m,k=map(int,input().split()) arr=list(map(int,input().split())) ans=1 if...
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 math import sys input = sys.stdin.readline from collections import * def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('...
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" ]
# -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random import itertools import sys from typing import List """ created by shhuan at 2020/3/19 13:35 """ def check(s, a, b, after): ns, na, nb = len(s), len(a), len(b) if ns < na + nb: ...
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" ]
from collections import Counter for _ in range(int(input())): n, m = map(int, input().split()) print("YES" if n % m == 0 else "NO") ########################################## ## ## ## Implemented by brownfox2k6 ## ## ...
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" ]
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n=int(input()) b=[int(x) for x in input().split()] L=[] B=[] X=[0]*n H=[0]*(2*n) a=[0]*(2*n) v=b.copy() for i ...
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" ]
T = int(input()) ANS = [] for _ in range(T): s = input() t = input() sl = [[] for i in range(26)] for i in range(len(s)): sl[ord(s[i]) - ord('a')].append(i) ans = 0 tek = -1 ttt = True #print(sl) for i in range(len(t)): l = -1 r = len(sl[ord(t[i]...
py
13
B
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. Th...
[ "geometry", "implementation" ]
import sys input = sys.stdin.buffer.readline def dot(a,b): return a[0]*b[0] + a[1]*b[1] for _ in range(int(input())): points = [list(map(int,input().split())) for i in range(3)] points = [[points[i][:2],points[i][2:]] for i in range(3)] diff = [[[points[i][ti^1][k] - points[i][ti][k] for k ...
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" ]
def main(): t=int(input()) allans=[] for _ in range(t): n,s=input().split() n=int(n) #for maxLIS, put small to large. decreasesInARow=[0 for _ in range(n-1)] for i in range(n-2,-1,-1): if s[i]=='>': decreasesInAR...
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" ]
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
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position...
[ "math" ]
n = int(input()) s = input() print(n+1)
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" ]
# Thank God that I'm not you. import bisect 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)...
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 = lambda: sys.stdin.readline().rstrip('\n\r') from collections import Counter, defaultdict, deque from itertools import accumulate, chain, zip_longest, product, repeat from bisect import bisect_left, bisect_right from math import gcd from string import ascii_lowercase from functools import cmp_to_key ...
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def lazy_segment_tree(n): n0 = 1 while n0 < n: n0 *= 2 tree = [0] * (2 * n0) lazy = [0] * (2 * n0) return tree, lazy def eval(s, t, a): b = [] u, v = [0, len(tree) // 2 - 1], [0, len(tree) ...
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" ]
def algo(p, q): bit_arr = [1 if q & (1 << i) else 0 for i in range(70)] awaiting_supplies = 70 if p % 2 != q % 2 or p > q: return [-1] for m in range(69): pow_of_2 = 70 - m - 1 p_digit = 1 if p & (1 << pow_of_2) else 0 if bit_arr[pow_of_2] % 2 == p_digit: ...
py
1292
C
C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (...
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
import sys # Read input and build the graph inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) # Relable to speed up n^...
py
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, ...
[ "math", "strings" ]
#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
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" ]
import sys, collections, math,bisect input = sys.stdin.readline for _ in range(int(input())): n,d = map(int,input().split()) # 考虑单链 # 分别记录每个节点的深度,孩子节点个数,父节点 depth = [0] + list(range(n)) child = [0] + [1] * (n - 1) + [0] fa = [-1,-1] + list(range(1,n)) cur_d = sum(depth) if d > ...
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" ]
import math def main(): t = int(input()) for _ in range(t): n = int(input()) a = -1 for i in range(2, int(n ** 0.34 + 5)): if n % i == 0: a = i break if a == -1: print("NO") continue n //= a b...
py
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are cor...
[ "greedy" ]
n = int(input()) a = list(input()) s1 = 0 t = 0 for i in range(n): if a[i] == "(": s1 += 1 else: s1 -= 1 if s1 < 0: t += 2 if s1 != 0: print(-1) else: print(t)
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff...
[ "brute force", "data structures", "sortings" ]
import sys readline = sys.stdin.readline 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 max = segf self.lazy = [0]*(2*self.N0) ...
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" ]
t=int(input()) for k in range(t): n,x,yak=map(int,input().split()) print(max(1,min(n,x+yak-n+1)),min(x+yak-1,n))
py
1294
B
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is ...
[ "implementation", "sortings" ]
for t in range(int(input())): n = int(input()) cord_list = [] for i in range(n): x, y = map(int, input().split()) cord_list.append((x, y)) cord_list.sort() r = 0 u = 0 fir = 0 sec = 0 ans = '' while cord_list: r = abs(cord_list[0][0] - f...
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" ]
import sys input=sys.stdin.readline n=int(input()) a=list(map(int,input().split())) sa=[0]+[a[i] for i in range(n)] for i in range(1,n+1): sa[i]+=sa[i-1] dd={} for i in range(n+1): for j in range(i+1,n+1): if sa[j]-sa[i] in dd: dd[sa[j]-sa[i]].append([i+1,j]) else: ...
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 math length = int(input()) first = list(map(int, input().split())) second = list(map(int, input().split())) second_count = sum(second) first_count = sum(first) if second_count == len(second): print(-1) else: intersection_count = 0 i = 0 while i < len(first): if first[i...
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" ]
def sol(n) : m = n ;a = 0 for i in range(2,int(n**(1/2))+1) : if not n%i : a = i; break else : print('NO'); return n //= a for i in range(2,int(n**(1/2))+1) : if not n%i and i!=a : b = i; break else : print('NO'); return n//=b if a*b*n == m and n!=b: print(...
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" ]
i=input for _ in[0]*int(i()): a,b,c=sorted(map(int,i().split())) r=(a>0)+(b>0)+(c>0)+(min(a,b,c)>3) if (c>1 and b>1):r+=1;c-=1;b-=1 if (c>1 and a>1):r+=1;a-=1 if (b>1 and a>1):r+=1 print(r)
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 os import sys from collections import defaultdict,deque from io import BytesIO, IOBase # MOD = 998244353 # nmax = 5000 # fact = [1] * (nmax+1) # for i in range(2, nmax+1): # fact[i] = fact[i-1] * i % MOD # inv = [1] * (nmax+1) # for i in range(2, nmax+1): # inv[i] = pow(fact[i], MOD-2,...
py
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; f...
[ "combinatorics", "math" ]
import sys # from math import * from heapq import * from bisect import * from itertools import * from functools import * from collections import * def read(fn=int): return map(fn, input().split()) n,m = read() mod = 998244353 v = 1 for i in range(m,m-n+1,-1): v = (v * i) % mod for i in range(1,n): v = (v * ...
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" ]
t = int(input()) for i in range(t): a, b, x, y = map(int, input().split()) print(max(max(x, a - 1 - x) * b, a * max(y, b - 1 - y)))
py
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO...
[ "data structures", "dsu", "implementation" ]
n, q = map(int,input().split()) a = [[0] * n for _ in range(2)] bp = 0 for _ in range(q): x, y = map(int,input().split()) x -= 1 y -= 1 u = 0 if a[x][y] == 0: u = 2 else: u = 1 a[x][y] ^= 1 for l in range(-1, 2): if 0 <= y + l < n and a[1 - x][y + l]: if u == 2: bp += 1 ...
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" ]
inf = int(2e9) + 1 n = int(input()) m = [-inf] + [int(x) for x in input().split()] + [-inf] def get_lmin(): l = [0] * (n + 2) st = [n + 1] for i in range(n, -1, -1): while m[st[-1]] > m[i]: l[st.pop()] = i st.append(i) return l def get_rmin(): r = [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" ]
n = input() stepsmin = 0 stepsmax = 0 pozic = 0 s = input() for i in range(int(n)): if s[i] == "L": stepsmin -= 1 else: stepsmax += 1 for j in range(stepsmin, stepsmax + 1): pozic += 1 print(pozic)
py
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller ...
[ "math" ]
# LUOGU_RID: 101845249 for _ in range(int(input())): x, y, a, b = map(int, input().split()) q, r = divmod(y - x, a + b) print(-1 if r else q)
py
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11)...
[ "implementation" ]
import sys def f(): n=int(input()) arr=input() arr=arr.split(" ") arr=map(int,arr) arr=list(arr) count=0 maxi=-sys.maxsize i=0 while True: if i==(n*2)-1: break if i==n-1 and arr[i%n]==1: count=count+1 i=i+1 e...
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" ]
from unittest import async_case t = int(input()) def solve(a, b, c): ans = 0 if a > 0: ans += 1 a -= 1 if b > 0: ans += 1 b -= 1 if c > 0: ans += 1 c -= 1 if c == max(a, b, c): if a > 0 and c > 0: ans += 1 a -= 1 ...
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" ]
t = int(input()) for case in range(t): a, b, p = map(int, input().split(' ')) s = input() i = len(s) - 1 if s[i-1] == 'A': cost = a elif s[i-1] == 'B': cost = b if cost > p: print(i+1) continue i -= 1 while i >= 1: if s[i-1] == 'A' and ...
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()) while t > 0: s = input() r = [0] r += [i + 1 for i in range(len(s)) if s[i] == 'R'] r += [len(s) + 1] print(max(r[i + 1] - r[i] for i in range(len(r) - 1))) t -= 1
py
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q...
[ "combinatorics", "greedy", "math" ]
n=int(input()) sum=0 for i in range(1,n+1): sum+=1/i print(sum)
py
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 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 ...
[ "data structures", "greedy" ]
import collections import math import os import random import sys from bisect import bisect, bisect_left from functools import reduce from heapq import heapify, heappop, heappush from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, ...
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" ]
from collections import defaultdict, deque, Counter from sys import stdin, stdout from heapq import heappush, heappop import math import io import os import math import bisect #?############################################################ def isPrime(x): for i in range(2, x): if i*i > x: ...
py
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the ...
[ "math" ]
t=int(input()) for i in range(t): a,b,c,n=map(int,input().strip().split()) sum=a+b+c+n maxt=max(a,(max(b,c))) if sum%3==0 and sum/3>=maxt: print("YES") else: print("NO")
py
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memor...
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
import sys def get_ints(): return map(int, sys.stdin.readline().strip().split()) def solve(): n, m = [int(x) for x in input().split()] min_t = m max_t = m prev = 0 t = [0]*n l = [0]*n h = [0]*n for i in range(n): t[i],l[i],h[i] = get_ints() flag = True fo...
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 bisect import collections import heapq import io import math import os import sys LO = 'abcdefghijklmnopqrstuvwxyz' Mod = 1000000007 def gcd(x, y): while y: x, y = y, x % y return x # _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode() _input = lam...
py
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 bisect import * from collections import * import sys import io, os import math import random import operator from heapq import * gcd = math.gcd sqrt = math.sqrt maxint=10**21 def ceil(a, b): if(b==0): return maxint a = -a k = a // b k = -k return k # arr=list(map(int, ...
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 input = sys.stdin.readline from collections import Counter n = int(input()) w = list(map(int, input().split())) d = [w[i]-i for i in range(n)] c = Counter() for i in range(n): c[d[i]] += w[i] print(max(c.values()))
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" ]
for _ in range(int(input())): a,b,c=map(int,input().split()) cnt=0 if a: cnt+=1 a-=1 if b: cnt+=1 b-=1 if c: cnt+=1 c-=1 if a==1 and b==1 and c>1: cnt+=2 a-=1 b-=1 c-=2 elif a==1 and b>1 an...
py
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. ...
[ "greedy", "implementation" ]
# LUOGU_RID: 101844865 for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) l = 0 while l < n and a[l] >= l: l += 1 r = n while r > 0 and a[r - 1] >= n - r: r -= 1 print(l > r and 'Yes' or 'No')
py
1312
E
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such...
[ "dp", "greedy" ]
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction from itertools import permutations from collections import defaultdict mod = 10 ** 9 + ...
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" ]
for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) l=0 h=10**9+7 def check(x): res=0 for i in range(len(arr)): if arr[i]==-1: if i>0 and arr[i-1]!=-1: res=max(res,abs(arr[i-1]-x)) ...
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" ]
def md(xi,yi,xs,ys): return abs(xs-xi)+abs(ys-yi) def case1(D,S,t): i = D.index(min(D)) for j in range(i,-1,-1): if D[i]+S[i]-S[j]>t: return i-j return i+1 def case2(D,S,t): for i in range(len(S)): if D[i]+S[i]>t: return i return len(S) def c...
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" ]
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
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 math n, m = map(int, input().split()) grid = [] for _ in range(n): grid.append(list(map(int, input().split()))) ans = 0 for c in range(m): cnt = [0 for _ in range(n)] for i in range(n): grid[i][c] -= (c+1) if grid[i][c] % m == 0 and grid[i][c] <= ((n-1)*m): cn...
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 sys import math import itertools n,m=map(int,input().split()) init=[1] for i in range(1,n): if(m==0): break pairs=i//2 if(m>=pairs): m-=pairs init.append(i+1) else: init.append(i+1+2*(pairs-m)) m=0 if(m!=0): print(-1) sys.exit() nxt=10000000+6...
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" ]
# 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
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" ]
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
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" ]
from sys import stdin input = stdin.readline q = int(input()) for rwere in range(q): n = int(input()) seg = [] pts = [] for i in range(n): pocz, kon = map(int,input().split()) seg.append([2*pocz, 2*kon]) pts.append(2*kon+1) p,k = map(list,zip(*seg)) pts += (p + k) pts.sort() ind = -1 while...
py
1291
F
F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.Th...
[ "graphs", "interactive" ]
import sys def ask(s): print(s) sys.stdout.flush() def solve(): n, k = map(int, input().split()) head = [True] * (n + 1) head[0] = False if k == 1: N = 2 * int(n / (k + 1)) else: N = 2 * int(n / k) for i in range(1, N + 1): cl = (i - 1) * int((k + 1) ...
py
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2...
[ "math" ]
import array import bisect import heapq import json import math import collections import random import re import sys import copy from functools import reduce import decimal from io import BytesIO, IOBase import os import itertools import functools from types import GeneratorType import fractions from...
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" ]
import heapq import sys input = sys.stdin.readline def make_tree(n): tree = [0] * (n + 1) return tree def get_sum(i, tree): s = 0 while i > 0: s += tree[i] i -= i & -i return s def add(i, x, tree): while i <= n: tree[i] += x i += i & -i n =...
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" ]
for _ in range(int(input())): a, b, c = map(lambda x : min(int(x), 4), input().split()) res = 0 if a: a -= 1 res += 1 if b: b -= 1 res += 1 if c: c -= 1 res += 1 cnt = [0] * 4 for x in a, b, c: cnt[x] += 1 cnt = ''.join(map(str, cnt...
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) xy = [tuple(map(int, input().split())) for _ in range(n)] if n % 2: ans = "NO" else: ans = "YES" for i in range(n): u1, u2 = xy[i], xy[(i + 1) % n] v1, v2 = xy[(i + n // 2) % n], xy[(...
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" ]
import math for _ in range(int(input())): (n, k) = tuple(map(int, input().split())) a = list(map(int, input().split())) l = [] dct = {} s = math.ceil(math.log(10**16, k)) for i in range(s, -1, -1): l.append(k**i) pos = True for i, item in enumerate(a): for j, i...
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" ]
testcase=int(input()) for _ in range(testcase): n=int(input()) arr=[int(num) for num in input().split()] deleted=set() remaining_nums=set(range(1,2*n+1)) doable=True for num in arr: deleted.add(num) remaining_nums.remove(num) remaining_nums=sorted(list(remaining_...
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" ]
h,n = map(int,input().split()) d= list(map(int,input().split())) z=0 cm=0 cv=0 r=0 for i in range(n): h= h+d[i] r= r+d[i] if h<=0: cm=i+1 z=1 break if r<cv: cv=r # print(r) if z==1: print(cm) else: if r>=0: print(-1) ...
py
1322
C
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given...
[ "graphs", "hashing", "math", "number theory" ]
import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from math import gcd t=int(input()) for tests in range(t): n,m=map(int,input().split()) C=list(map(int,input().split())) X=[[] for i in range(n+1)] for k in range(m): x,y=map(int,input().split()) X[y]...
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" ]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.py' # # Created by: PyQt5 UI code generator 5.15.7 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. def f(): l1 = input().split(' '...
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" ]
T = int(input()) def findPeriod(DP): for offset in range(0, len(DP)): for period in range(1, 500): is_period = True for j in range(offset, len(DP) - period): if (DP[j][0] == DP[j + period][0] and DP[j][1] == DP[j + period][1] and DP[j][2] == DP[j + period][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" ]
def ddfs(root): global count global flag visit=[0]*(n+1) stack=[0,root] stack2=[] while(len(stack)>1): par=stack.pop() stack2.append(par) if(visit[par]): continue visit[par]=1 for i in graph[par]: if(visit[i]==0): ...
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff...
[ "brute force", "data structures", "sortings" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def update(l, r, s): q, ll, rr, i = [1], [0], [l1 - 1], 0 while len(q) ^ i: j = q[i] l0, r0 = ll[i], rr[i] if l <= l0 and r0 <= r: lazy[j] += s i += 1 continue ...
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" ]
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from array import array class SortedList: def __init__(self, iterable=None, _load=200): """Initialize sorted list instance.""" if iterable is None: iterable = [] ...
py
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord...
[ "greedy", "implementation", "sortings" ]
for _ in range(int(input())): nish=int(input()) girish=[int(x) for x in input().split()] girish.sort() print(girish[nish]-girish[nish-1])
py
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the ...
[ "math" ]
t = int(input()) for i in range(t): a, b, c, n = map(int, input().split()) total_coins = (a + b + c + n) // 3 if (a + b + c + n) % 3 != 0 or total_coins < max(a, b, c): print("NO") else: print("YES")
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" ]
from sys import stdin,stdout input = stdin.readline from math import sqrt,gcd # from collections import Counter # from heapq import heapify,heappop,heappush # from time import time # from bisect import bisect, bisect_left #! Checking remainder with x if number of remainder is greater then given count the...
py
1292
C
C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (...
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
import sys input = sys.stdin.readline from collections import deque N=int(input()) E=[[] for i in range(N+1)] for i in range(N-1): x,y=map(int,input().split()) E[x].append(y) E[y].append(x) Q=deque() USE=[0]*(N+1) Q.append(1) H=[0]*(N+1) H[1]=1 USE[1]=1 P=[-1]*(N+1) QI=deque() w...
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" ]
import sys # def input(): return sys.stdin.readline()[:-1] def input(): return sys.stdin.buffer.readline()[:-1] def print(*values, end='\n'): sys.stdout.write(' '.join([str(x) for x in values]) + end) from collections import deque def main(): n = int(input()) res = [[''] * n for _ in range(n)] data = ...
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 i in range(int(input())): n = int(input()) a = list(map(int, input().split(' '))) x, y, z = -1, -1, -1 for i in range(n): if a[i] % 2 == 0: z = i + 1 break else: if x == -1: x = i + 1 else: y ...
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" ]
from math import ceil,floor,log t=int(input()) for i2 in range(t): n,d=map(int,input().split()) p,dad=0,[0]*(n+1) c=(n*(n-1))//2 for i in range(1,n+1): p+=floor(log(i,2)) if p>d or c<d: print("NO") continue now=1 dad=[0]*(n+1) vec=[[]for i in range(n+...
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" ]
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import defaultdict def main(): n=int(input()) a=list(map(int,input().split())) b,ma,ans=defaultdict(list),0,[] for i in range(n): su=0 for j ...
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" ]
from collections import deque, defaultdict, Counter from heapq import heappush, heappop, heapify from math import inf, sqrt, ceil from functools import lru_cache from itertools import accumulate, combinations, permutations, product from typing import List from bisect import bisect_left, bisect_right import sys ...
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" ]
from math import lcm for i in range(int((x := int(input())) ** 0.5), 0, -1): if x % i == 0 and lcm(i, x // i) == x: print(i, x // i) break
py
1288
D
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j...
[ "binary search", "bitmasks", "dp" ]
import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import defaultdict n, m = map(int, input().split()) A = [list(map(int, input().split())) for i in range(n)] pair = [] for i in range((1<<m)-1): for j in range(i+1, 1<<m): if (i|j) == (1<<m)-1...
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" ]
# https://codeforces.com/problemset/problem/1294/D import sys q, x = map(int, sys.stdin.readline().split(" ")) dict = {} mex = 0 for i in range(q): y = int(sys.stdin.readline()) y_ = y % x # y init if y_ in dict: new_y_ = y_ + x*dict[y_] dict[y_] += 1 dict[n...
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" ]
import sys import collections import math input = sys.stdin.readline ints = lambda: list(map(int, input().split())) n = int(input()) tree = [[] for _ in range(n + 1)] edges = {} for i in range(n - 1): u, v = ints() tp = sorted((u, v)) tp = tuple(tp) edges[tp] = i tree[u].append(v) ...
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
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller ...
[ "math" ]
for i in [*open(0)][1:]: x,y,a,b=map(int,i.split()) print([(y-x)//(a + b),-1][(y-x)%(a+b)>0])
py
1324
A
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12...
[ "implementation", "number theory" ]
for run in range(int(input())): n=int(input()) lst=list(map(int,input().split())) if lst[0]%2==0: odd=False else: odd=True for i in range(1,n): if odd and lst[i]%2!=1: odd='x' print('NO') break if odd==False and lst[i]%2...
py