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
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 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()) # t...
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" ]
n = int(input()) for t in range(n): m = int(input()) a = list(map(int, input().split())) ans1 = sum(a) ans2 = 0 dlina = 0 maxim = 0 for i in range(m): if dlina != m - 1: ans2 += a[i] if ans2 > 0: dlina += 1 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" ]
T = 1 for test_no in range(T): x0, y0, ax, ay, bx, by = map(int, input().split()) xs, ys, t = map(int, input().split()) LIMIT = 2 ** 62 - 1 x, y = [x0], [y0] while ((LIMIT - bx) / ax >= x[-1] and (LIMIT - by) / ay >= y[-1]): x.append(ax * x[-1] + bx) y.append(ay * y[-1] + by) n = len(x) ans = 0 for i in ...
py
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, a...
[ "greedy" ]
n = int(input()) l1 = list(map(int,input().split())) l2 = list(map(int,input().split())) s = 0 r = 0 for i in range(n): if(l1[i]==1 and l2[i]==0): s = s +1 elif(l1[i]==0 and l2[i]==1): r = r +1 if(s==r): if(s==0): print(-1) else: print(2) elif(s...
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 for _ in range(int(input())): n, d = map(int, input().split()) if d <= n: print("YES") else: low = 0 high = n flag = False while low <= high: mid = (low + high) // 2 time = mid + ceil(d / (mid + 1)) ...
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 input = sys.stdin.readline s = [ord(i)-97 for i in input().strip()] p = [[0] for i in range(26)] for i in range(len(s)): for j in range(26): p[j].append(p[j][-1]) p[s[i]][i+1] += 1 for z in range(int(input())): l, r = map(int, input().split()) if l == r: print('Ye...
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
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 def center_symmetry(xs, ys): if len(xs) & 1: return 0 curx, cury = 1e9 + 1, 1e9 + 1 for i in range(n // 2): l, r = i, i + n // 2 mx = abs(xs[l] - xs[r]) + 2 * min(xs[l], xs[r]) my = abs(ys[l] - ys[r]) + 2 * min(ys[l], ys[r]) ...
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()) minimos, maximos = [], [] asc, nasc = 0, 0 for i in range(n): sequencia = list(map(int, input().split(" ")))[1:] for j in range(len(sequencia)): if j > 0 and sequencia[j] > sequencia[j - 1]: asc += 1 break elif j == len(sequencia) - 1: nasc +...
py
1292
D
D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now suffici...
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
import copy M = 5003 Primes = [] Rob = [0] * M for x in range(2,M): if Rob[x]==0: Primes.append(x) y = x+x while y<M: Rob[y]+=1 y+=x P = len(Primes) n = int(input()) Cnt = [0] * M for a in input().split(): Cnt[int(a)] +=1 PF = [] PF.append( [0] * P) s = 0 res = 0 for k in r...
py
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It...
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
for _ in range(int(input())): string = input() len_max = 0 len = 0 for i in string: if i == 'R': len = 0 else: len += 1 if len > len_max: len_max = len print(len_max + 1)
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" ]
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : F_2_Same_Sum_Blocks_Hard.py @Time : 2023/02/08 23:31:26 @Author : @bvf ''' import sys import os from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 4096 class FastIO(IOBase): newlines = 0 def __i...
py
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)L...
[ "brute force", "math", "number theory" ]
from math import isqrt, lcm import sys x = int(input()) for i in range(isqrt(x), 0, -1): j, r = divmod(x, i) if r == 0 and lcm(i, j) == x: print(i, j) sys.exit(0)
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 math import inf,floor,ceil answers=[] smallest_prime_factor=[0]*(2*10**4+1) primes=[] for i in range(2,2*10**4+1): if smallest_prime_factor[i]==0: smallest_prime_factor[i]=i primes.append(i) j=0 while i*primes[j]<=2*10**4: smallest_prime_factor[i*primes[j]]=primes[j] ...
py
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format a...
[ "data structures", "dp" ]
from collections import defaultdict, Counter,deque from math import sqrt, log10, log, floor, factorial,gcd from bisect import bisect_left, bisect_right from itertools import permutations,combinations import sys, io, os input = sys.stdin.readline # input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # sys.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" ]
p = int(input()) for j in range (p): n, x = map(int, input().split()) s = set() num = 0 for i in input().split(): s.add(int(i)) m = max(s) if x in s: print(1) else: if x % m == 0: num += x // m else: if x//m< 1: ...
py
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+...
[ "dfs and similar", "sortings" ]
#!/usr/bin/env python3 import math import sys input = lambda: sys.stdin.readline().rstrip("\r\n") from bisect import bisect_left as bs def test_case(): n, m = map(int, input().split()) a = list(map(int, input().split())) p = sorted(list(map(lambda x: int(x)-1, input().split()))) i = 0 ...
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 = sys.stdin.readline import heapq n=int(input()) C=[tuple(map(int,input().split())) for i in range(n)] CA=[] CB=[] for ind,(a,b,c,d) in enumerate(C): CA.append((a,0,ind)) CA.append((b,1,ind)) CB.append((c,0,ind)) CB.append((d,1,ind)) CA.sort() CB.sort() SMA...
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 itertools import math import threading import time from builtins import input, range from math import gcd as gcd import sys from io import BytesIO, IOBase import queue import itertools import collections from heapq import heappop, heappush import random import os from random import randint import ...
py
1287
A
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are an...
[ "greedy", "implementation" ]
a = int(input()) for i in range(a): q = int(input()) s = input() if "A" not in s: print(0) else: w = s.index("A") d = [] e = 0 for j in range(w, q): if s[j] == "A": d.append(e) e = 0 else: ...
py
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, a...
[ "greedy" ]
n = int(input()) a = [int(l) for l in input().split()] b = [int(l) for l in input().split()] unfav = 0 fav = 0 imp = 1 for i in range(n): d = a[i] - b[i] if d == -1: unfav +=1 elif d==1: fav +=1 imp = 0 if imp == 0: if (unfav+1)%fav == 0: print((u...
py
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The...
[ "greedy", "implementation" ]
from heapq import heapify, heappop, heappush from itertools import cycle from math import sqrt,ceil import os import sys from collections import defaultdict,deque from io import BytesIO, IOBase # prime = [True for i in range(5*10**7 + 1)] # def SieveOfEratosthenes(n): # p = 2 # while (p * p <...
py
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between ...
[ "greedy", "implementation", "math" ]
# Thank God that I'm not you. from collections import Counter, deque import heapq import itertools import math import random import sys from types import GeneratorType; def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else:...
py
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of ...
[ "implementation", "math" ]
from math import gcd def sanoq(n,x): s=0 while n: s, n = s+n%x, n//x return s a=int(input()) j=0 for x in range(2,a): j+=sanoq(a,x) g=gcd(j,a-2) print(f"{j//g}/{(a-2)//g}")
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" ]
def solve(): a = input() b = input() c = input() for i in range(len(a)): if c[i] not in [a[i],b[i]]: return 'NO' return 'YES' for i in range(int(input())): print(solve())
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" ]
n, m = map(int, input().split()) numList = [x+1 for x in range(n)] backdoor = [] count = sum([(i-1) // 2 for i in range(1, n+1)]) if count < m: exit(print(-1)) while count > m: lastpop = numList.pop() count -= (lastpop - 1) // 2 if count >= m: if len(backdoor) == 0: backdoor.append(10 ** 9) e...
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, random input = lambda : sys.stdin.readline().rstrip() write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x)) debug = lambda x: sys.stderr.write(x+"\n") YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18 LI = lambda : list(map(int, input().spl...
py
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 gc import heapq import itertools import math from collections import Counter, deque, defaultdict from sys import stdout import time from math import factorial, log, gcd import sys from decimal import Decimal import threading from heapq import * from fractions import Fraction import bisect def S...
py
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" ]
n = int(input()) A = list(map(int, input().split())) from collections import defaultdict D = defaultdict(lambda: []) for r in range(n): s = 0 for l in range(r, -1, -1): s += A[l] D[s].append((l, r)) k = 0 ans = -1 for s, LR in D.items(): cand_k = 0 cand_ans = [] c...
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" ]
def tst(n, d, l): for i in range(1, n): if d >= i * l[i]: d -= l[i] * i l[0] += l[i] else: l[0] += d // i break print(l[0]) pass s = int(input()) for i in range(s): n, d = map(int, input().split()) l = list(map(int, inp...
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 os import sys from io import BytesIO, IOBase from collections import Counter, defaultdict import math import heapq import bisect import collections def ceil(a, b): return (a + b - 1) // b BUFSIZE = 8192 inf = float('inf') class FastIO(IOBase): newlines = 0 def __init__(self, file): ...
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" ]
# Thank God that I'm not you. import bisect from collections import Counter, deque import heapq import itertools import math import random import sys from types import GeneratorType; def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs)...
py
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the nu...
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
###################################################################################### #------------------------------------Template---------------------------------------# ###################################################################################### import collections import heapq import sys import math...
py
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the p...
[ "brute force", "data structures", "implementation" ]
#!/usr/bin/env python3 def solution(n: int, m: int, k: int, soldier: list) -> int: arr = soldier max_val = None pop_num_r0 = min(k, m-1) for left_r0 in range(pop_num_r0+1): right_r0 = n-pop_num_r0+left_r0 # print('l0, r0:', left_r0, right_r0) len_arr_r0 = right_r0 - left_r0 ...
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 t in range(int(input())): a, b = map(int, input().split()) print(a * (len(str(b + 1)) - 1))
py
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The...
[ "greedy", "implementation" ]
import sys input = sys.stdin.readline from collections import defaultdict n = int(input()) l = set() r = defaultdict(list) a = input()[:-1] b = input()[:-1] for i in range(n): r[b[i]].append(i) if a[i] == '?': l.add(i) ew = [] x = [0]*n for i in range(n): if a[i] != '?': ...
py
1296
D
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal...
[ "greedy", "sortings" ]
###################################################################################### #------------------------------------Template---------------------------------------# ###################################################################################### import collections import heapq import sys import math...
py
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO...
[ "data structures", "dsu", "implementation" ]
N,Q = map(int,input().split()) dat = [[0]*N for _ in range(2)] num = 0 def check(x,y): l = 0 for i in range(-1,2): if 0<=i+x<N and dat[abs(y-1)][i+x]==1: l += 1 return l num = 0 for i in range(Q): y,x = map(int,input().split()) l = check(x-1,y-1) if dat[y-1][x-1]==0: if l!=0: num += l else: num -= l...
py
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good o...
[ "constructive algorithms", "greedy", "implementation", "math" ]
for _ in range(int(input())): n,x,y=map(int,input().split()) print(max(1,min(n,x+y-n+1)),min(n,x+y-1))
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 math import heapq import bisect import functools import itertools import collections import os import sys from io import BytesIO, IOBase MOD0 = 10 ** 9 + 7 MOD1 = 998244353 BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() ...
py
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format a...
[ "data structures", "dp" ]
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if se...
py
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ...
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
from bisect import bisect_right from collections import defaultdict n=int(input()) s=input() a=[0]*n d=defaultdict(int) ind=defaultdict(int) for i,el in enumerate(s): num=200*(ord(el)-ord("a"))+d[el] d[el]+=1 a[i]=num ind[num]=i l=True q=[False]*n for i in range(n): m=min(a[i:]) ...
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" ]
import sys input = sys.stdin.readline from collections import deque def bfs(root): vis=[0]*n queue=[root,-1] queue=deque(queue) vis[root]=1 d=0 while len(queue)!=1: element = queue.popleft() if element==-1: queue.append(-1) d+=1 continue vis[element] = 1 dist[element] = d fo...
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 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
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" ]
for _ in range(int(input())): p=[el for el in input().split()] n=int(p[0]) s=p[1] ans=[0]*n num=n last=0 for i in range(n): if i==n-1 or s[i]==">": j=i while j>=last : ans[j]=num num-=1 j-=1 ...
py
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of ...
[ "implementation", "math" ]
import math n,m=([int(x) for x in input().split()]) if n==m: print(0) else: if (m/n)%2!=0 and (m/n)%3!=0: print(-1) else: a=0 b=m/n while b%2==0: b=b//2 a=a+1 c = 0 d = m /n while d % 3 == 0: d = d ...
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" ]
# 10:47- N,MOD = map(int, input().split()) fact = [1]*(N+1) for i in range(1,N+1): fact[i] = fact[i-1]*i%MOD ans = 0 for i in range(1,N+1): tmp = fact[i]*fact[N-i+1]*(N-i+1) ans += tmp ans %= MOD print(ans)
py
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position...
[ "math" ]
n = int(input()) s = input() print(n+1) #234567812222222222222222222222
py
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format a...
[ "data structures", "dp" ]
from math import * from collections import * import os from io import BytesIO, IOBase import sys from bisect import * from heapq import * MOD = 1000000007 # Code by Big Dick Daddy Dick def binpow(a, b, m): a %= m x = 1 while b > 0: if b & 1: x = x * a % m ...
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = list(input().rstrip()) cnt = [0] * 26 x = [0] * (26 * 26) for i in s: for j in range(26): x[(i - 97) + j * 26] += cnt[j] cnt[i - 97] += 1 ans = max(max(x), max(cnt)) print(ans)
py
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip...
[ "math" ]
t = int(input()) for _ in range(t): n, g, b = map(int, input().split()) if g >= n: print(n) continue # nice way to get ceiling half = (n+1) // 2 # multipler * chunk of g+b days + remainder good days remainder = half % g ans = (half//g) * (g+b) + remainder if r...
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 time # start = time.time() def escolheBits(lista, bit): if bit < 0 or len(lista) == 0: return 0 bit1, bit0 = [], [] for i in lista: if (i >> bit) & 1: bit1.append(i) else: bit0.append(i) if len(bit1) == 0: return escolh...
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" ]
x=int(input()) a=list(input()) b=list(input()) a1=[[] for i in range(26)] q=[] b1=[[] for i in range(26)] q1=[] ans=[] for i in range(len(a)): if(a[i]=='?'): q.append(i) else: a1[ord(a[i])-ord('a')].append(i) for i in range(len(b)): if(b[i]=='?'): q1.append(i) els...
py
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer numb...
[ "math" ]
# https://codeforces.com/problemset/problem/1296/B def check(n): res = n while n >= 10: k = n % 10 n = n // 10 res += n n = n + k return res for _ in range(int(input())): print(check(int(input())))
py
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey...
[ "data structures", "dp", "greedy", "math", "sortings" ]
#! /bin/env python3 n = int(input()) b = list(map(int, input().split(' '))) ans = -1000 ATshayu = {} for i in range(n): v = b[i] - i try: ATshayu[v] += b[i] except: ATshayu[v] = b[i] finally: ans = max(ans, ATshayu[v]) print(ans)
py
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are prese...
[ "data structures", "greedy", "implementation", "math" ]
[n,x]=list(map(int,input().split(" "))) arr=[0 for i in range(x)] # mex=0 index=0 ans=[] if 0: none=0 else: for i in range(n): k=int(input()) arr[k%x]+=1 while(arr[index%x]!=0): arr[index%x]-=1 index+=1 ans.append(index) for i in ans: print(i)
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" ]
def get(f): return f(input().strip()) def gets(f): return [*map(f, input().split())] for _ in range(get(int)): n = get(int) xy = sorted(gets(int) for _ in range(n)) for i in range(1, n): if xy[i][1] < xy[i - 1][1]: print('NO') break else: print('YES') p ...
py
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons ...
[ "brute force" ]
from sys import stdin input=lambda :stdin.readline()[:-1] def solve(): n,m=map(int,input().split()) s=input() p=list(map(lambda x:int(x)-1,input().split())) cnt=[0]*n for i in p: cnt[i]+=1 tmp=1 ans=[0]*26 for i in range(n-1,-1,-1): tmp+=cnt[i] ans[ord(s[i])-97]+=tmp print(...
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()) while t>0: n = int(input()) arr = list(map(int,input().split())) f = 0 arr1 = [] for i in range(n): arr1.append((arr[i],i)) arr1 = sorted(arr1) for i in range(n-1): if (arr1[i][0] == arr1[i+1][0]) and (arr1[i+1][1]-arr1[i][1])>1: f = 1 ...
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" ]
k, n = map(int, input().split()) arr = [int(x) for x in input().split()] sum = 0 for i in range(0, n): sum = sum + arr[i] if sum + k <= 0: print(i + 1) exit() if sum >= 0 : print(-1) exit() l = 1 h = 10000000000000 ans = 1000000000000000000 while l <= h : ...
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())): h = int(input()) a = sum(list(map(lambda x: int(x)%2, input().split()))) if(a==0 or a==h): print("YES") else: print("NO")
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=[int(v) for v in input().split()] w=[] q=set() for j in range(n): w.append(input()) q=set(w) c=set(["S", "E", "T"]) res=0 for j in range(n): for z in range(j+1, n): eta=[] for l in range(k): if w[j][l]==w[z][l]: eta.append(w[j][l]) else:...
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" ]
r = "" for t in range(int(input())): a, b, c = sorted(list(map(int, input().split())), reverse=True) suma = 0 if a > 0: a -= 1 suma += 1 if b > 0: b -= 1 suma += 1 if c > 0: c -= 1 suma += 1 if a > 0 and b > 0: a -= 1 b -= 1 ...
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" ]
def time(x, d): return(x+d/(x+1)) t = int(input()) for xx in range(t): n, d = map(int,input().split()) l = 0 r = d - 1 ans = "NO" if d <= n: ans = "YES" else: while l < r: m1 = (l+((r-l)//3)) m2 = (l+((2*(r-l))//3)) tm1 = time(m1, d) ...
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" ]
''' t3= 8->6|7(1)->5|4(2)->2|3(3) ''' from sys import stdin input=stdin.readline from collections import defaultdict,deque n,m=map(int,input().strip().split()) g=defaultdict(list) for _ in range(m): x,y=map(int,input().strip().split()) g[y-1].append(x-1) a=int(input()) l=list(map(lambda s:int...
py
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+...
[ "dfs and similar", "sortings" ]
T=int(input('')) while(T>0): [n,m]=list(map(int,input('').split())) arr=list([int(x) for x in input('').split()]) arr2=[0]*n vis=[0]*n for i in range(0,n): arr2[i]=arr[i] vis=[0]*n arr2.sort() temp=list(int(x) for x in input('').split()) for i in temp: i=i...
py
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l...
[ "data structures", "geometry", "greedy" ]
import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n=int(input()) a=list(map(int,input().split())) stack=[] for aa in a: stack.append([aa,1]) while len(stack)>1 and stack[-1][0]/stack[-1][1]<stack[-2][0]/stack[-2][1]: stack[-2]=[stack[-2][0]+stack[-1][0],stack[-2][1]+stack...
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
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 input=sys.stdin.readline s=list(input().rstrip()) n=len(s) cnt=[[0]*(n+1) for i in range(26)] for i in range(1,n+1): cnt[ord(s[i-1])-ord("a")][i]+=1 for j in range(26): cnt[j][i]+=cnt[j][i-1] q=int(input()) for _ in range(q): l,r=map(int,input().split()) if s[r-1]!=s[l-1]:...
py
1288
E
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array o...
[ "data structures" ]
import sys class segmenttree: def __init__(self, n, default=0, func=lambda a, b: a + b): self.tree, self.n, self.func, self.default = [0] * (2 * n), n, func, default def fill(self, arr): self.tree[self.n:] = arr for i in range(self.n - 1, 0, -1): self.tree[i] = s...
py
1292
C
C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (...
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
''' Testing Python performance @Pajenegod's solution ''' INF = 10 ** 10 def main(): #print = out.append ''' Cook your dish here! ''' # Read input and build the graph n = get_int() coupl = [[] for _ in range(n)] for _ in range(n - 1): u, v = get_list() coupl[u-1].append(v-1) ...
py
1292
E
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much...
[ "constructive algorithms", "greedy", "interactive", "math" ]
import sys t = int(input()) def get(): ans = "" for i in range(n): ans = ans + S[i] return ans def query(pat): print("Querying ", pat, file = sys.stderr) print("? " + pat, flush = True) A = list(map(int, input().split())) for k in A[1:]: for i in range(len(pat)): S[k-1+i] = pat[i] ...
py
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. ...
[ "math", "number theory", "probabilities" ]
import random n = int(input()) a = list(map(int, input().split())) limit = min(8, n) iterations = [x for x in range(n)] random.shuffle(iterations) random.shuffle(iterations) iterations = iterations[:limit] def factorization(x): primes = [] i = 2 while i * i <= x: if x % i == 0: primes.appe...
py
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are righ...
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
import sys, collections, math, bisect, heapq, random, functools input = sys.stdin.readline out = sys.stdout.flush def solve(): n,k = map(int,input().split()) edges = [[] for i in range(n + 1)] degree = [0] * (n + 1) e = [] for i in range(n - 1): u,v = map(int,input().split()) ...
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 bisect import bisect_left, bisect_right from collections import Counter, deque from functools import lru_cache from math import factorial, comb, sqrt, gcd, lcm from copy import deepcopy import heapq from sys import stdin, stdout # 加快读入速度, 但是注意后面的换行符(\n) # 如果是使用 input().split() 或者 int(input()) 之类的, 换行符就...
py
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of ...
[ "implementation", "math" ]
from math import log,ceil,gcd n = int(input()) a = 0 for i in range(2,n): m = n while m: m,r = divmod(m,i) a += r g = gcd(a,n-2) print(f"{a//g}/{(n-2)//g}")
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" ]
d4i=[0,-1,0,1] d4j=[-1,0,1,0] direction=['L','U','R','D'] back=['R','D','L','U'] def main(): # Observations: # if ri,cj==xi,yj, i,j is x # if ri,cj==-1,-1, i,j is cycle: # Steps: # Mark cycles and Xs # DFS from all X only to nodes pointing to x # Fil...
py
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. ...
[ "greedy", "implementation" ]
def solve(): n = int(input()) aseq = read_ints() i = peak = 0 while i < n and aseq[i] >= i: peak = i i += 1 prev = aseq[peak] for i in range(peak+1, n): if aseq[i] >= prev: if prev - 1 < 0: return False prev -= 1 ...
py
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ...
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
from __future__ import division, print_function import os,sys import re from io import BytesIO, IOBase 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 # from math import lo...
py
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the followi...
[ "dp", "greedy", "strings" ]
import math from collections import Counter, deque from sys import stdout import time from math import factorial, log, gcd import sys from decimal import Decimal import heapq def S(): return sys.stdin.readline().split() def I(): return [int(i) for i in sys.stdin.readline().split()] def I...
py
1294
C
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, yo...
[ "greedy", "math", "number theory" ]
def factor(n: int) -> bool: count = 0 mul = [] i = 2 while(i*i <= n): if (n%i==0): j = findOhterFactor(i, n) if(j): mul.append(i) mul.append(j) mul.append(n//i//j) return mul i+=1 r...
py
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the nu...
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
import sys from math import * from collections import * inp = lambda: sys.stdin.buffer.readline().decode().strip() out=sys.stdout.write # n=int(inp()) # arr=list(map(int,inp().split())) for _ in range(int(inp())): n,m=map(int,inp().split()) ones=m zeros=n-m buckets=ones+1 total=(n*(n+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" ]
if __name__ == '__main__': n = input() a = input() ll = a.split(' ') l = [int(x) for x in ll] # max_val = max(l) # max_bit = 0 # while max_val: # max_val >>= 1 # max_bit += 1 def solve(arr: list, bit: int) -> int: if not arr or bit < 0: ...
py
1286
C2
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients th...
[ "brute force", "constructive algorithms", "hashing", "interactive", "math" ]
from sys import stdout class String2: def __init__(self, s, b=None): if b is not None: self.b = b return self.b = [0] * 26 for i in s: self.b[ord(i) - ord('a')] += 1 def __add__(self, other): b = self.b.copy() for i in ...
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" ]
[u,v]=list(map(int,input().split(" "))) if u==0 and v==0: print(0) elif u>v or u%2!=v%2: print(-1) elif u==v: print(1) print(v) else: t=(v-u)//2 if t&u: print(3) print(str(t)+" "+str(t)+" "+str(u)) else: print(2) print(str(t)+" "+str(t^u))
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" ]
for _ in range(int(input(''))): k=list(map(int,input().split())) a,b,x,y=k[0],k[1],k[2],k[3] l=[(a-x-1)*b,a*(b-y-1),a*y,b*x] print(max(l))
py
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip...
[ "math" ]
t= int(input()) for counter in range(t): array = [int(x) for x in input().split()] allowed = array[0] // 2 finished = 0 g = array[1] b = array[2] cycle = g + b progress = cycle * (allowed // b) ans = progress leftover = allowed % b remaining = array[0] - progress if rema...
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 os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer...
py
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so so...
[ "binary search", "greedy", "ternary search" ]
import 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 = int(input()) a = [0] + list(map(int, input().split())) + [0] ma, mi = -inf, inf for i in range(1, n + 1): if not a[i] == -1 and min(a[...
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" ]
n,m=map(int,input().split()) ans=[1] if n==1 and m==0: print(*ans) exit() elif n==2 and m==0: ans.append(2) print(*ans) exit() suma=0 ans=[1,2] for i in range(3,n+1): if suma+(i-1)//2<m: ans.append(i) suma+=(i-1)//2 else: ans.append(i-1+(i-2*(m-suma)))...
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 i in range(int(input())): Number=int(input()) listNum=list(map(int,input().split())) count=sum(listNum) odd=0 even=0 for j in range(Number): if(listNum[j]%2==1): odd+=listNum[j] else: even+=listNum[j] if(count%2==1): print('YES'...
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 MAX = 1_000_005 lp = [0] * MAX pr = [] pid = {1: 0} for i in range(2, MAX): if not lp[i]: lp[i] = i pr.append(i) pid[i] = len(pr) for p in pr: if p > lp[i] or i * p >= MAX: break lp[i * p] = p n = int(input()) a = list(map(int, input().split())) ...
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 from math import sqrt, gcd, factorial, ceil, floor, pi, inf from collections import deque, Counter, OrderedDict, defaultdict from heapq import heapify, heappush, heappop #sys.setrecursionlimit(10**5) from functools import lru_cache #@lru_cache(None) #=================================================...
py
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" ]
# Author Name: Ajay Meena # Codeforce : https://codeforces.com/profile/majay1638 import sys import math import bisect import heapq from bisect import bisect_right from sys import stdin, stdout from collections import deque # -------------- INPUT FUNCTIONS ------------------ def get_ints_in_variables(): re...
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, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t = int(input()) ans = [] for _ in range(t): n, x = map(int, input().split()) a = list(map(int, input().split())) a.sort(reverse = True) s = set(a) if x in s: ans0 = 1 elif a[0] > x: ans...
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 _ in range(int(input())): n = int(input()) if n <= 3: if n == 3: print(7) else: print(1) else: if n % 2 == 0: print('1' * (n // 2)) else: print('7' + ('1' * ((n - 3) // 2)))
py
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ...
[ "greedy" ]
from bisect import * from collections import * import sys import io, os import math import random from heapq import * gcd = math.gcd sqrt = math.sqrt maxint=10**21 def ceil(a, b): a = -a k = a // b k = -k return k # arr=list(map(int, input().split())) input = io.BytesIO(os.read(0, os.fst...
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;sc = sys.stdin.readline;out=sys.stdout.write for _ in range(int(sc())): n=int(sc());s=str(input());p=[0,0];d={(0,0):1};r,l,ind=n,0,1 for e in range(n): if s[e]=='L':p[0]-=1 elif s[e]=='R':p[0]+=1 elif s[e]=='U':p[1]+=1 else:p[1]-=1 p=tuple(p) i...
py
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l...
[ "data structures", "geometry", "greedy" ]
import sys input = sys.stdin.buffer.readline n = int(input()) a = list(map(int, input().split())) stk = [] for x in a: s = x c = 1 while stk and stk[-1][0] * c >= s * stk[-1][1]: s += stk[-1][0] c += stk[-1][1] stk.pop() stk.append((s, c)) sys.stdout.write(''.join('{}\n'.forma...
py
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constructio...
[ "brute force", "data structures", "dp", "greedy" ]
import re import functools import random import sys import os import math from collections import Counter, defaultdict, deque from functools import lru_cache, reduce from itertools import accumulate, combinations, permutations from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush from...
py