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
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord...
[ "greedy", "implementation", "sortings" ]
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) a.sort() median = n print(a[median]-a[median-1])
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 __future__ import division, print_function import os,sys from io import BytesIO, IOBase from random import randint, randrange if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip from math import ceil, floor, factorial,...
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" ]
I=input I() r=p=0 for x,y in zip(I(),I()):r+=x>y;p+=x<y print(r and p//r+1or-1)
py
13
C
C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. ...
[ "dp", "sortings" ]
import 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
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a s...
[ "brute force", "strings" ]
t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) f = False for j in range(n): for k in range(j, n): if a[j] == a[k] and (k - j) >= 2: print('YES') f = True break if f == Tru...
py
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re...
[ "brute force", "combinatorics", "math", "number theory" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) a = list(map(int, input().split())) cnt = [0] * m for i in a: cnt[i % m] += 1 if max(cnt) >= 2: ans = 0 print(ans) exit() ans = 1 for i in range(n): ai = a[i] for j in...
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,...
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) l = pow(10, 6) + 5 c = [0] * l u = [] for _ in range(n): s = list(map(int, input().split()))[1:] f = 0 for i in range(len(s) - 1): if s[i] < s[i + 1]: f = 1 break ...
py
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re...
[ "brute force", "combinatorics", "math", "number theory" ]
import math from sys import stdin input = stdin.readline #// - remember to add .strip() when input is a string n, m = map(int,input().split()) arr = list(map(int,input().split())) if n > m: print(0) else: prod = 1 for i in range(0,n): for j in range(i+1,n): prod = (prod ...
py
1295
D
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.I...
[ "math", "number theory" ]
import math import sys input = sys.stdin.readline def prime_factorize(n): ans = [] for i in range(2, int(n ** (1 / 2)) + 1): while True: if n % i: break ans.append(i) n //= i if n == 1: break if not n == 1: ...
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" ]
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ans="NO" for i in range(n-2): if a[i] in a[i+2:]: ans="YES"; break print(ans)
py
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart in...
[ "constructive algorithms", "math", "ternary search" ]
n,m,p=map(int,input().split()) f=list(map(int,input().split())) g=list(map(int,input().split())) an=0 an2=0 for i in range(n): if f[i]%p!=0: an=i break for i in range(m): if g[i]%p!=0: an2=i break print(an+an2)
py
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any othe...
[ "dfs and similar", "graphs", "shortest paths" ]
# Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase from collections import deque def main(): n,m=map(int,input().split()) graph=[[] for _ in range(n+1)] for _ in range(m): u,v=map(int,input().spli...
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" ]
from sys import stdin N,M = map(int,stdin.readline().split()) ARRS = [list(map(int,stdin.readline().split())) for i in range(N)] def test(x): bitmasks = dict() for i,row in enumerate(ARRS): key = tuple(1 if num >= x else 0 for num in row) if key not in bitmasks: bitmasks[key] = i...
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 from array import array input = lambda: sys.stdin.buffer.readline().decode().strip() n = int(input()) if n & 1: exit(print('no')) ys, xs = array('i'), array('i') for _ in range(n): x, y = map(int, input().split()) ys.append(y) xs.append(x) curx, cury = 1e9 + 1, 1e9 + 1 f...
py
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and re...
[ "brute force", "constructive algorithms", "greedy", "strings" ]
n = int(input()) s = input() ans=0 for i in range(122,97,-1): if len(s)==1: break j = 0 while j<len(s): if len(s)==1: break if ord(s[j])==i: if j==0 or j==len(s)-1: if j==0 and ord(s[j+1])==i-1: ans+=1 s = s[1:] elif j==len(s)-1 and ord(s[j-1])==i-1: ans+=1 s ...
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by...
[ "geometry", "greedy", "math" ]
import sys input = sys.stdin.readline for _ in range(int(input())): n, x = map(int, input().split()) w = list(map(int, input().split())) a = max(w) if a >= x: for i in w: if i == x: print(1) break else: print(2) e...
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" ]
import sys, io, os import math import bisect from sys import stdin,stdout from math import gcd,floor,sqrt,log from collections import defaultdict as dd from bisect import bisect_left as bl,bisect_right as br #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline inp =lambda: int(input()) strng =lam...
py
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of...
[ "implementation", "strings" ]
for _ in range(int(input())): a = input() b = input() c = input() s = 'YES' for i in range(len(a)): if not(c[i] == a[i] or c[i] == b[i]): s = 'NO' break print(s)
py
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.E...
[ "math" ]
from itertools import accumulate from math import ceil H, n = map(int, input().split()) nums = list(map(int, input().split())) prefixsum = list(accumulate(nums)) # find the min elmnt the_min = -min(prefixsum) # calculate the iteration turns = 0 if H > the_min and prefixsum[-1] < 0: turns = cei...
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 array import array input = lambda: sys.stdin.buffer.readline().decode().strip() inp = lambda dtype: [dtype(x) for x in input().split()] debug = lambda *x: print(*x, file=sys.stderr) ceil1 = lambda a, b: (a + b - 1) // b Mint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, [] def shrink(l, r): ...
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" ]
#import io, os #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t=int(input()) for _ in range(t): n=int(input()) b=list(map(int,input().split())) a=[] for i in range(1,2*n+1): a.append(i) perm=[] visited={} for i in b: visited.update({i:1}) flag=False for i in b: ...
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" ]
from sys import stdin input = stdin.readline inp = lambda : list(map(int,input().split())) def answer(): ans = [] j = n - 1 for i in range(n): if(a[i] == '('): while(j > i and a[j] == '('): j -= 1 if(j == i):break ans.app...
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by...
[ "geometry", "greedy", "math" ]
def solve(): n, x = read_ints() aseq = read_ints() if x in aseq: return 1 amax = max(aseq) if amax > x: return 2 ans = 0--x // amax return ans def main(): t = int(input()) output = [] for _ in range(t): ans = solve() output...
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" ]
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..) import sys def main(n, d): P = [0] + list(range(n - 1)) C = [set() for _ in range(n)] for v in range(n - 1): C[v].add(v + 1) D = list(range(n)) Vd = [set() for _ in range(n)] for v in range(n): Vd[v].add(v) L = [n - 1] # B = ...
py
1304
D
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog⁡n) time for a sequence of length nn. He wants to test himself if he can implement it correctly,...
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
import sys input=sys.stdin.readline t=int(input()) for _ in range(t): n,s=input().rstrip().split() n=int(n) last=0 num=n ans1=[0]*n for i in range(n): if i==n-1 or s[i]==">": for j in range(last,i+1)[::-1]: ans1[j]=num num-=1 ...
py
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn l...
[ "binary search", "data structures", "hashing", "sortings" ]
import sys input = lambda: sys.stdin.readline().rstrip() ke = 133333333 pp = 1000000000001003 def rand(): global ke ke = ke ** 2 % pp return ((ke >> 10) % (1<<15)) + (1<<15) N = int(input()) W = [rand() for _ in range(N)] A = [] B = [] for i in range(N): a, b, c, d = map(int, in...
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 #input = sys.stdin.readline q = int(input()) for _ in range(q): ans = "YES" n,m = map(int,input().split()) mh = ml = m tx = 0 for _ in range(n): t,l,h = map(int, input().split()) if tx < t: mh += t - tx ml -= t - tx tx = t mh = min(mh, h) ml = max(ml, l) if m...
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" ]
from sys import stdin input=lambda :stdin.readline()[:-1] def solve(): n=int(input()) xy=[] for i in range(n): x,y=map(int,input().split()) xy.append((x,y)) xy.sort() nowx,nowy=0,0 ans=[] for x,y in xy: if nowx>x or nowy>y: print('NO') return while nowx<x: ...
py
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a...
[ "implementation", "math" ]
import math def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) nonz = 0 c = 0 for i in a: if i == 0: c+=1 nonz += 1 else: nonz += i if nonz ...
py
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t...
[ "dfs and similar", "dp", "greedy", "trees" ]
from bisect import bisect_right from collections import defaultdict 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.filen...
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,...
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
from bisect import bisect_right def is_seq(s, t): return (s != t[::-1]) n = int(input()) count = 0 mx, mn = [], [] for _ in range(n): _, *item = map(int, input().split()) if item == sorted(item, reverse=1): mx.append(item[-1]) mn.append(item[0]) mn.sort() for i ...
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 sys input = sys.stdin.readline def f(x, w, nw): if x > nw: return 0 s1 = w[:x].count('1') c = 0 if s1 == x: c += 1 for i in range(nw-x): if w[i] == '1': s1 -= 1 if w[i+x] == '1': s1 += 1 if s1 == x: ...
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,...
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
n = int(input()) ans = 0 mx = [0] * (10 ** 6 + 5) mn = [] koltrue = 0 for _ in range(n): l = list(map(int, input().split())) mnn = l[1] mxx = l[1] t = False for i in range(2, l[0] + 1): if l[i-1] < l[i]: t = True mnn = min(mnn, l[i]) mxx = max(mxx, l...
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, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter # from itertools import permutations,combinations def ...
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" ]
from sys import stdin input = stdin.readline inp = lambda : list(map(int,input().split())) def assign1(ans , take , what): if(what == '<'): ans.extend(take) else: if(len(ans)): this = ans.pop() ans.extend(take[::-1]) ans.append(this) e...
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by...
[ "geometry", "greedy", "math" ]
for _ in range(int(input())): n, x = map(int, input().split()) a = list(map(int, input().split())) if x in a: print(1) else: m = max(a) print(max(2, (x + m - 1) // m))
py
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, a...
[ "greedy" ]
import sys input = sys.stdin.readline n = int(input()) r = list(map(int, input().split())) b = list(map(int, input().split())) f = 0 s = 0 for i in range(n): if r[i] == 1 and b[i] == 1: pass else: if r[i] == 1: f += 1 if b[i] == 1: s += 1 if...
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 sys import stdin, stdout import __pypy__ def main(): n = int(stdin.readline()) matrix = [[]] ans = [[]] s = [] cnt = 0 for i in range(n): matrix.append([]) matrix[-1].append((-9,-9)) ans.append([]) ans[-1].append("Z") temp = list(map(in...
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 collections import Counter 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(i...
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" ]
def main(): brackets = input() length = len (brackets) left = 0 right = length - 1 ans = [] while (left < right): while (left < right and brackets[left] == ')'): left += 1 while (left < right and brackets[ri...
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" ]
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase class SortedList: def __init__(self,iterable=None,_load=200): """Initialize sorted list instance.""" if iterable is None: iterable = [] values = sorted(iterable) ...
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()) diff = list(map(int,input().split())) nums = [1] for i in diff: nums.append(nums[-1]+i) mini = min(nums) extra = 0 if mini<=0: extra = (-1)*mini + 1 for i in range(len(nums)): nums[i]+=extra result = [i for i in range(1,n+1)] if sorted(nums)==result: print(*nums) else: ...
py
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s...
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
#I = lambda: [int(i) for i in input().split()] #import io, os, sys #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # n = int(input()) # l1 = list(map(int,input().split())) # n,x = map(int,input().split()) # s = input() #mod = 1000000007 # print("Case #"+str(_+1)+":",) from collections import...
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" ]
s = input() h = [] for i in range(len(s)): h.append([-1] * 26) i = len(s) - 2 h[-1][ord(s[-1]) - 97] = len(s) - 1 while i >= 0: for j in range(26): h[i][j] = h[i+1][j] h[i][ord(s[i]) - 97] = i i -= 1 # print(h) q = int(input()) for i in range(q): x, y = map(int, input().split()) x -= 1...
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()) r=[] for i in range(t): a=input() b=input() c=input() k=0 for j in range(len(a)): if a[j]==b[j]: if c[j]!=a[j]: k=1 break else: if c[j]!=a[j] and c[j]!=b[j]: k=1 brea...
py
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constructio...
[ "brute force", "data structures", "dp", "greedy" ]
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
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
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 os os.system("cls") # clear screen # Debug mode (color output green) if os.getcwd().endswith("codeforces_py"): from colorama import Fore, Style import builtins def print(*args, **kwargs): builtins.print(Fore.GREEN, end="") builtins.print(*args, **kwargs) builtins.p...
py
1324
F
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is whi...
[ "dfs and similar", "dp", "graphs", "trees" ]
def 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
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the p...
[ "brute force", "data structures", "implementation" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t = int(input()) ans = [] inf = pow(10, 9) + 1 for _ in range(t): n, m, k = map(int, input().split()) a = list(map(int, input().split())) k = min(k, m - 1) l = m - k c = n - m ans0 = 0 for i in rang...
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" ]
n=int(input()) L=list() for i in range(n): x,y,a,b=[int(x) for x in input().split()] L.append((x,y,a,b)) for (x,y,a,b) in L: if (y-x)%(a+b)==0: print((y-x)//(a+b)) else: print(-1)
py
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.I...
[ "binary search", "brute force", "implementation" ]
import sys input = lambda: sys.stdin.buffer.readline().decode().strip() from math import inf, gcd, lcm, log, log2, floor, ceil, sqrt from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify from functools import lru_cache from itertools import permutations, accumulate, grou...
py
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a s...
[ "brute force", "strings" ]
t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) flag = 'NO' k = 0 while k < n: if a.count(a[k]) == 1: k += 1 elif a.count(a[k]) == 2: if a[k] == a[k+1]: k += 2 else: ...
py
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagram...
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
# import sys,os,io # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline PI = 3.141592653589793238460 INF = float('inf') MOD = 1000000007 # MOD = 998244353 def bin32(num): return '{0:032b}'.format(num) def add(x,y): return (x+y)%MOD def sub(x,y): return (x-y+MOD)%MOD def m...
py
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a...
[ "implementation", "math" ]
a = int(input()) for i in range(a): q = int(input()) *s, = map(int, input().split(' ')) d = 0 for j in range(q): if s[j] == 0: d += 1 s[j] = 1 if sum(s) == 0: d += 1 print(d)
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=[int(j) for j in input().split()] a=[int(j) for j in input().split()] i=1 while d>0 and i<n: if a[i]>0: a[0]+=1 a[i]-=1 d-=i else : i+=1 if d>=0: print(a[0]) else : ...
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,yellow=map(int,input().split()) print(max(1,min(n,x+yellow-n+1)),min(x+yellow-1,n))
py
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are differen...
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
a=int(input()) for i in range(a): n=int(input()) a1=list(map(int, input().split())) a2=list(map(int, input().split())) a1.sort() a2.sort() print(*a1) print(*a2)
py
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letter...
[ "brute force", "dp", "math", "strings" ]
import sys input = sys.stdin.readline from itertools import combinations s = input()[:-1] d = [] x = 0 for i in range(97, 123): d.append(chr(i)) for a, b in combinations(d, 2): c0, c1 = 0, 0 x0, x1 = 0, 0 for i in s: if i == a: c0 += 1 x0 += c1 el...
py
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord...
[ "greedy", "implementation", "sortings" ]
t=int(input()) for i in range(t): n=int(input()) l=list(map(int,input().split())) l.sort() print(l[n]-l[n-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" ]
from collections import deque from sys import stdin import sys from math import ceil sys.setrecursionlimit(3*10**5) n,m = map(int,stdin.readline().split()) rn = ceil(n**0.5) lis = [ [] for i in range(n) ] for i in range(m): u,v = map(int,stdin.readline().split()) u -= 1 v -= 1 lis[u].app...
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" ]
for i in range(int(input())): n = int(input()) s = list(map(int, input().split())) ok = False for i in range(n): for j in range(i + 2, n): if s[i] == s[j]: ok = True print('YES' if ok else 'NO')
py
1288
B
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b)...
[ "math" ]
for _ in range(int(input())) : a,b = map(int,input().split()) i = 0 x = 9 while x <= b : x*=10; x += 9; i += 1 print(a*i)
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()) a = list(map(int, input().split())) d = 0 m = 0 was = {0} for i in a: d += i was.add(d) m = min(d, m) q = -m+1 if was == {i for i in range(m, n-q+1)}: for i in a: print(q, end=' ') q += i print(q) else: print(-1)
py
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of ...
[ "implementation", "math" ]
n, m = map(int, input().split()) is_a = True if n == m: print(0) elif n * 2 == m or n * 3 == m: print(1) elif (n * 2 > m and n * 3 > m) or (m % 2 != 0 and m % 3 != 0): print(-1) else: cnt = 0 delenie = m // n while delenie != 1: if delenie % 2 != 0 and delenie % 3 != 0: ...
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" ]
def main(): import sys input = sys.stdin.buffer.readline N = int(input()) P = list(map(int, input().split())) A = list(map(float, input().split())) class LazySegTree: # Range add query def __init__(self, A, initialize=True, segfunc=min, ident=2000000000): ...
py
1288
B
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b)...
[ "math" ]
t = int(input()) for i in range(t): a,b = [i for i in input().split()] toadd = 0 cmpr = '9'*len(b) if int(b) == int(cmpr): toadd = 1 print(int(a)*(len(b)-1+toadd)) # count = 0 # for i in range(1,10001): # for j in range(1,1000): # if i+j+i*j == int(str(i)+str(j)): # ...
py
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she cam...
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
import sys input = sys.stdin.buffer.readline def radix(a): digits = len(str(max(a))) for i in range (digits): b = [[] for _ in range (10)] e = pow(10, i) for j in a: num = (j//e)%10 b[num].append(j) a *= 0 for l in b: ...
py
1285
B
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii i...
[ "dp", "greedy", "implementation" ]
from itertools import accumulate def smart(a): if a[0] <= 0 or a[-1] <= 0: return False acc = list(accumulate(a)) if 0 in acc: return False y = sum(a) minsofar = 0 for i, cursum in enumerate(acc): if cursum - minsofar >= y and (minsofar != 0 or i != len(a) - 1): ...
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by...
[ "geometry", "greedy", "math" ]
#Lockout 1 Round #4 #Problem C import sys input = lambda: sys.stdin.readline()[:-1] get_int = lambda: int(input()) get_int_iter = lambda: map(int, input().split()) get_int_list = lambda: list(get_int_iter()) flush = lambda: sys.stdout.flush() #DEBUG DEBUG = False def debug(*args): if DEBUG: pr...
py
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memor...
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
for _ in range(int(input())): n,m=map(int,input().split()) lo,hi=m,m t0=0 ans="YES" for __ in range(n): t,l,h=map(int,input().split()) lo-=t-t0;hi+=t-t0 t0=t lo,hi=max(lo,l),min(hi,h) if lo>hi:ans="NO" print(ans)
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=defaultdict(list) for i in range(n): su=0 for j in range(i,n...
py
1295
A
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit...
[ "greedy" ]
for i in range(int(input())): n=int(input()) f=n%2 k=n//2 print("7"*f + "1"*(k-f))
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" ]
import sys from math import sqrt, gcd, factorial, ceil, floor, pi, inf from collections import deque, Counter, OrderedDict from heapq import heapify, heappush, heappop #sys.setrecursionlimit(10**6) #======================================================# input = lambda: sys.stdin.readline() I = lambda: int(inp...
py
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arrange...
[ "dfs and similar", "greedy", "implementation" ]
import sys import threading from math import inf from bisect import * from collections import defaultdict, deque def li(): return list(map(int, input().split())) def nn(): return int(input().split()) def w(): return input() def solve(): word = input() if len(word) == 1: print("YES") ...
py
1290
C
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of...
[ "dfs and similar", "dsu", "graphs" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): rs, rt = get_root(s), get_root(t) if not rs ^ rt: ...
py
1284
C
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a ...
[ "combinatorics", "math" ]
# Thank God that I'm not you. from itertools import permutations, combinations; import heapq; from collections import Counter, deque; import math; import sys; from functools import lru_cache; n, mod = map(int, input().split()) factorials = [1] currMul = 1; for i in range(1, n + 1): curr...
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" ]
s = input() l = [] for j in range(len(s)): l.append(s[j]) # bracketOpen = [] # bracketClose = [] ans = [] # if len(s)%2==0 or len(s)%2==1: # for j in range(len(s)): # if l[j]=="(": # bracketOpen.append(j+1) # # for j in range(len(s)//2,len(s)): # elif l[j]==")": # ...
py
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11)...
[ "implementation" ]
n = int(input()) a = [int(x) for x in input().split()][:n] count, max = 0, 0 check1, check2 = False, False start, end = 0, 0 for i in range(n): if a[i] == 1: count += 1 if not check1: start += 1 else: count = 0 check1 = True if count > max: max = count for i in reversed(range(n)): if a[i] == 1 and no...
py
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" ]
def get(f): return f(input().strip()) def gets(f): return [*map(f, input().split())] for _ in range(get(int)): n = get(int) a = sorted(gets(int)) print(a[n] - a[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" ]
n = int(input()) for i in range(n): p,q = [int(i) for i in input().split()] if p==q: print(0) elif p<q: diff = q-p if diff%2==0: print(2) else: print(1) elif p>q: diff = p-q if diff%2==0: print(1) else: ...
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 sys from array import array from collections import deque input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: [dtype(x) for x in input().split()] inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)] debug = lambda *x: print(*x, file=sys.stderr) ceil1 = lambda a, b: (a + b - 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 = list(map(int,input().split())) ans = [0] for i in range (n-1): ans.append(ans[-1]+l[i]) a = min(ans) for i in range(n): ans[i] = ans[i] - a + 1 a = [False for i in range (n)] for i in range(n): if ans[i] <= n: a[ans[i]-1] = True bb = True for i in range(n): bb = bb and...
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())): t=int(input()) p=input() l=list(p) a='' for i in p: if int(i)%2!=0: a+=i if len(a)<2: print("-1") else: print(a[:2])
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" ]
a,b=map(int, input().split()) if a>b or (b-a)%2==1: print(-1) elif a==b: if a==0: print(0) else: print(1) print(a) else: x=(b-a)//2 if (a+x)^x==a: print(2) print(x+a,x) else: print(3) print(a,x,x)
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" ]
from heapq import heappop, heappush, heapify from math import ceil, factorial, gcd, log, floor from sys import stdin, stdout from collections import defaultdict, deque, Counter from bisect import bisect_left, bisect_right, insort_right inf = int(1e19) input = stdin.readline mod = 998244353 #D V ARAVIN...
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" ]
from math import inf n, h, l, r = map(int, input().split()) nums = list(map(int, input().split())) f = [-inf]*h f[0] = 0 for i, x in enumerate(nums): g = [-inf]*h for s in range(h): g[s] = max(f[(s-x)%h], f[(s-x+1)%h])+(l<=s<=r) f = g print(max(f))
py
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s...
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
def find(S,N,k): ans = S[k-1:] if len(ans)%2==0: ans+=S[:k-1] else: ans+=S[:k-1][::-1] return ans for _ in range(int(input())): N = int(input()) S = input() ans = [[S,1]] for k in range(2,N+1): ans.append([find(S,N,k),k]) ans.sort() print(ans[0][0]) pr...
py
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be ...
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
import sys # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ t = int(input()) for _ in range(t): n = int(input()) edges = [] for i in range(n): li, ri = map(int, input().split()) e...
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" ]
input = __import__('sys').stdin.readline n, m = map(int, input().split()) adj = [[] for _ in range(n)] for _ in range(m): u, v = map(lambda x: int(x)-1, input().split()) adj[u].append(v) adj[v].append(u) k = int(n**0.5) while k*k < n: k += 1 DFS_IN = 0 DFS_OUT = 1 # cc ans = [] ...
py
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algori...
[ "data structures", "greedy", "sortings" ]
import os,sys from io import BytesIO, IOBase from heapq import * def main(): n = int(input()) lst = [(a,b)for a,b in zip(map(int,input().split()),map(int,input().split()))] lst.sort(key=lambda xx:xx[0]) heap = [] i,ans,su = 0,0,0 while i != n: j,st = i,lst[max(0,i-1)][0] ...
py
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going...
[ "constructive algorithms", "graphs", "implementation" ]
import sys import math from collections import defaultdict,Counter # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') # m=pow(10,9)+7 n,m,k=map(int,input().split()) if k>(4*m*n-2*n-2*m): print(...
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" ]
def f0(n, m): mod = int(1e9 + 7) c = 2 * m + 1 dp = [[0] * c for _ in range(n + 1)] dp[0][0] = 1 for i in range(n): # TODO 空间压缩 / 斜率优化 for j in range(c): for k in range(j, c): dp[i + 1][k] = (dp[i + 1][k] + dp[i][j]) % mod return dp[-1][-1] ...
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" ]
#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
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 random from math import sqrt as s def dist(x1, y1, x2, y2): return s((x2 - x1) ** 2 + (y2 - y1) ** 2) def is_dot_on_line(c1, c2, dot): A = c1[1] - c2[1] B = c2[0] - c1[0] C = c1[0] * c2[1] - c2[0] * c1[1] maxx, minx = max(c1[0], c2[0]), min(c1[0], c2[0]) maxy, miny = ma...
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 diff(a,b): ans = [] for i in range(len(a)): ans.append(a[i]-b[i]) return ans a = input() n = len(a) q = int(input()) count = [[0 for i in range(26)] for j in range(n)] count[0][ord(a[0])-97] += 1 for i in range(1,n): for j in range(26): count[i][j] = count[i-1][j] count[i][ord(a[i])-97] += 1 # for i in c...
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 _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) flag=False for i in range(n): for j in range(n): if abs(a[i]-a[j])%2!=0:print("NO");flag=True;break; if flag:break if not flag: print("YES")
py
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and re...
[ "brute force", "constructive algorithms", "greedy", "strings" ]
n = int(input()) ak = input() co = 0 n1 = n while True: max1 = 'a' maxi = -1 for i in range(n): if i + 1 < n and ak[i] == chr(ord(ak[i + 1]) + 1) and max1 <= ak[i]: maxi = i max1 = ak[i] if i - 1 >= 0 and ak[i] == chr(ord(ak[i - 1]) + 1) and max1 <= ak[i]...
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" ]
class LazySegmentTree: # add operations, max queries def __init__(self, data, func=max): """initialize the lazy segment tree with data""" self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self._lazy = [0] * (2 * _size) ...
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,...
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
seq = int(input()) cresc = ncresc = h = 0 maxi = [] mini = [] for _ in range(seq): s = [int(p) for p in input().split()[1:]] c = False for i in range(1, len(s)): if s[i] > s[i-1]: cresc += 1 c = True break if not c: maxi.append(max(s)) mini.ap...
py