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
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" ]
t=int(input()) M=[] def fonction(L): L.sort() i=0 test=True while test==True and (i<=n-1): test=(max(L)-L[i])%2==0 i+=1 if test==False: return "NO" else: return "YES" for i in range(t): n=int(input()) L=[int(x) for x in input().split()...
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
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" ]
from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per from heapq import heapify,heappush,heappop,heappushpop input=stdin.readline R=lambda:map(int,inp...
py
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" ]
import sys for i in range(int(sys.stdin.readline())): s = int(sys.stdin.readline()) ls = [int(a) for a in sys.stdin.readline().split()] par = 1 if ls[0] % 2 == 0: par = 0 f = True for i in ls: if i % 2 != par: f = False ...
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" ]
import sys, collections, math, bisect, heapq, random, functools input = sys.stdin.readline out = sys.stdout.flush def solve(): H,n = map(int,input().split()) a = list(map(int,input().split())) pre = [0] pos = -1 minv = float('inf') for i in range(n): pre.append(pre[-1] + a[...
py
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifical...
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
string = input() l = 0 r = len(string)-1 indices = [] while l < r: while string[l] == "(" and string[r] == ")": didOp = True indices.extend([l+1, r+1]) l += 1 r -= 1 if string[l] != "(": l += 1 if string[r] != ")": r -= 1 if indi...
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" ]
n, h, l, r = map(int, input().split()) arr = list(map(int, input().split())) s = [0] * (n + 1) for i in range(n): s[i + 1] = s[i] + arr[i] dp = [[0] * (n + 1) for _ in range(n + 1)] # dp[i][j] 为前i个数减j, 前i个数的最大分数 # dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + (l <= (s[i] - j) % h <= r) for i in range(1, n + 1)...
py
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positiv...
[ "greedy", "implementation", "math" ]
tst = int(input()) vals = [] for i in range(0,tst): arr = a,b = [int(x) for x in input().split()] vals.append(arr) for lst in vals: a = lst[0] b = lst[1] if a == b: print(0) elif a > b and (a-b)%2 == 0: print(1) elif a < b and (b-a)%2 != 0: print(1) else: print(2)
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" ]
t=int(input()) d=[] def fonction(a,b,c): test="Yes" for i in range(len(a)): if c[i]!= a[i] and c[i]!=b[i]: test="No" break return test for i in range(t): a=input() b=input() c=input() d.append(fonction(a,b,c)) for k in d: print(k)
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 input = stdin.readline from collections import defaultdict n, m = map(int, input().split()) a = list(map(int, input().split())) if len(a) > m: #by pigeonhole guaranteed k st. there exists i, j st a[i] % m == a[j] % m == k=> product will be 0 print(0) else: ans = 1 for i in range(...
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" ]
from cmath import inf from sys import stdin, stdout n = int(stdin.readline().strip()) arr = list(map(int, stdin.readline().split())) mono_stack = [] non_dec_sum = [0] * n prefix_sum = 0 for i, num in enumerate(reversed(arr)): count = 1 while mono_stack and num <= mono_stack[-1][0]: v...
py
1325
E
E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this...
[ "brute force", "dfs and similar", "graphs", "number theory", "shortest paths" ]
from sys import stdin, exit from collections import deque N = int(input()) arr = list(map(int, stdin.readline().split())) # sieve, prime list, dictionary of primes # lp is largest prime MAX = 1_000_005 pid = {1:0} pr = [] lp = [0]*MAX for i in range(2, MAX): if not lp[i]: lp[i] = i pr.append(i) pid[i] = l...
py
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun...
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
import os import 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 = file.fileno() self.buffer = BytesIO() self.writable = "x" in f...
py
1320
D
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a...
[ "data structures", "hashing", "strings" ]
import sys input = sys.stdin.readline MOD = 987654103 n = int(input()) t = input() place = [] f1 = [] e1 = [] s = [] curr = 0 count1 = 0 for i in range(n): c = t[i] if c == '0': if count1: e1.append(i - 1) if count1 & 1: s.append(1) curr +=...
py
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo...
[ "data structures", "divide and conquer", "implementation", "sortings" ]
class SegmentTree(): def __init__(self,N,func,initialRes=0): self.f=func self.N=N self.tree=[0 for _ in range(4*self.N)] self.initialRes=initialRes # for i in range(self.N): # self.tree[self.N+i]=arr[i] # for i in range(self.N-1,0,-1): # ...
py
1299
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" ]
n = int(input()) if n%2 != 0: print("NO") else: pts = [] for i in range(n): l = [int(x) for x in input().split(" ")] a,b = l[0], l[1] pts.append((a,b)) cx, cy = None, None ans = "YES" for i in range(n//2...
py
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate...
[ "binary search", "brute force", "math", "ternary search" ]
from math import ceil T = int(input()) for test in range(T): n, d = [int(i) for i in input().split()] if d <= n: print("YES") continue for x in range(n): if ceil(d/(x+1)) <= n-x: print("YES") break else: print("NO") ...
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" ]
# Question link: https://codeforces.com/contest/1304/problem/B # Longest Palindrome # time limit per test1 second # memory limit per test256 megabytes # inputstandard input # outputstandard output # Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string t...
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 = {'ES':'T', 'SE':'T', 'ET':'S', 'TE':'S', 'TS':'E', 'ST':'E'} for i in range(n-1): for j in range(i+1, n): x = '' for k in range(m): if g[i][k] =...
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" ]
import sys input = sys.stdin.readline n=int(input()) A=list(map(int,input().split())) Primes=(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 22...
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" ]
n , m = list(map(int ,input().split())) count = 0 while m > n : if(m % (n*2) == 0): n *= 2 count += 1 else: n *= 3 count += 1 if(n == m): print(count) else: print(-1)
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" ]
n = int(input()) a = list(map(int, input().split())) m = len(bin(max(a)))-2 def solve(i=m, l=0, r=n-1): if i == -1: return 0 k = l y = 1 << i for j in range(l, r+1): if a[j] & y == 0: a[j], a[k] = a[k], a[j] k += 1 z = -1 for j...
py
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo...
[ "data structures", "divide and conquer", "implementation", "sortings" ]
from sys import stdin, stdout, setrecursionlimit # from Multiset import update, remove from bisect import bisect_left string = lambda: stdin.readline().strip() get = lambda: int(stdin.readline().strip()) array = lambda: list(map(int, stdin.readline().strip().split())) charar = lambda: list(map(s...
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 _ in range(int(input())): n,s,k=map(int,input().split()) arr=set(el for el in list(map(int,input().split()))) start=s c=0 while start<=s and start in arr: start-=1 c+=1 start1=s while start1>=s and start1 in arr: start1+=1 c-=1 if start!=0:...
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 sys from collections import * from itertools import * from math import * from array import * from functools import lru_cache import heapq import bisect import random import io, os from bisect import * if sys.hexversion == 50924784: sys.stdin = open('cfinput.txt') RI = lambda: map(int, sys.st...
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" ]
from sys import stdin input = stdin.readline u, v = [int(x) for x in input().split()] if u > v or (v-u)%2 == 1: print(-1) elif u == v == 0: print(0) elif u == v: print(1); print(u) else: x = (v-u)//2 if ((u+x)^x) == u and u+x+x == v: print(2); print(u+x, x) else: print(3); print(u, x, x) # h...
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" ]
import sys input = sys.stdin.readline for _ in range(int(input())): a, b, p = map(int, input().split()) s = input()[:-1] n = len(s) i = n-1 c = 0 x = {'A':a, 'B':b} while i > 0 and c + x[s[i-1]] <= p: c += x[s[i-1]] i -= 1 while i > 0 and s[i-1] == s[i]:...
py
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are cor...
[ "greedy" ]
# first count if there are an equal number of open and closing parentheses # if there are not, return -1 (impossible) # worst case is always going to be the length of the array # E.g. ))))(((( - need to reorder the whole substring input() arr = list(input().strip()) open_count = arr.count("(") close_cou...
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t = int(input()) pow2 = [1] for _ in range(63): pow2.append(2 * pow2[-1]) d = dict() for i in range(32): d[pow2[i]] = i ans = [] for _ in range(t): n, m = map(int, input().split()) a = list(map(int, input().spl...
py
1296
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (poss...
[ "math" ]
for t in range(int(input())): n=int(input()) num=list(map(int,input().split())) e=0 for i in num: if i%2==0: e+=1 o=n-e if e==n or (e==0 and o%2==0): print("NO") else: print("YES")
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" ]
x0, y0, ax, ay, bx, by = [int(x) for x in input().strip().split()] xs, ys, t = [int(x) for x in input().strip().split()] lis = [(x0, y0)] def getdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) def getdisp(p1, p2): x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2) for i ...
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
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 i in range(int(input())): n = int(input()) cnto = sum(list(map(lambda x: int(x) % 2, input().split()))) print('YES' if cnto == 0 or cnto == n else 'NO')
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; R = sys.stdin.readline for _ in range(int(R())): dic = {} e = [[] for _ in range(6)] k = 0 v = [] for _ in range(3): x1,y1,x2,y2 = map(int,R().split()) if (x1,y1) not in dic: dic[(x1,y1)] = k; v += (x1,y1),; k += 1 if (x2,y2) not in dic: dic[(x2,y2)] = ...
py
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all studen...
[ "implementation" ]
for t in range(int(input())): n , m = map(int, input().split()) a = list(map(int, input().split())) s = sum (a) if s > m: print(m) else: print(s)
py
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i...
[ "dp", "strings" ]
import sys readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def solve(): s = ...
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())): input();print(len({int(x)for x in input().split()}))
py
1296
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (poss...
[ "math" ]
for _ in range(int(input())): n= int(input()) l=list(map(int,input().split())) imp=False p=False s=0 for i in l: s+=i if i%2==1 and not imp:imp=True if i%2==0 and not p:p=True if s%2==1 or (imp and p):print("YES") else:print("NO")
py
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and re...
[ "brute force", "constructive algorithms", "greedy", "strings" ]
from sys import stdin input = stdin.readline #// - remember to add .strip() when input is a string n = int(input()) word = list(input()) alpha = "abcdefghijklmnopqrstuvwxyz"[::-1] popcount = 0 counter = 0 for i in alpha: cur_letter = i popcount = 0 while True: popcount = 0 popl=...
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" ]
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, heapify, heappop, heappush from io import BytesIO, IOBase from copy impo...
py
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, ...
[ "math", "strings" ]
import sys input = lambda :sys.stdin.readline()[:-1] ni = lambda :int(input()) na = lambda :list(map(int,input().split())) yes = lambda :print("yes");Yes = lambda :print("Yes");YES = lambda : print("YES") no = lambda :print("no");No = lambda :print("No");NO = lambda : print("NO") #######################################...
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" ]
""" Author - Satwik Tiwari . 20th Oct , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from ...
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" ]
for _ in range(int(input())): a,b,c,d = map(int,input().split()) s = a+b+c+d s1 = max(a, b,c) <= s//3 if( s%3 ==0 and s1): print("YES") else: print("NO")
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 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
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for an...
[ "brute force", "greedy", "math" ]
import sys input = lambda: sys.stdin.readline().rstrip() n = int(input()) li = list(map(int, input().split())) total_cts = [0] * 31 cts = [[0] * 31 for _ in range(n)] for i in range(n): v = li[i] bv = bin(v) cur = 0 for j in range(len(bv) - 1, 1, -1): if bv[j] == '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" ]
n=int(input()) l=*map(int,input().split()), a=[0]*n a[0]=1-l[0] a[1]=1 f=(n+1)*[0] x=min(a[0],a[1]) for i in range(2,n): a[i]=a[i-1]+l[i-1] x=min(x,a[i]) x=1-x tf=True for i,j in enumerate(a): j+=x a[i]=j if j>n: tf=False break elif f[j]:tf=False else:f[j]+...
py
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn l...
[ "binary search", "data structures", "hashing", "sortings" ]
MOD = 10**18+13 import sys readline = sys.stdin.readline from random import randrange def compress(L): L2 = list(set(L)) L2.sort() C = {v : k for k, v in enumerate(L2, 1)} return L2, C N = int(readline()) T = set() L = [None]*N for i in range(N): L[i] = tuple(map(int, ...
py
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, ...
[ "math", "strings" ]
import sys, math import heapq from dataclasses import dataclass from collections import deque from bisect import bisect_left, bisect_right input = sys.stdin.readline hqp = heapq.heappop hqs = heapq.heappush # input def ip(): return int(input()) def sp(): return str(input().rstrip()) def mip(): ...
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" ]
from collections import defaultdict, Counter, deque import threading import sys input = sys.stdin.readline def ri(): return int(input()) def rs(): return input() def rl(): return list(map(int, input().split())) def rls(): return list(input().split()) threading.stack_size(10**8) sys.setrecursionlimit(10**6)...
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" ]
def solution(): n, m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] for i in range(1, n): if a[0] + a[i] > m: dif = m - a[0] a[0] += dif; a[i] -= dif else: a[0] += a[i]; a[i] = 0 print(a[0]) c = int(input()) for ciclo...
py
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne num...
[ "greedy", "math", "strings" ]
for _ in range(int(input())): x = int(input()) y = list(input()) z = [] for i in y: if int(i) % 2 != 0: z.append(i) if len(z) == 2: break if len(z) == 2: print("".join(z)) else: print(-1)
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" ]
# 14:26- from itertools import accumulate MOD = 10**9+7 N,M = map(int, input().split()) dp1 = list(accumulate([1]*N)) dp2 = [1]*N for _ in range(1,M): dp1 = list(accumulate(dp1)) cur = 0 ndp2 = [0]*N for i in range(N-1,-1,-1): cur+=dp2[i] ndp2[i]=cur dp2 = ndp2 # print(dp1) # print(dp2) ...
py
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO...
[ "data structures", "dsu", "implementation" ]
import sys, random input = lambda : sys.stdin.readline().rstrip() write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x)) debug = lambda x: sys.stderr.write(x+"\n") YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18 LI = lambda : list(map(int, input().split()));...
py
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" ]
def f(s, t, I): n = len(s) m = len(t) check = [[0 for j in range(m)] for i in range(m)] start = [(0, 0)] check[0][0] = 1 for i in range(n): next_s = [] for i1, i2 in start: add = True if i1 < I and s[i]==t[i1]: add = False ...
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" ]
from sys import stdin from typing import List def readarray(typ): return list(map(typ, stdin.readline().split())) def solveDP(arr: List[int], left: int, right: int, currentSum: int, indices: List[int], dp: dict): if currentSum != 0 and currentSum % 2 == 0: return [indices, currentSum]...
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" ]
for test in range(int(input())): n,m,k=map(int,input().split()) a=list(map(int,input().split())) k=min(k,m-1) l=m-1-k resf=0 for i in range(k+1): res=1<<33 for j in range(l+1): res=min(max(a[i+j],a[i+j+n-m]),res) resf=max(res,resf) print(resf)
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" ]
# в массиве будут присутствовать n - 1 разный элементов, # ихможно выбрать столькими способами: количество сочетаний из m по n - 1 # далее выбираем элемент который будет повторяться, максимум мы взять не сможем, # так как иначе не будет выполняться 4 условие, поэтому домножаем на n - 2 # некоторые элементы будут по...
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" ]
t = int(input()) for i in range(t): n, d = map(int, input().split()) *a, = map(int, input().split()) cnt = 1 while len(a) > 1 and d > 0 and d >= cnt: m = min(d // cnt, a[1]) a[0] += m d -= m * cnt del a[1] cnt += 1 print(a[0])
py
1324
D
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji...
[ "binary search", "data structures", "sortings", "two pointers" ]
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) c = sorted([a[i] - b[i] for i in range(n)]) ans = 0 l = 0 r = n - 1 while l < r: if c[l] + c[r] > 0: ans += r - l r -= 1 else: l += 1 print(ans)
py
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positiv...
[ "greedy", "implementation", "math" ]
for _ in range(int(input())): a, b = map(int, input().split()) if a == b: print(0) elif a > b: print(1 if (a - b) % 2 == 0 else 2) else: print(2 if (a - b) % 2 == 0 else 1)
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" ]
# 08:54- import sys input = lambda: sys.stdin.readline().strip() from collections import defaultdict,deque N = int(input()) A = [] lib = defaultdict(int) for _ in range(N-1): a,b = map(int, input().split()) A.append((a,b)) lib[a]+=1 lib[b]+=1 D = deque([i for i in range(N-1)]) B = set() for ...
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()) ans = 1 for i in range(1, int(math.sqrt(n))+1): if n % i == 0 and math.gcd(i, n // i) == 1: ans = i print(ans, n // ans)
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" ]
import sys input = sys.stdin.readline output = sys.stdout.write def main(): tests = int(input().rstrip()) for i in range(tests): input() nums = set(map(int, input().rstrip().split())) ans = str(len(nums)) output(ans) output('\n') if __name__ == '__main_...
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" ]
n = int(input()) neighbourNodes = [[] for i in range(n)] for i in range(n - 1): path, toPath = map(int, input().split()) path -= 1 toPath -= 1 neighbourNodes[path].append((toPath, i)) neighbourNodes[toPath].append((path, i)) rootNode, currentMax = None, 0 for node in range(n...
py
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate...
[ "binary search", "brute force", "math", "ternary search" ]
t=int(input()) for e in range(t): n,d=list(map(int, input().split())) l=0 r=n a=[] eps=1e-6 while r-l>1: m1=int(l+(r-l)/3-0.000000001) m2=int(l+(r-l)/3*2-0.000000001) if m1+d/(m1+1)>m2+d/(m2+1): l=l+(r-l)/3 elif m1+d/(m1+1)<m2+d/(m2+1): r=l+(r-l)/3*2 else: ...
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" ]
import collections import math def prime_range(n): sieve = [0] * n pid = {1: 0} for i in range(2, n): if not sieve[i]: sieve[i] = i pid[i] = len(pid) for j in range(i * i, n, i): if not sieve[j]: sieve[j] = i return sieve,...
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" ]
from __future__ import division, print_function import os import sys from io import BytesIO, IOBase def powmin2(x, r): return pow(x, r - 2, r) def comb(m, n, k): res = 1 for i in range(n): res = (res * (m - i)) % k pro_mod = 1 for i in range(2, n + 1): pro_mod = (pro_mod * i) % k...
py
1323
B
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e....
[ "binary search", "greedy", "implementation" ]
from collections import defaultdict import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def divisor(i): s = [] for j in range(1, int(i ** (1 / 2)) + 1): if i % j == 0: s.append(i // j) s.append(j) return sorted(set(s)) n, m, k = map(i...
py
1325
A
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both...
[ "constructive algorithms", "greedy", "number theory" ]
for _ in range(int(input())): print(1,int(input())-1)
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" ]
import math from sys import stdin from collections import Counter, defaultdict, deque from bisect import bisect_right from typing import List, DefaultDict def readarray(typ): return list(map(typ, stdin.readline().split())) def readint(): return int(input()) for _ in range(readint()): ...
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" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def binary_trie(): G0, G1, cnt = [-1], [-1], [0] return G0, G1, cnt def insert(x, l): j = 0 for i in range(l, -1, -1): cnt[j] += 1 if x & pow2[i]: if G1[j] == -1: G0.append(-1)...
py
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can...
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
import sys import math input = sys.stdin.readline sys.setrecursionlimit(10 ** 4 + 5) test = False mod1, mod2 = 10 ** 9 + 7, 998244353 inf = 10 ** 16 + 5 lim = 10 ** 5 + 5 def test_case(): x0, y0, ax, ay, bx, by = map(int, input().split()) xs, ys, t = map(int, input().split()) x, y = [x0], [y0] w...
py
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" ]
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py import os import sys import threading from io import BytesIO, IOBase import math from heapq import heappop, heappush, heapify, heapreplace from collections import defaultdict, deque, OrderedDict, Counter from bisect import...
py
1285
F
F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8...
[ "binary search", "combinatorics", "number theory" ]
import math N = 10**5 + 10 u = [-1]*N divi = [ [] for i in range(N) ] pd = [ [] for i in range(N) ] mark = [0]*N def precalc(): for i in range(1,N) : for j in range(i,N,i) : divi[j].append(i) if i == 1 : u[i] = 1 elif (i//divi[i][1]) % divi[i][1] == 0 : u[i] = 0 else ...
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" ]
x0, y0, ax, ay, bx, by = map(int, input().split()) x, y, t = map(int, input().split()) xaxis = [];yaxis = [];dis = 3*(10 ** 16); xaxis.append(x0) yaxis.append(y0) lim=120;ans=0 for i in range(0, lim): xaxis.append(xaxis[i] * ax + bx) yaxis.append(yaxis[i] * ay + by) for j in range(0,lim): inx=j ...
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: n = b // a res = 0 while n != 1 and n % 3 == 0: res += 1 n //=3 while n != 1 and n % 2 == 0: res += 1 n //=2 if n == 1: print(res) else: print(-1)
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" ]
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase import io from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections impor...
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 math import itertools import datetime from typing import List from sys import stdin input = stdin.readline class Solution: def __init__(self): self.n, self.m = map(int, input().split()) self.mod = 998244353 def binpow(self, a: int, b: int = 998244353 - 2) -> int: ans = 1 ...
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" ]
# 2022-08-21 21:01:42.073918 # https://codeforces.com/problemset/problem/1307/C import string import sys from collections import Counter, defaultdict _DEBUG = True if not _DEBUG: input = sys.stdin.readline # print = sys.stdout.write def proc(s): n = len(s) c = Counter() t2 = defaultdict(int) ...
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" ]
import os.path from math import gcd, floor, ceil from collections import * import sys from heapq import * class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._lo...
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def bfs(s): p = [s] k = 0 visit = [0] * (n + 1) visit[s] = 1 parent = [-1] * (n + 1) while len(p) ^ k: i = p[k] for j in G[i]: if not visit[j]: visit[j] = 1 ...
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 _ in range(t): a, b, x, y = (int(i) for i in input().split()) res = max(x * b, (a - x - 1) * b, y * a, (b - y - 1) * a) print(res)
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 math import log2 for t in range(int(input())): n, m = map(int, input().split()) c = [0] * 61 s = 0 for x in map(int, input().split()): c[int(log2(x))] += 1 s += x if s < n: print(-1) continue i, res = 0, 0 while i < 60: if (1<<i...
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 collections import math MOD = 998244353 n, m = list(map(int, input().split(" "))) N = m + 1 fac = [1] * N for i in range(1, N): fac[i] = (fac[i - 1] * i) % MOD inv_fac = [1] * N inv_fac[N - 1] = pow(fac[N - 1], MOD - 2, MOD) for i in range(N - 2, -1, -1): inv_fac[i] = (inv_fac[i + 1] * (...
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" ]
t = int(input()) for _ in range(t): a = list(map(int, input().split())) a.sort() if a[0] >= 4: print(7) else: res = 0 if a[2]: res += 1 a[2] -= 1 if a[1]: res += 1 a[1] -= 1 if a[0]: res +=...
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" ]
import sys from sys import stdin from collections import deque def NC_Dij(lis,start): ret = [float("inf")] * len(lis) ret[start] = 0 visit = [] q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() visit.append(now) ...
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 from array import array # noqa: F401 from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def main(): n, m = map(int, input().split()) if n < 3: if m == 0: print(*[1, 2][:n]) ...
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 d(pa, pb): return abs(pa[0]-pb[0])+abs(pa[1]-pb[1]) put = input().split() x0, y0, ax, ay, bx, by = int(put[0]), int(put[1]), int(put[2]), int(put[3]), int(put[4]), int(put[5]) put = input().split() xs, ys, t = int(put[0]), int(put[1]), int(put[2]) p = list() while x0 <= 10 ** 19 and y0 <= 10 ** 19: ...
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()) def fonction(n,M): if any((M.count(k)>=2 and (n-1-(M[::-1].index(k)))>(M.index(k)+1)) for k in set(M)): return "YES" else: return "NO" M=[] for i in range (t): n=int(input()) L=[int(x) for x in input().split()] M.append(fonction(n,L)) for k i...
py
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse...
[ "brute force", "dp", "greedy", "implementation" ]
for i in range(int(input())): n = int(input()) a = list(map(int, input().split())) found = False for j in range(n): if a[j] % 2 == 0: found = True print(1) print(j + 1) break if not found: if n == 1: print(-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" ]
n=int(input()) q=list(map(int,input().split())) q=[0]+q qs=[0] qss=[0] for i in range(1,n): qs.append(qs[i-1]+q[i]) qss.append(qss[i-1]+qs[i]) if ((1+n)*n/2-qss[n-1])%n!=0: print(-1) else: table=[0 for i in range(1+n)] p=[0 for i in range(1+n)] p[1]=int(((1+n)*n/2-qss[n-1])/n) ...
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
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" ]
from heapq import heappush, heappop from collections import defaultdict, Counter, deque import threading import sys import bisect input = sys.stdin.readline def ri(): return int(input()) def rs(): return input() def rl(): return list(map(int, input().split())) def rls(): return list(input().split()) # thr...
py
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko...
[ "implementation", "strings" ]
n,m=[int(x) for x in input().split()] L=[x for x in input().split()] M=[x for x in input().split()] q=int(input()) res=[] M=M*n L=L*m for i in range(q): y=int(input()) y=y%(n*m) res.append(L[y-1]+M[y-1]) for k in res: print(k)
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" ]
n,s1,s2=int(input()), input(), input() left=dict() right=dict() sol=[] for i in range(n): arr1=left.get(s1[i], []) arr1.append(i+1) left[s1[i]]=arr1 arr2=right.get(s2[i], []) arr2.append(i+1) right[s2[i]]=arr2 leftunmatched=[] rightunmatched=[] for c in set(left.keys()).unio...
py
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shape...
[ "brute force", "data structures", "implementation" ]
n,k=list(map(int,input().split())) a=[input() for i in range(n)] b=set(a) E=ord("S")+ord("E")+ord("T") d=0 for i in range(n-1): for j in range(i+1,n): c='' for l in range(k): if a[i][l]==a[j][l]: c=c+a[i][l] else: c=c+chr(E-ord(...
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" ]
for p in[0]*int(input()): x=int(input().split()[1]);a=[];s=0 for c in input():a+=x-s,;s+=1-2*int(c) print(sum(y*s>=y%s==0 for y in a)if s else-(0 in a))
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" ]
n = int(input()) arr = list(map(int,input().split())) lowerBound = [(0,0), (1,arr[0])] currSum = arr[0] for i in range(1,n): currSum += arr[i] xcoord = i+1 ycoord = currSum while (len(lowerBound) > 1) and ( (ycoord - lowerBound[-1][1]) / (xcoord - lowerBound[-1][0]) <= (ycoord - lowerBound[-2][1]) / (x...
py
13
C
C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. ...
[ "dp", "sortings" ]
import heapq input() ans=0 a=[] inf=10**9 for x in map(int,input().split()): x=inf-x heapq.heappush(a,x) ans+=a[0]-x heapq.heappop(a) heapq.heappush(a,x) print(-ans)
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" ]
import sys from collections import defaultdict, deque, Counter from decimal import * from heapq import heapify, heappop, heappush import math import random import string from copy import deepcopy from itertools import combinations, permutations, product from operator import mul, itemgetter from functools impo...
py