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
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 def tobase(n, k): ret = [] while n: ret.append( n % k) n //= k return ret ncase = int(sys.stdin.readline().strip()) while ncase: ncase -= 1 n, k = map(int, sys.stdin.readline().split()) a = list(map(int, sys.stdin.readline().split())) b = [ tobase(i, k) for i in a ] mlen = max(...
py
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shape...
[ "brute force", "data structures", "implementation" ]
import sys from math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm 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
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q...
[ "combinatorics", "greedy", "math" ]
n = int(input()) s=float(1) i=2 while i<=n: s=s+(1/i) i+=1 print(s)
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff...
[ "brute force", "data structures", "sortings" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def update(l, r, s): q, ll, rr, i = [1], [0], [l1 - 1], 0 while len(q) ^ i: j = q[i] l0, r0 = ll[i], rr[i] if l <= l0 and r0 <= r: lazy[j] += s i += 1 continue ...
py
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a cont...
[ "implementation", "strings" ]
for _ in range(int(input())): s=list(input()) zero=0 total=0 if '1' in s: for i in s[s.index('1')::]: if i=='0': zero+=1 else: total+=zero zero=0 print(total)
py
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of...
[ "implementation", "strings" ]
t = int(input()) for i in range(t): a = input() b = input() c = input() for i in range(len(a)): if c[i] != a[i] and c[i] != b[i]: print("NO") break else: print("YES")
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 r in range (t): n=int(input()) spends=n while n>=10: spends+=n//10 n=n//10+n%10 print(spends)
py
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfe...
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
import os import sys from collections import defaultdict,deque from io import BytesIO, IOBase # MOD = 998244353 # nmax = 5000 # fact = [1] * (nmax+1) # for i in range(2, nmax+1): # fact[i] = fact[i-1] * i % MOD # inv = [1] * (nmax+1) # for i in range(2, nmax+1): # inv[i] = pow(fact[i], MOD-2,...
py
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all studen...
[ "implementation" ]
def solve(): n,m = list(map(int,input().split())) return min(sum(list(map(int,input().split()))),m) for i in range(int(input())): print(solve())
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 sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def e...
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" ]
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py import os import sys from io import BytesIO, IOBase import math from heapq import heappop, heappush, heapify, heapreplace from collections import defaultdict, deque, OrderedDict from bisect import bisect_left, bisect_righ...
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 pos = 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...
py
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are prese...
[ "data structures", "greedy", "implementation", "math" ]
from 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): if(b==0): return maxint a = -a k = a // b k = -k return k # arr=list(map(int, input().split()))...
py
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re...
[ "brute force", "combinatorics", "math", "number theory" ]
n, m = map(int, input().split()) a = list(map(int, input().split())) if n > m: exit(print(0)) ans = 1 for i in range(n): for j in range(i+1, n): ans *= abs(a[i] - a[j]) ans %= m print(ans)
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" ]
s = input().split(' ') n = int(s[0]) m1 = int(s[1]) - 1 m = m1 l = [] s = "" def f(str1): i1 = m + 1 i2 = m while i1 != 0 and i1 != 1: if str1[i2] != str1[m - i2]: return False else: i2 -= 1 i1 -= 2 return True for i in range(n)...
py
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifical...
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
s = input() r = set() def foo(): global s, r rem = [] p1, p2 = 0, len(s)-1 op = True while p1 <= p2: if op: if s[p1] == '(' and p1 not in r: rem.append(p1) op = False p1 += 1 else: if s[p2] == ')' and p2 not in r: ...
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" ]
from __future__ import division, print_function import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) l = list(map(int, input().split())) # not my solution, from: https://codeforces.com/contest/1299/submission/70653333 su=[l[0]] cou=[-1,0] for k in range(1,n): nd=1 ...
py
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i...
[ "dp", "strings" ]
tt=int(input()) for _ in range(tt): s=input() t=input() flag='NO' j=0 ptr=0 while(j<len(s) and ptr<len(t)): if(s[j]==t[ptr]): ptr+=1 j+=1 else: j+=1 if(ptr==len(t)): flag='YES' else: pos=[0]*26 f...
py
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn l...
[ "binary search", "data structures", "hashing", "sortings" ]
MOD = 10**18+13 import sys readline = sys.stdin.readline from random import randrange def compress(L): L2 = list(set(L)) L2.sort() C = {v : k for k, v in enumerate(L2, 1)} return L2, C N = int(readline()) T = set() L = [None]*N for i in range(N): L[i] = tuple(map(int, ...
py
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 os import sys from io import BytesIO, IOBase from collections import Counter, defaultdict from sys import stdin, stdout import io from math import * import heapq import bisect import collections def ceil(a, b): return (a + b - 1) // b inf = float('inf') def get(): return stdin.readline().rs...
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 io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline q,x=map(int,input().split()) cant = [0]*(x+5) res=0 for i in range (q): val = int (input()) val %=x cant[val]+=1 while cant[res%x]>0: cant[res%x]-=1 res+=1 print(res)
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" ]
input() a=input().split() print(a.pop(next((x for x in zip(*(f'{int(x):30b}'for x in a))if x.count('1')==1),'1').index('1')),*a)
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" ]
a = int(input()) for i in range(a): q = input() s = input() w = input() d = "YES" for j in range(len(q)): if q[j] != w[j] and w[j] != s[j]: d = "NO" break print(d)
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" ]
def solve(): t = int(input()) for i in range(t): n = int(input()) b = list(map(int, input().split())) impossible = False a = [-1] * (2 * n) numbers = set(b) for i, x in enumerate(b): if impossible: break ...
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, io, os import math import bisect from sys import stdin,stdout from math import gcd,floor,sqrt,log from collections import defaultdict as dd from bisect import bisect_left as bl,bisect_right as br #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline inp =lambda: int(input()) strng =lam...
py
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 sys # Testing out some really weird behaviours in pypy class RangeQuery: def __init__(self, data, func=min): self.func = func self._data = _data = [list(data)] i, n = 1, len(_data[0]) while 2 * i <= n: prev = _data[-1] _data.append([func(p...
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
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()) m = [[0 for _ in range(n)], [0 for _ in range(n)]] blocked = 0 for _ in range(q): r, c = map(int, input().split()) r = r - 1 c = c - 1 row_to_check = (r + 1) % 2 if c == 0: columns_to_check = [c, c + 1] elif c == n - 1: ...
py
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ...
[ "greedy" ]
import sys import threading input=sys.stdin.readline from collections import Counter,defaultdict,deque from heapq import heappush,heappop,heapify #threading.stack_size(10**8) #sys.setrecursionlimit(10**6) def ri():return int(input()) def rs():return input() def rl():return list(map(int,input().split())) def...
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 input=sys.stdin.buffer.readline from collections import deque def dfs(): visited=[0 for i in range(n+1)] queue=deque() queue.append([1,0]) add=0 while(queue): par=queue.popleft() if(visited[par[0]]==1): continue visited[par[0]]=1 ...
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" ]
# 10:59- import sys input = lambda: sys.stdin.readline().strip() from collections import Counter N,M,K = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) recs = set() for i in range(1,int(K**0.5)+1): if K%i==0: recs.add((i,K//i)) recs.add((K//i,i)...
py
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero)...
[ "brute force", "math" ]
import sys import math import itertools input = sys.stdin.readline def solve(): a , b , c = map(int , input().split()) ansA , ansB , ansC = 1 , 1 , 1 ans = (a-1)+(b-1)+(c-1) i = 1 while i <= 2*a: tmpA = i tmpB = i tmpC = tmpB * (c//tmpB) tmpAns = abs(...
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" ]
d={} s=set() for x in input(): for y in s:d[x,y]=d.get((x,y),0)+d[y] s|={x};d[x]=d.get(x,0)+1 print(max(d.values())) num_inp=lambda: int(input()) arr_inp=lambda: list(map(int,input().split())) sp_inp=lambda: map(int,input().split()) str_inp=lambda:input()
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
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart in...
[ "constructive algorithms", "math", "ternary search" ]
import os import sys from io import BytesIO, IOBase from collections import Counter import math as mt 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 f...
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, setrecursionlimit input = stdin.readline # stdout.flush() # import string # characters = string.ascii_lowercase # digits = string.digits # setrecursionlimit(int(1e6)) # dir = [-1,0,1,0,-1] # moves = 'NESW' from random import shuffle, randint inf = float('inf') from functools im...
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 from collections import deque def norm_edge(i, j): return (i, j) if i < j else (j, i) inpt = sys.stdin.read().split('\n') n, k = map(int, inpt[0].split()) edges = [] for edge_str in inpt[1:n]: i, j = tuple(map(lambda x: int(x) - 1, edge_str.split())) edges.append(norm_edge(i, j)) degree = [0...
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
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she cam...
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
import sys input = sys.stdin.buffer.readline from functools import reduce def __flatten(A): return reduce(lambda x, y: x+y, A) def radix(a): digits = len(str(max(a))) for i in range (digits): b = [[] for _ in range (10)] e = pow(10, i) for j in a: num = (j/...
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" ]
# chalo shuru karte hai! import sys from math import * from itertools import * from heapq import heapify, heappop, heappush from bisect import bisect, bisect_left, bisect_right from collections import deque, Counter, defaultdict as dd mod = 10**9+7 # Sangeeta Singh def input(): return sys.stdin.readline()....
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 math as mt from collections import defaultdict,deque import sys from bisect import bisect_right as b_r from bisect import bisect_left as b_l # from os import path # from heapq import * mod=1000000007 INT_MAX = sys.maxsize-1 INT_MIN = -sys.maxsize # if(path.exists('inputt.txt')): # sys.st...
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" ]
for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split(" "))) if n%2: yes=1 for i in range(n): if arr[i]<min(i,n-1-i): yes=0 break print("yes" if yes else "no") else: yes=1 for i in range(n): if arr[i]<min(i,n-1-i): yes=0...
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" ]
n = int(input()) for i in range(n): a,b,c,n = [int(i) for i in input().split()] z = max(a,b,c) p = n - (z-a + z-b + z-c) if p>=0: if p%3==0: print("YES") else: print("NO") if p<0: print("NO")
py
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n b...
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
from math import sqrt import sys from functools import reduce from collections import deque import io import os # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def tinput(): return 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" ]
for _ in range(int(input())): n = int(input()) cords = [] for i in range(n): a, b = map(int, input().split()) cords.append([a, b]) cords = sorted(cords, key = lambda t: t[0]) cords = sorted(cords, key = lambda t: t[1]) prevx = 0 prevy = 0 ans = '' flag = F...
py
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifical...
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
def min_opr(s): min_oprs = 0 output = [] # While I can make an operation op = True while op: op = False # Indexes to remove from the string to_remove = set() # Two pointers a = 0 b = len(s) - 1 while a < b: # ...
py
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ...
[ "greedy" ]
import re import functools import random import sys import os import math from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, he...
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" ]
# LUOGU_RID: 101845080 for _ in range(int(input())): n, s, k = map(int, input().split()) a = list(map(int, input().split())) c = [1] + [(s - i < 1) + (s + i > n) for i in range(1, k)] for x in a: if abs(x - s) < k: c[abs(x - s)] += 1 p = 0 while p < k and c[p] == 2: ...
py
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate...
[ "binary search", "brute force", "math", "ternary search" ]
import math t = int(input()) result = [] for i in range(t): nd = list(map(int, input().split())) n = nd[0] d = nd[-1] flag = 0 if (d <= n): result.append("YES") continue for i in range(n): if (math.ceil(i + (d/(i+1))) <= n): flag = 1 ...
py
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all studen...
[ "implementation" ]
# input the number of test cases t = int(input()) # loop over range of t for i in range(t): # input the number of grades and max grade possible n,m=str(input()).split(' ') # input the list of grades grades=str(input()).split(' ') # turn the list of strings to ints because of this wretched p...
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() ans = [] c = 0 for i in range(n): c = c + 1 if s[i] == '(' else c - 1 ans.append(c) c = 0 for i in range(n): if(ans[i] < 0): c += 1 elif(ans[i] == 0 and ans[i - 1] < 0): c += 1 if(ans[-1] == 0): print(c) else: print(-1)
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 sys input=sys.stdin.readline n,m=map(int,input().split()) a=[list(map(int,input().split())) for i in range(n)] ans=0 for j in range(m): idx={} for i in range(n): idx[i*m+(j+1)]=i score_cyc=10**18 # up r=0 cyc=[0]*n for i in range(n): if a[i][j] not in idx...
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" ]
from collections import deque n,m=map(int,input().split()) h=dict() for i in range( m): u,v=map(int,input().split()) u-=1 v-=1 if v in h: h[v].append(u) else: h[v]=[u] k=int(input()) arr=[int(j)-1 for j in input().split()] p=deque([arr[-1]]) h1=dict() h1[arr[-1]]=1 E ...
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 os 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
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" ]
def PROBLEM(): n,m=map(int,input().split()) T=[] for _ in range(n): T.append(input()) S='' i=0 Nb=1 while T!=[]: P=RecherchePosPali(T,n,T[i]) if P!=-1: S=T[i]+S+T[P] T.remove(T[P]) T.remove(T[i]) n-=2 ...
py
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re...
[ "brute force", "combinatorics", "math", "number theory" ]
from sys import stdin input = stdin.readline n, m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] if n > m: print(0); quit() ans = 1 for i in range(n): for j in range(i): ans = ans*abs(a[i]-a[j])%m print(ans) # https://www.bilibili.com/read/cv8299203
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 run in range(int(input())): n=int(input()) s='' if n%2==1: s+='7' n-=3 while n>0: s+='1' n-=2 print(s)
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" ]
from collections import * from heapq import * from bisect import * from itertools import * from functools import * from math import * from string import * import operator import sys input = sys.stdin.readline def solve(): n, d = map(int, input().split()) A = list(map(int, input().split())) ...
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" ]
def strelizia(): oh_pie = 0 kaguya = 0 owe_pie = [(0, 0, 0)] while (kaguya <= oh_pie): o_pie = oh_pie while (kaguya <= o_pie): x = owe_pie[kaguya][0] p = owe_pie[kaguya][1] c = 1 l = len(stamen[x]) if (l > virm): for (to, ed) in stamen[x]: if (to != p): darling[ed - 1...
py
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo...
[ "data structures", "divide and conquer", "implementation", "sortings" ]
import sys def main(): input = sys.stdin.readline _ = int(input()) *X, = map(int, input().split()) *V, = map(int, input().split()) D = {v: i for i, v in enumerate(sorted(set(V)))} N = len(D) ans = 0 I = sorted(range(len(X)), key=lambda i: X[i]) C = BinaryIndexedTree(N) S = Bina...
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" ]
from sys import stdin input=lambda :stdin.readline()[:-1] def solve(): n=int(input()) ans=[] now=n for i in range(2,int(n**0.5)+10): if now%i==0 and len(ans)<=1: ans.append(i) now//=i ans.append(now) if len(set(ans))==3 and min(ans)!=1: print('YES') print(*ans) else...
py
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all studen...
[ "implementation" ]
q = int(input()) for i in range(q): w = input().split() n, m = w n = int(n) m = int(m) b = input().split() s = 0 for j in range(len(b)): b[j] = int(b[j]) s = s + b[j] if s > m: print(m) else: print(s)
py
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of ...
[ "implementation", "math" ]
a = input().split() b = int(a[1]) a = int(a[0]) if a == b: print("0") elif b % a != 0 or (b / a % 2 != 0 and b / a % 3 != 0): print("-1") else: b /= a count = 0 while b % 2 == 0: b /= 2 count += 1 while b % 3 == 0: b /= 3 count += 1 if b != 1: print("-1...
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" ]
def solve(): n, g, b = read_ints() good_needed = 0--n // 2 loops = 0--good_needed // g cnt = (loops - 1) * (g + b) diff = good_needed - (loops - 1) * g cnt += diff if cnt < n: cnt = n return cnt def main(): t = int(input()) output =...
py
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re...
[ "brute force", "combinatorics", "math", "number theory" ]
###################################################################################### #------------------------------------Template---------------------------------------# ###################################################################################### import collections import heapq import sys import math...
py
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t...
[ "dfs and similar", "dp", "greedy", "trees" ]
import os, sys from io import BytesIO, IOBase from collections import * 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.w...
py
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, ...
[ "math", "strings" ]
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): if(b==0): return maxint a = -a k = a // b k = -k return k # arr=list(map(int, input().split()))...
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" ]
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict BUFSIZE = 8192 class F...
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" ]
from collections import deque; import sys; input = sys.stdin.readline def bfs(s): queue = deque([s]) cv = [0] * n cv[s] = 1 par = [-1] * n while queue: u = queue.popleft() col = 1 + int(par[u] == 1) for nxt in adj[u]: if not cv[nxt]: i...
py
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ...
[ "greedy" ]
import sys, 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
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 tt in range(t): a, b, p = map(int, input().split()) s = input() cs = {'A':a, 'B':b} c = 0 i = len(s)-1 while i > 0 and c+cs[s[i-1]] <= p: # print(tt, i) c += cs[s[i-1]] i -= 1 while i > 0 and s[i-1] == s[i]: i -= 1 ...
py
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2...
[ "math" ]
n = int(input()) a = list(map(int,input().split())) lst=[ ] s = 0 flag = 0 for i in a: s+=i flag = min(flag,s) lst.append(1-flag) for i in range(1,n): lst.append(lst[-1]+a[i-1]) d = dict() for i in lst: d[i]=0 xy=0 for i in lst: d[i]+=1 if (d[i]>1): xy=1 if...
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 i in range(t): s = int(input()) sum1 = 0 while s > 9: x = s - (s % 10) s = s - x + x // 10 sum1 += x sum1 += s print(sum1)
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 solve(): num_values = int(input()) values = [int(each) for each in input().split()] if num_values == 1: print(values[0]) return right_and = [values[0]] left_and = [values[-1]] for i in range(1, num_values): right_and.append(values[i]|right_and[-1]) ...
py
1315
A
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to ...
[ "implementation" ]
L=[] def fonction(a,b,x,y): pr1=b*x pr2=b*(a-x-1) pr3=a*y pr4=a*(b-y-1) return max(pr1,pr2,pr3,pr4) t=int(input()) for i in range(t): a,b,x,y=[int(x) for x in input().split()] L.append(fonction(a,b,x,y)) for k in L: print(k)
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" ]
t=int(input()) for i in range(t): n=int(input()) m=input().split() a=[int(i) for i in m] odd=0 even=0 for j in a: if j%2==0: even+=j else: odd+=j if sum(a)%2==1: print("YES") else: if odd>1 and even>1: print("YES") else: print("NO")
py
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a cont...
[ "implementation", "strings" ]
for i in range(int(input())): s = input() while len(s) > 0 and s[0] == "0": s = s[1:] while len(s) > 0 and s[-1] == "0": s = s[:-1] res = 0 for x in s: if x == "0": res += 1 print(res)
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" ]
# 2022-09-04 15:27:04.802963 # https://codeforces.com/problemset/problem/1301/C import sys _DEBUG = False # _DEBUG = True if not _DEBUG: input = sys.stdin.readline print = sys.stdout.write """ 6 2 7 // 3 == 2 001001 3 + 3 001010 3 + 1 + 1 """ def proc(n, m): total_num = n *...
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" ]
n = int(input()) a = list(map(int,input().split())) bits = [0]*30 for i in a: x = 1 for j in range(30): if i&x: bits[j] += 1 x *= 2 z = -1 for i in range(29,-1,-1): if bits[i] == 1: z = i break if z >= 0: x = 2**z for i in a: if x&...
py
1312
G
G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type...
[ "data structures", "dfs and similar", "dp" ]
import sys input = sys.stdin.readline n=int(input()) T=[input().split() for i in range(n)] k=int(input()) S=list(map(int,input().split())) SETS=set(S) E=[[] for i in range(n+1)] P=[-1]*(n+1) for i in range(n): p,s=T[i] p=int(p) E[p].append((s,i+1)) P[i+1]=p for i in range(n+1): ...
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 min_p_factor = [0] * MAX pr = [] pid = {1: 0} for i in range(2, MAX): if not min_p_factor[i]: min_p_factor[i] = i pr.append(i) pid[i] = len(pr) for p in pr: if p > min_p_factor[i] or i * p >= MAX: break min_p_factor[i * p] = p n = ...
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" ]
from sys import stdin input = stdin.readline #google = lambda : print("Case #%d: "%(T + 1) , end = '') inp = lambda : list(map(int,input().split())) def answer(): cantake = set([i for i in range(1 , 2 * n + 1)]) ans = [-1 for i in range(2 * n)] for i in range(n): ans[2 * i] = a[i] ...
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" ]
# Problem: F2. Same Sum Blocks (Hard) # Contest: Codeforces - Codeforces Round #547 (Div. 3) # URL: https://codeforces.com/problemset/problem/1141/F2 # Memory Limit: 256 MB # Time Limit: 3000 ms import sys import bisect import random import io, os from bisect import * from collections import * from context...
py
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifical...
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
def f(x): y=str(x+1) return y s=list(input()) l1=[] l2=[] for j in range(len(s)): if s[j]=="(": l1.append(j) else: l2.append(j) l2.reverse() D=[] c=1 k=0 while c!=0 and len(l1)*len(l2)!=0: k=k+1 c=0 L=[] J=[] for j in range(min(len(l1),len(l2))...
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 input=lambda:sys.stdin.readline().rstrip() def trans(a,v): ret=0 for i in range(len(a)): ret*=2 ret+=a[i]>=v return ret def solve(): n,m=map(int,input().split()) a=[list(map(int,input().split())) for i in range(n)] bis=[-1,pow(10,9)+1] ans=[] while bis[1]-bis[0]>1: flg=1 mid=su...
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" ]
import math from sys import stdin from collections import Counter, defaultdict, deque from bisect import bisect_right from typing import List, DefaultDict def readarray(typ): return list(map(typ, stdin.readline().split())) def readint(): return int(input()) for _ in range(readint()): ...
py
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can...
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
import sys input = sys.stdin.buffer.readline def process(x0, y0, ax, ay, bx, by, xs, ys, t): a, b = ax, bx c, d = ay, by points = [] for i in range(60): x1 = a**i*x0+((a**i-1)//(a-1))*b y1 = c**i*y0+((c**i-1)//(c-1))*d if x1 <= 10**17 and y1 <= 10**17: ...
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" ]
for _ in range(int(input())): n,g,b=map(int,input().split()) if n%2==0: k=int(n/2) else: k=int(n/2)+1 if k%g==0: x=int(k/g) else: x=int(k/g)+1 ans=(x-1)*b+(x-1)*g gleft=k-(x-1)*g ans+=gleft if ans>=n: print(ans) else: ...
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" ]
def solve(): n = int(input()) aseq = read_ints() acc = [0] for ai in aseq: acc.append(acc[-1] + ai) # print(acc) yasser_tastiness = acc[-1] ans = min(aseq) for i, e in enumerate(aseq): if e < 0: if i + 1 < len(acc): ans = max(...
py
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positiv...
[ "greedy", "implementation", "math" ]
for i in range(int(input())): a,b = map(int,input().split()) if a == b: print(0) else: print(1 + int((a < b) ^ ((b - a) & 1)))
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" ]
for _ in range(int(input())): a,b,c=map(int,input().split()) x=float("inf") s,d,f=0,0,0 w=[] for i in range(1,11000): for j in range(i,11000,i): for k in range(j,11000,j): t=abs(a-i)+abs(b-j)+abs(c-k) if t<x: x=t s,d,f=i,j,k print(x) print(str(s)+' '+str(d)+" "+str(f))
py
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossib...
[ "greedy" ]
t=int(input()) M=[] def fonction(n,L): if max(L)>=2*n: return -1 elif len(set(L))!=len(L): return -1 else: res=list() D=list() for k in L: j=k ra=[D[i][1] for i in range(len(D))] while(( j in ra) or (j in L)) a...
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" ]
n = int(input()) s = input() ans = "YES" mx = 'a' p = '' lst = 'a' for i in range(n): if s[i] >= mx: mx = s[i] p += '0' elif s[i] == mx and i > 0 and s[i - 1] == mx: p += '0' elif s[i] == mx or s[i] < mx: p += '1' if lst > s[i]: ans = "NO" else: ...
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 sys.setrecursionlimit(200000) import math from collections import Counter from collections import defaultdict from collections import deque input = sys.stdin.readline from functools import lru_cache import heapq ############ ---- Input Functions ---- ############ def inp(): return(int(input()...
py
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tr...
[ "binary search", "dp", "greedy", "strings" ]
import sys input = lambda: sys.stdin.readline().rstrip() for _ in range(int(input())): a, b, p = map(int, input().split()) s = input() s_len = len(s) result = 1 f_used = '' for i in range(s_len - 1, 0, -1): if s[i - 1] == f_used: continue else: ...
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" ]
from sys import stdin input = stdin.readline def solve(i , prev): if(i == n):return 0 if(dp[i][prev] != -1):return dp[i][prev] ans , minus = 0 , 1 for j in range(i , n): if(prev == value[i][j]): ans = max(ans , solve(j + 1 , prev + 1) + minus) minus += 1 ...
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())) size = 320 block = [i // size for i in range(n)] par, cnt = [0] * n, [0] * n for i in range(n - 1, -1, -1): setelah = i + p[i] if setelah >= n: par[i] = i + n cnt[i] = 1 e...
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,...
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
from sys import stdin input = stdin.readline #google = lambda : print("Case #%d: "%(T + 1) , end = '') inp = lambda : list(map(int,input().split())) def answer(): minv , maxv = [] , [] canPair , ans = n , 0 for x in range(n): ok , m = False , float('inf') for i in range(1 ...
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" ]
from math import * from heapq import heappop, heappush MOD = 10**9 + 7 #input=sys.stdin.readline #map(int, input().split()) #list(map(int, input().split())) class Solution(): pass def areYouCool(n,a,b, amount): for val in range(1, min(a//amount, n-1) + 1): if (b//amount) + val >= n: ...
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" ]
#include <bits/stdc++.h> #define ll long long ll a[(int)2e3 + 5], dp[(int)2e3 + 5][(int)2e3 + 5]; ll n, h, l, r; ll vaild(int x) { return ((x >= l && x <= r) ? 1ll : 0ll); } void solve() { std::cin >> n >> h >> l >> r; for(int i = 0; i < n; ++i) std::cin >> a[i]; for(int i = (n - 1); i >=...
cpp