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
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "...
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
N, M = map(int, input().split()) setagem = set() ans = '' aux = '' for i in range(N): s = input() reverso = s[::-1] if (s == reverso): aux = reverso elif reverso in setagem: ans += reverso setagem.add(s) ans = ans[::-1] + aux + ans print(len(ans)) print(ans) #Logi...
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 sys input = sys.stdin.readline n = int(input()) w = list(map(int, input().split())) x = 0 q = [] for i in range(n): a = b = w[i] d = [a] e = [] for l in range(i+1, n): if w[l] < a: a = w[l] d.append(a) for l in range(i-1, -1, -1): if w[l] <...
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 math import random 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 from copy import deepcopy def S(): return sys.stdin.readline().split() def I(): return [int(i) for i i...
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" ]
for _ in range(int(input())): n, d = map(int, input().split()) ld, rd = 0, n * (n - 1) // 2 tn = n cd = 0 mvl = 1 while tn: vl = min(tn, mvl) ld += cd * vl cd += 1 tn -= vl mvl *= 2 if not (ld <= d <= rd): print('NO') cont...
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 = lambda: sys.stdin.readline().strip() def get_cross(a,b): A = [a,b] A.sort() if A[0][1]<A[1][0]:return None,None return max(A[0][0],A[1][0]),min(A[0][1],A[1][1]) for _ in range(int(input())): N,M = map(int, input().split()) A = [] for _ in range(N): t,l,h = map(int, inp...
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 _ in range(t): n, d = map(int, input().strip().split()) a = list(map(int, input().strip().split())) for i in range(1, n): if d == 0: break if a[i] == 0: continue if a[i] * i <= d: a[0] += a[i] d -= a[i] * i else: for j in range(a[i]-1, 0, -1): if j * i <= d: a[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" ]
from operator import add class LazySegmentTree(): def __init__(self,n,init,merge=min,merge_unit=10**18,operate=add,operate_unit=0): self.merge=merge self.merge_unit=merge_unit self.operate=operate self.operate_unit=operate_unit self.n=(n-1).bit_length() se...
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" ]
N = 505 dp1 = [N*[-1] for _ in range(N)] dp2 = N*[int(1e9)] def calculate1(): for l in range(n): dp1[l][l+1] = a[l] for d in range(2,n+1): for l in range(n+1-d): r = l + d for mid in range(l+1, r): lf = dp1[l][mid] rg = dp1[mid][r] ...
py
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format a...
[ "data structures", "dp" ]
n=int(input()) s=input() dp=[0]*n maxdp=[0]*26 for i in range(n): dp[i]=1 for j in range(ord(s[i])-ord("a")+1,26): dp[i]=max(dp[i],maxdp[j]+1) maxdp[ord(s[i])-ord("a")]=dp[i] print(max(maxdp)) print(*dp)
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" ]
from collections import Counter import math import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 MEM = dict() class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.wri...
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
1296
D
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal...
[ "greedy", "sortings" ]
import sys;sc = sys.stdin.readline;out=sys.stdout.write n, a, b, k = map(int, sc().split());ans=0 s = sorted([((int(q) % (a+b) or a+b) + a - 1) // a - 1 for q in sc().split()]) for e in s: if k>=e: k-=e;ans+=1 out(str(ans))
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" ]
from math import factorial as fact mod = 10**9 + 7 def C(n, k): return fact(n) // (fact(k) * fact(n - k)) n, m = map(int, input().split()) print(C(n + 2*m - 1, 2*m) % mod)
py
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko...
[ "implementation", "strings" ]
n,m=map(int,input().split()) a=input().split() b=input().split() for i in range(int(input())): y=int(input()) print(a[y%n-1]+b[y%m-1])
py
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; f...
[ "combinatorics", "math" ]
num_inp=lambda: int(input()) arr_inp=lambda: list(map(int,input().split())) sp_inp=lambda: map(int,input().split()) str_inp=lambda:input() M = 998244353 n, m = map(int, input().split()) f = {} f[0] = 1 for i in range(1, m+1): f[i] = f[i-1]*i%M ans = ((n-2)*pow(2, n-3, M)*f[m]*pow(f[n-1]*f[m-n+1], M-2, M...
py
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.I...
[ "binary search", "brute force", "implementation" ]
for _ in range(int(input())): n,s,k=map(int,input().split()) arr=set(el for el in list(map(int,input().split()))) start=s c=0 while start<=s and start in arr: start-=1 c+=1 start1=s while start1>=s and start1 in arr: start1+=1 c-=1 if start!=0:...
py
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" ]
def solve(): n = int(input()) a = input() ans = 0 if 'A' not in a: return 0 i = 0 while a[i] == 'P': i += 1 a = a[i:] b = [len(i) for i in a.replace('A',' ').split()] if len(b): return max(b) return 0 for i in range(int(input())): print(...
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()] cnt, ans = 0, 0 start_cnt, end_cnt = 0, 0 check = False for i in range(n): if a[i] == 1: cnt += 1 if check == False: start_cnt += 1 else: cnt = 0 check = True if cnt > ans: ans = cnt for i in range(n - 1, star...
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff...
[ "brute force", "data structures", "sortings" ]
import sys readline = sys.stdin.buffer.readline class Lazysegtree: #RAQ def __init__(self, A, intv, initialize = True, segf = min): #区間は 1-indexed で管理 self.N = len(A) self.N0 = 2**(self.N-1).bit_length() self.intv = intv max = segf self.lazy = [0]*(2*sel...
py
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the ...
[ "math" ]
def main(): t = int(input()) for _ in range(t): a, b, c, n = [int(i) for i in input().split()] mx = max(a, b, c) diff = 0 for k in [a, b, c]: diff += abs(k - mx) if n >= diff and (n - diff) % 3 == 0: print("YES") else: ...
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" ]
import os import sys from io import BytesIO, IOBase from collections import Counter, defaultdict from sys import stdin, stdout import io import math import heapq import bisect import collections def ceil(a, b): return (a + b - 1) // b inf = float('inf') def get(): return stdin.readline().rstrip() ...
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()) lst = [int(x) for x in input().split()][:n] cnt, m_cnt = 0, 0 cnt2, m_cnt2 = 0, 0 if lst[0] == lst[-1] and lst[0] == 1: for j in range(n - 1): if lst[j] == 1: cnt += 1 else: pos = j break if cnt > m_cnt: m_cnt = cnt for j in range(n - 1, pos, -1): if lst[j] == 1: cnt +=...
py
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vac...
[ "greedy", "implementation" ]
for t in range(int(input())): n, d = map(int, input().split(' ')) a = list(map(int, input().split(' '))) i = 1 while(d > 0 and i < n): m = min(d, a[i]*i)//i d -= m*i a[0] += m i += 1 print(a[0])
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 i in range(int(input())): n = int(input()) print(f"{1} {n-1}")
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 heapq import heappush, heappop from collections import defaultdict, Counter, deque import threading import sys # input = sys.stdin.readline def ri(): return int(input()) def rs(): return input() def rl(): return list(map(int, input().split())) def rls(): return list(input().split()) # threading.stack_...
py
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. ...
[ "math", "number theory", "probabilities" ]
import random prime = [1] * (10**6 + 100) div = 2 while div < 1002: i = 2 while div * i <= 10**6+99: prime[div*i] = 0 i += 1 div += 1 while prime[div] == 0 and div < 1002: div += 1 prim = [] for i in range(2,10**6+100): if prime[i] == 1: prim.append(i) def primes(a): odp = set() aa = a ...
py
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be ...
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
import io import os from collections import Counter, defaultdict, deque # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default =...
py
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-...
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
import sys input = sys.stdin.readline for _ in range(int(input())): n, k = map(int, input().split()) w = list(map(int, input().split())) while 1: if not any(w): print('YES') break if sum(i%k for i in w) > 1: print('NO') break ...
py
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array m...
[ "constructive algorithms", "sortings" ]
t = int(input()) while t: n = int(input()) arr = list(map(int, input().split())) print(*sorted(arr, reverse=True)) t -= 1
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" ]
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n, s = input().split() n = int(n) ans = [] p, i = n, 0 while i < n - 1: if s[i] == ">": ...
py
13
E
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. ...
[ "data structures", "dsu" ]
import sys input = sys.stdin.readline n, m = map(int, input().split()) p = list(map(int, input().split())) BLOCK_LENGTH = 300 block = [i//BLOCK_LENGTH for i in range(n)] jumps = [0] * n end = [0] * n for i in range(n - 1, -1, -1): nex = i + p[i] if nex >= n: jumps[i] = 1 end[...
py
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
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 bisect import collections import copy import enum import functools import heapq import itertools import math import random import re import sys import time import string from typing import List sys.setrecursionlimit(3001) input = sys.stdin.readline t = int(input()) for _ in range(t): 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=input().split() a2=input().split() a1=[int(f) for f in a1] a2=[int(f) for f in a2] a1.sort() a2.sort() for j in range(n): print(a1[j],end=" ") print() for j in range(n): print(a2[j],end=" ") pri...
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 i in range(int(input())): print(max(map(len,input().split("R")))+1)
py
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'....
[ "data structures", "implementation" ]
from sys import stdin input=lambda :stdin.readline()[:-1] def solve(): n=int(input()) s=input() x,y=0,0 ans=[10**9,-1,-1] seen=dict() seen[(x,y)]=0 for i in range(n): if s[i]=='L': x-=1 elif s[i]=='R': x+=1 elif s[i]=='U': y+=1 else: y-=1 if ...
py
1288
D
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j...
[ "binary search", "bitmasks", "dp" ]
import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import defaultdict n, m = map(int, input().split()) A = [list(map(int, input().split())) for i in range(n)] pair = [] for i in range((1<<m)-1): for j in range(i+1, 1<<m): if (i|j) == (1<<m)-1...
py
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the ...
[ "math" ]
for i in range(int(input())): a,b,c,n = map(int,input().split()) x = max(a,b,c) rem = 0 rem+=x-a rem+=x-b rem+=x-c if rem==n and n%3==0: print("YES") elif((n-rem)%3==0 and (rem>=0 and rem<=n)): print("YES") else: print("NO")
py
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ...
[ "data structures", "greedy" ]
import sys, os, io input = lambda: sys.stdin.readline().rstrip('\r\n') from collections import defaultdict n = int(input()) a = list(map(int,input().split())) has = defaultdict(list) for j in range(n): lin = 0 for i in range(j,-1,-1): lin += a[i] if lin in has and has[lin][-1]%n >= i:c...
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()) while t>0: n = int(input()) l = [int(a) for a in input().split(" ",2*n-1)] l.sort() print(l[n]-l[n-1]) t-=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" ]
# LUOGU_RID: 91828014 import sys # sys.setrecursionlimit(int(1e9)) # import random from collections import Counter, defaultdict, deque from functools import lru_cache, reduce # from itertools import accumulate,product from heapq import nsmallest, nlargest, heapify, heappop, heappush # from bisect import bisect_l...
py
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer...
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
import sys input = sys.stdin.readline from itertools import accumulate mod=10**9+7 n,m=map(int,input().split()) G=list(map(int,input().split())) CP=[[0]*(n+1) for i in range(n+1)] for i in range(m): f,e=map(int,input().split()) CP[f][e]+=1 SUMCP=[] for i in range(n+1): SUMCP.append(l...
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()) x, r=0, m/n for i in[2,3]: while r % i == 0: r/=i x+=1 print(x if r==1 else -1)
py
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko...
[ "implementation", "strings" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) s = list(input().rstrip().decode().split()) t = list(input().rstrip().decode().split()) q = int(input()) ans = [] for _ in range(q): y = int(input()) ans0 = s[(y - 1) % n] + t[(y - 1) % m]...
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" ]
q = int(input()) while q: a = int(input()) print(a+((a-1)//9)) q-=1
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" ]
# LUOGU_RID: 102224372 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 Byte...
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" ]
# for _ in range(int(input())): # n, m = map(int, input().split()) # s = input() # arr = list(map(int, input().split(' '))) # arr = arr + [n] # nums = [arr[i] - 1 for i in range(m + 1)] # numToAlpha = {i:s[i] for i in range(n)} # dic = {chr(i + 97): 0 for i in range(26)} ...
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" ]
for _ in range(int(input())): n, m = map(int, input().split()) s = input() res = [0] * 26 temp = [0] * (n + 1) p = list(map(int, input().split())) for num in p: temp[0] += 1 temp[num] -= 1 for i in range(1, n + 1): temp[i] += temp[i - 1] for i in ...
py
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is t...
[ "bitmasks", "greedy" ]
import sys input = lambda: sys.stdin.buffer.readline().decode().strip() get_bit, sz = lambda x, i: (x >> i) & 1, 47 for _ in range(int(input())): n, m = map(int, input().split()) a, mem, ans = [int(x) for x in input().split()], [0] * sz, 0 if n > sum(a): print(-1) continue ...
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" ]
import sys input=sys.stdin.readline t=int(input()) for _ in range(t): n=int(input()) s=input().rstrip() a=[[s,1]] for i in range(1,n-1): h=n-i if h%2==0:a.append([s[i:]+s[:i],i+1]) else: v=s[:i] a.append([s[i:]+v[::-1],i+1]) a....
py
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse...
[ "brute force", "dp", "greedy", "implementation" ]
import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log MOD = int(1e9 + 7) INF = int(1e20) input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()...
py
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of ...
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
import math import sys input = sys.stdin.readline n = int(input()) g = [[] for _ in range(n)] for i in range(n - 1): x, y = map(lambda i : int(i) - 1, input().split()) g[x].append((y, i)) g[y].append((x, i)) par = [-1] * n parEdge = [-1] * n dep = [0] * n stack = [0] par[0] = 0 while len(stack) > 0: cur...
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" ]
# 2022-07-03T13:40:19Z from collections import defaultdict, Counter n, k = map(int, input().split()) cards = [] for _ in range(n): cards.append(input()) c = Counter(cards) ans = 0 def another(fa, fb): if 'S' != fa and 'S' != fb: return 'S' if 'E' != fa and 'E' != fb: return 'E' retu...
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)) for s, c in stk: print('{}\n'.for...
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 run in range(int(input())): a,b,x,y=map(int,input().split()) left=x*b right=(a-1-x)*b top=a*y down=(a*(b-1-y)) print(max(left,right,top,down))
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" ]
S = input() N = len(S) cnt = [0]*26 dp = [[0]*26 for j in range(26)] for i in range(N): ch = ord(S[i]) - 97 for j in range(26): dp[j][ch] += cnt[j] cnt[ch] += 1 res = max(cnt) for i in range(26): res = max(res, max(dp[i])) print(res)
py
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero)...
[ "brute force", "math" ]
maxn = 10**4 for _ in range(int(input())): a = list(map(int, input().split())) curr = [10**5] * (2 * maxn + 10) pair = [0] * (2 * maxn + 10) for i in range(1, 2 * maxn + 1): for j in range(i, 2 * maxn + 1, i): if abs(j - a[-1]) < curr[i]: curr[i] = abs(j - a[-...
py
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t...
[ "dfs and similar", "dp", "greedy", "trees" ]
from collections import deque def bfs(st,L,d): q = deque() q.append(st) d[st] = 0 while q: a = q.popleft() for i in L[a]: if d[i] == float('inf'): q.append(i) d[i] = d[a] + 1 def solve(): n = int(input()) tree = [[] for i in range(n+1)] for i in range(n-1): a,b = map(int,i...
py
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arrange...
[ "dfs and similar", "greedy", "implementation" ]
import sys import math from collections import Counter #from decimal import * #import random alfabet = {'a': 1, 'b': 2,'c': 3,'d': 4,'e': 5,'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,'p': 16,'q': 17,'r': 18,'s': 19,'t': 20,'u': 21,'v': 22,'w': 23,'x': 24,'y': 25,'z': 26} ...
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" ]
#problem info: #problem link: from os import O_TEMPORARY import sys import argparse def main(): n,m, k = list(map(int,input().split())) steps_1 = ["R", "L", "D"] limits_1 = [m-1, m-1, 1] steps_2 = ["RUD", "L", "D"] limits_2 = [m-1,m-1, 1] steps_3 = ["RUD", "L", "U"] ...
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" ]
import os import sys from collections import Counter as ctr, deque as dq,defaultdict from io import BytesIO, IOBase from types import GeneratorType from re import search BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self...
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 import math import collections from heapq import heappush, heappop from functools import reduce input = sys.stdin.readline ints = lambda: list(map(int, input().split())) def factors(n): return list(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) i...
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" ]
# import sys # sys.stdin = open("input.txt") cupcakes = [] dp = [] def sol(): for i in range(1, n): dp[i] = max(dp[i - 1] + dp[i], dp[i]) t = int(input()) for _ in range(t): n = int(input()) cupcakes = [*map(int, input().split())] n -= 1 dp = cupcakes[1:] sol() ...
py
1313
A
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The ...
[ "brute force", "greedy", "implementation" ]
import itertools import sys input = sys.stdin.readline for _ in range(int(input())): data = sorted(map(int, input().split()), reverse=True) cases = [] for i in range(3): tmp = list(itertools.combinations([0, 1, 2], i + 1)) cases.append(tmp) cnt = 0 for i in range(3)...
py
1325
E
E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this...
[ "brute force", "dfs and similar", "graphs", "number theory", "shortest paths" ]
import collections import math def prime_range(n): sieve = [0] * n pid = {1: 0} for i in range(2, n): if not sieve[i]: sieve[i] = i pid[i] = len(pid) for j in range(i * i, n, i): if not sieve[j]: sieve[j] = i return sieve,...
py
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" ]
def left(p,x): n = len(p) l,r = 0,n-1 if p[l] == x: return 0 while l<=r: mid = (l+r)//2 if p[mid]<x: if mid != n-1: if p[mid+1] >= x: return mid+1 else: l = mid+1 else: ...
py
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "...
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
n,m=[int(x) for x in input().split()] L=[] for i in range(n): ch=input() L.append(ch) ph="" s=set() for k in L: if k==k[::-1]: ph+=k s.add(k) break for k in L: if (k[::-1] in L) and (k[::-1]!=k)and (k[::-1] not in s): ph=k+ph+k[::-1] s.add(k) e...
py
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller ...
[ "math" ]
for i in range(int(input())): x, y, a, b = map(int, input().split()) if (y - x) % (a + b) == 0: print((y - x) // (a + b)) else: print(-1)
py
1325
B
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longe...
[ "greedy", "implementation" ]
t = int(input()) for _ in range(t): n = int(input()) *l, = map(int, input().split(' ')) print(len(set(l)))
py
1312
A
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) an...
[ "geometry", "greedy", "math", "number theory" ]
for t in range(int(input())): arr = list(map(int,input().strip().split()))[:2] if(arr[0] % arr[1]): print("NO") else: print("YES")
py
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun...
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): n = int(input()) path = [set() for _ in range(n+1)] for _ in range(n-1): u1,v1 = map(int,input().split()) path[u1].add(v1) path[v1].add(u1) ini = n ...
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" ]
import threading import sys from sys import stdin input=stdin.readline sys.setrecursionlimit(10**8) from collections import defaultdict def main(): n=int(input()) arr=list(map(int,input().split())) graph=[[] for _ in range(n)] for _ in range(n-1): a,b=map(int,input().split()) ...
py
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun...
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
from sys import stdin, stdout input = stdin.buffer.readline #print = stdout.write n = int(input()) g = [[] for i in range(n + 1)] vis = [0] * (n + 1) deg = [] for i in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) def ask(a, b): print('?', a, b, flush=True) return int(input()) def...
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" ]
#1 2 3 4 5 6 7 8 #1 2 3 4 5 6 7 8 9 10 11 12 #6 #1 2 3 4 5 7 8 9 10 11 12 #1 2 3 4 5 6 import math for _ in range(int(input())): # n,m=map(int,input().split()) n=int(input()) a=list(map(int,input().split())) a.sort() # print(a) print(a[n] - a[n - 1])
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" ]
def rl(): return list(map(int,input().split())) def ri(): return int(input()) def rs(): return input() def rm(): return map(int,input().split()) def solve(): n=ri() a=rl() nm=[0 for i in range(30)] for i in range(n): s=bin(a[i])[-1:1:-1] for j in range(len(s...
py
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q...
[ "combinatorics", "greedy", "math" ]
print(sum(1/(i+1)for i in range(int(input()))))
py
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n b...
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
import sys input = sys.stdin.buffer.readline output = sys.stdout.write def adj(x, y, n, answer, T): if T: return [(direct, flipped, x+dx, y+dy) for (direct, flipped, dx, dy) in [('D', 'U', 1, 0), ('U', 'D', -1, 0), ('R', 'L', 0, 1), ('L','R', 0, -1)] if 0 <= x+dx <= n-1 and 0 <= y+d...
py
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between ...
[ "greedy", "implementation", "math" ]
import os, sys from io import BytesIO, IOBase from math import log2, ceil, sqrt, gcd from _collections import deque import heapq as hp from bisect import bisect_left, bisect_right from math import cos, sin from itertools import permutations # sys.setrecursionlimit(2*10**5+10000) BUFSIZE = 8192 class Fas...
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" ]
from collections import deque import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def bfs(s): q = deque() q.append(s) dist = [inf] * (n + 1) dist[s] = 0 while q: i = q.popleft() di = dist[i] for j in G[i]: if dist[j] == in...
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" ]
n,m=map(int,input().split()) fact=[1] for el in range(1,n+1): fact.append((fact[-1]*el)%m) ans=0 for el in range(1,n+1): t=fact[el] p=fact[n-el+1] q=(n-el+1) ans=(ans+(((t*p)%m)*q)%m)%m print(ans)
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" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = list(input().rstrip()) n = len(s) l, r = 0, n - 1 ans = [] while l < r: while l < r and s[l] & 1: l += 1 while l < r and not s[r] & 1: r -= 1 if not s[l] & 1 and s[r] & 1: ans.append(l +...
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 sys, math import heapq from dataclasses import dataclass from collections import deque from bisect import bisect_left, bisect_right input = sys.stdin.readline hqp = heapq.heappop hqs = heapq.heappush # input def ip(): return int(input()) def sp(): return str(input().rstrip()) def mip(): ...
py
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey...
[ "data structures", "dp", "greedy", "math", "sortings" ]
n=int(input()) b=list(map(int,input().split())) d={} for i in range(n): if i-b[i] in d: d[i-b[i]].append(i) else: d[i-b[i]]=[i] mx=0 for x in d: r=0 for m in d[x]: r+=b[m] mx=max(mx,r) print(mx)
py
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is t...
[ "bitmasks", "greedy" ]
import decimal import gc import heapq import math import os import random import sys from collections import Counter, deque, defaultdict from io import BytesIO, IOBase import bisect from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd =...
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" ]
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**5 + 1)] # def SieveOfEratosthenes(n): # p = 2 # while (p * p <...
py
1315
A
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to ...
[ "implementation" ]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.py' # # Created by: PyQt5 UI code generator 5.15.7 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. def f(): l1 = input().split(' '...
py
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be ...
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
import sys input = sys.stdin.buffer.readline def process(A): n = len(A) L = [] for i in range(n): l, r = A[i] L.append([l, 0, i]) L.append([r, 1, i]) L.sort() curr = set([]) L2 = [[0, None]] for I in range(2*n): x, t, i = L[I] if t==0:...
py
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are cor...
[ "greedy" ]
n = int(input()) s = input() open_c = 0 close_c = 0 seq_len = 0 total = 0 for v in s: if v == '(': open_c += 1 else: close_c += 1 if open_c < close_c: seq_len += 1 elif open_c == close_c: if seq_len >= 1: total += seq_len + 1 ...
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 import itertools import math def isPossible(A, targetVal): lowerBound = -(10 ** 18) upperBound = 10**18 for i in range(len(A)): if A[i] == -1: if i-1 >= 0 and A[i-1] != -1: lowerBound = max(lowerBound, A[i-1] - targetVal) upperBoun...
py
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then...
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
import os, sys from io import BytesIO, IOBase from array import array from itertools import accumulate import bisect import math from collections import deque # from functools import cache # cache cf需要自己提交 pypy3.9! from copy import deepcopy class FastIO(IOBase): newlines = 0 def __init__(sel...
py
1295
F
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from ...
[ "combinatorics", "dp", "probabilities" ]
import sys input = sys.stdin.readline mod=998244353 n=int(input()) LR=[list(map(int,input().split())) for i in range(n)] RMIN=1<<31 ALL=1 for l,r in LR: ALL=ALL*pow(r-l+1,mod-2,mod)%mod for i in range(n): if LR[i][1]>RMIN: LR[i][1]=RMIN RMIN=min(RMIN,LR[i][1]) LMAX=-1 for i in ...
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff...
[ "brute force", "data structures", "sortings" ]
import sys input = sys.stdin.readline from operator import itemgetter n,m,p=map(int,input().split()) W=[tuple(map(int,input().split())) for i in range(n)] A=[tuple(map(int,input().split())) for i in range(m)] M=[tuple(map(int,input().split())) for i in range(p)] Q=[[] for i in range(10**6+1)] for x,y,c in M...
py
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tr...
[ "binary search", "dp", "greedy", "strings" ]
t=int(input()); for i in range(0,t): e=input().split() a=int(e[0]) b=int(e[1]) p=int(e[2]) s=str(input()) j=len(s)-2 r=len(s) c=0 while(j>=0): l=s[j] while(s[j]==l and j>=0): j-=1 if(l=='A'): c+=a else: c+=b ...
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" ]
t = int(input("")) for test in range(t): s = int(input("")) spent = 0 while s!= 0: if s >= 10: gain = s//10 spent += gain*10 s -= gain*10 s += gain else: spent += s s = 0 print(spent)
py
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ...
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
import os, sys from io import BytesIO, IOBase from math import log2, ceil, sqrt, gcd from _collections import deque import heapq as hp from bisect import bisect_left, bisect_right from math import cos, sin from itertools import permutations from operator import itemgetter # sys.setrecursionlimit(2*10**5+1000...
py
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. ...
[ "math", "number theory", "probabilities" ]
import random # Sieve sieve_primes = [] PRIME_LIMIT = int(1e6) sieve = [False for i in range(0,PRIME_LIMIT)] for i in range(2,PRIME_LIMIT): if not sieve[i]: sieve_primes.append(i) for j in range(i*i, PRIME_LIMIT, i): sieve[j]=True # Input n = int(input()) arr=list(map(int...
py
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" ]
for _ in range(int(input())): i=2 l=[] n=int(input()) while i<=(n)**(1/2): if n%i==0: if i not in l: l.append(i) n=n/i if len(l)==2: if n not in l and n>=2: print("YES") ...
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 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
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 copy import gc import itertools from array import array from fractions import Fraction import heapq import math import operator import os, sys import profile import cProfile import random import re import string from bisect import bisect_left, bisect_right from collections import defaultdict, dequ...
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 a=int(input()) r=0 for b in range(2,a): c=a while c:r+=c%b;c//=b a-=2 d=gcd(r,a) print(f'{r//d}/{a//d}')
py