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 |
|---|---|---|---|---|---|
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo... | [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | class SegmentTree():
def __init__(self,arr,func,initialRes=0):
self.f=func
self.N=len(arr)
self.tree=[0 for _ in range(4*self.N)]
self.initialRes=initialRes
for i in range(self.N):
self.tree[self.N+i]=arr[i]
for i in range(self.N-1,0,-1):
... | py |
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
# 1288D
def solve(a):
m, n = len(a), len(a[0])
maxx = max(max(t) for t in a)
def check(t):
idx = [-1] * 256
for i in range(m):
mask = 0
for j in range(n):
if a[i][j] >= t:
mask |= 1 << j
# idx: [... | py |
1312 | F | F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have t... | [
"games",
"two pointers"
] | import sys
input = sys.stdin.readline
G0=[[[[0]*5500 for i in range(6)] for j in range(6)] for k in range(6)]
G1=[[[[0]*5500 for i in range(6)] for j in range(6)] for k in range(6)]
G2=[[[[0]*5500 for i in range(6)] for j in range(6)] for k in range(6)]
for x in range(1,6):
for y in range(1,6):
... | 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"
] | for _ in range(int(input())):
n=int(input())
s=input()
k=1
res=s
for j in range(1,n+1):
mov=n-j+1
t=s[:j-1]
final=s[j-1:]
if mov%2==0:
final+=t
else:
final=final+t[::-1]
if res>final:
k=j
r... | 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, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
ans = []
for _ in range(t):
n = int(input())
l, r = [], []
s = set()
for _ in range(n):
l0, r0 = map(int, input().split())
s.add(l0)
s.add(r0)
l.append(l0)
... | 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"
] | import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
t = int(input())
for _ in range(t):
n, d = map(int, input().split())
d... | 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
input = sys.stdin.readline
s = input()[:-1]
i, j = 0, len(s)-1
c = 0
a = [-1]
b = [-1]
while i < j:
if s[i] == '(':
if i+1 != a[-1]:
c += 1
a.append(i+1)
if s[j] == ')':
if j+1 != b[-1]:
c -= 1
b.append(j+1)
if c < ... | py |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this... | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | import sys
MAX = 1_000_005
lp = [0] * MAX
pr = []
pid = {1: 0}
for i in range(2, MAX):
if not lp[i]:
lp[i] = i
pr.append(i)
pid[i] = len(pr)
for p in pr:
if p > lp[i] or i * p >= MAX:
break
lp[i * p] = p
n = int(input())
a = list(map(int, input().split()))
... | py |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji... | [
"binary search",
"data structures",
"sortings",
"two pointers"
] | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = sorted([a[i] - b[i] for i in range(n)])
ans = 0
l = 0
r = n - 1
while l < r:
if c[l] + c[r] > 0:
ans += r - l
r -= 1
else:
l += 1
print(ans)
| py |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusiv... | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
dat = [[] for _ in range(N)]
P = []
for _ in range(N-1):
a,b = map(int,input().split())
P.append((a,b))
dat[a-1].append(b-1)
dat[b-1].append(a-1)
k = []
for i in range(N):
k.append([len(dat[i]),i])
k.sort(reverse=True)
num = 0
i = []
for ... | py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun... | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | import sys
input = sys.stdin.buffer.readline
def dfs(n, a, g, p=None):
parent = [None for i in range(n+1)]
depth = [[a]]
parent[a] = a
if p is not None:
parent[p] = p
while True:
next_s = []
for x in depth[-1]:
for y in g[x]:
if par... | 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
from array import array
from bisect import *
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda dtype: [dtype(x) for x in input().split()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
tests, Mint, Mlong = 1, 2 ** 31 - 1, 2 ** 63 - 1
out = []
max... | 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
from collections import defaultdict, deque, Counter
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools impo... | py |
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"
] | t = int(input())
for _ in range(t):
n = int(input())
print(1,n-1) | py |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the n... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | from sys import setrecursionlimit
setrecursionlimit(10 ** 6)
n = int(input())
c = [0 for i in range(n + 1)]
a = [0 for i in range(n + 1)]
g = [[] for i in range(n + 1)]
def dfs(x):
List = []
for i in g[x]:
List += dfs(i)
if c[x] > len(List):
raise ValueError
List.insert(c[x],... | py |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,... | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | n = int(input())
ans = 0
mx = [0] * (10 ** 6 + 5)
mn = []
koltrue = 0
for _ in range(n):
l = list(map(int, input().split()))
mnn = l[1]
mxx = l[1]
t = False
for i in range(2, l[0] + 1):
if l[i-1] < l[i]:
t = True
mnn = min(mnn, l[i])
mxx = max(mxx, l... | py |
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 _ in range(int(input())):
n,d=map(int,input().split())
l=list(map(int,input().split()))
m_=l[0]
w=1
i=1
while d>0:
if i<n:
if l[i]>0:
if d>=(l[i]*w):
m_=m_+l[i]
d=d-(l[i]*w)
l[i]=0
... | py |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO... | [
"data structures",
"dsu",
"implementation"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, q = map(int, input().split())
s = [[0] * (n + 2) for _ in range(2)]
now = 0
ans = []
for _ in range(q):
r, c = map(int, input().split())
r -= 1
if not s[r][c]:
for i in range(c - 1, c + 2):
if... | 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"
] | from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
"""
we can just solve it column independent
"""
def answer():
ans = 0
for j in range(m):
take = [0 for i in range(n)]
for i in range(n):
x = (a[i][j] - j - 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"
] | t = int(input())
for i in range(t):
n, m = map(int, input().split())
a = list(map(int, input().split()))
if n == 1 or a[0] == m:
print(a[0])
continue
summary = sum(a[1:])
smth = summary / m
if smth >= 1:
a[0] = m
else:
a[0] += summary % m
... | py |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji... | [
"binary search",
"data structures",
"sortings",
"two pointers"
] | n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
D = [0] * n
for i in range(n):
D[i] = A[i] - B[i]
D.sort()
# find pairs which gives Di + Dj > 0
total = 0
beg = 0
end = n - 1
while (end >= beg):
while (beg < end and D[beg] + D[end] <= 0):
... | 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"
] | #Abir Kundu 31.01.2023 h
t=int (input ())
while t>0:
t-=1
n=int (input ())
if n%2==0:
print ("1"*(n//2)) # this 1s numbers will be maximum
else: #for odd
print ("7"+"1"*((n-3)//2))
# 7 needs 3 segments , we have n-3 segments
# odd -odd == even
# onl... | py |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all th... | [
"dp",
"greedy",
"sortings"
] | # 1286 A.Garland https://codeforces.com/problemset/problem/1286/A
#
def main():
n = int(input())
p = [int(j) for j in input().split()]
print(solve(n, p))
def solve(n, p):
dp = [[[float('inf')]*2 for _ in range(n+1)] for _ in range(n+1)]
dp[0][0][0] = 0
dp[0][0][1] = 0
for i in ... | 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"
] | ######################################################################################
#------------------------------------Template---------------------------------------#
######################################################################################
import collections
import heapq
import sys
import math... | 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"
] | sequencias = int(input())
cont = 0
cresc = 0
ncresc = 0
maxi = []
mini = []
for x in range(sequencias):
sequencia = str(input()).split()
s = sequencia[1:]
sint = [int(p) for p in s]
for y in range(len(sint)):
if y > 0 and sint[y] > sint[y-1]:
cresc += 1
break
el... | py |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne num... | [
"greedy",
"math",
"strings"
] | for _ in range(int(input())):
n = int(input())
s = input()
odd = []
for i in range(n):
if(int(s[i])%2 !=0):
odd.append(s[i])
if(len(odd)>=2):
odd = odd[-2:]
r = "".join(odd)
print(r)
else:
print(-1) | 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"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
n = int(input())
li = list(map(int, input().split()))
if n % 2 == 1:
ip = True
for i in range(n // 2):
if li[i] < i or li[n - 1 - i] < i:
ip = False
... | py |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the nu... | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | import sys, threading
import math
from os import path
from collections import deque
from bisect import *
from string import ascii_lowercase
from functools import cmp_to_key
from random import randint
import heapq
def readInts():
x = list(map(int, (sys.stdin.readline().rstrip().split())))
return... | py |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assu... | [
"dp",
"implementation"
] | n, h, L, R = map(int, input().split())
w = [0] + list(map(int, input().split()))
dp = [[-1 << 31] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
w[i] += w[i - 1]
dp[0][0] = 0
for i in range(1, n + 1):
for j in range(1, i + 1):
s1 = (w[i] - j) % h
s2 = (w[i] - j + 1) % h
... | 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"
] | # https://codeforces.com/problemset/problem/13/A
import math
def func_sol(raw_data):
n = int(raw_data.split('\n')[0])
s = 0
for i in range(2, n):
t = n
while t > 0:
s += t % i
t //= i
gcd = math.gcd(s, n - 2)
return f'{s // gcd}/{(n - 2) // gcd}... | py |
1324 | A | A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12... | [
"implementation",
"number theory"
] | import math
def main():
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
if n == 1:
print("YES")
continue
ok = True
for i in range(n - 1):
ok &= (abs(a[i] - a[i + 1]) & 1) == 0
if ok:
... | py |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good o... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | def solve():
n, x, y = map(int, input().split())
if x > y:
x, y = y, x
hi_left = n
if y == n:
hi_left -= 1
can_take = x + y - hi_left
best = 0
if can_take <= 0:
best = 1
else:
best = can_take
if x > can_take:
best += 1
... | 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
import collections
input = sys.stdin.readline
ints = lambda: list(map(int, input().split()))
n, m, k = ints()
special = ints()
graph = [[] for _ in range(n + 1)]
for _ in range(m):
x, y = ints()
graph[x].append(y)
graph[y].append(x)
distances = [[-1, -1] for _ in range(n + 1)]
... | py |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ... | [
"data structures",
"greedy"
] | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : F_2_Same_Sum_Blocks_Hard.py
@Time : 2023/02/08 23:31:26
@Author : @bvf
'''
import sys
import os
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 4096
class FastIO(IOBase):
newlines = 0
def __i... | py |
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"
] | t = int(input())
import bisect
for _ in range(t):
n, m = map(int, input().split())
s = input()
p = sorted(list(map(int,input().split())))
counter = [0]*26
for i in range(1,n+1):
counter[ord(s[i-1])-ord('a')] += m-bisect.bisect_left(p,i)+1
print(*counter)
| py |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all th... | [
"dp",
"greedy",
"sortings"
] | import sys
input=lambda:sys.stdin.readline().rstrip()
N=int(input())
A=list(map(int,input().split()))
if max(A)==0:
print(1 if N>1 else 0)
sys.exit()
B,L=[],[0]
rem=[N//2,(N+1)//2]
ans=2
dp,dp2=[[],[]],[[],[]]
for i in A:
if i>0:
L.append(0)
B.append(i)
rem[i%2]-=1
else:
L[-1]+=1
for i in ... | 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(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly,... | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] | import os,sys
from random import randint, shuffle
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math
# Fast... | py |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this... | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | from sys import stdin
from collections import deque, Counter, defaultdict
N = int(input())
arr = list(map(int, stdin.readline().split()))
MAX = 1_000_005
lp = [0] * MAX
pr = []
pid = {1: 0}
for i in range(2, MAX):
if not lp[i]:
lp[i] = i
pr.append(i)
pid[i] = len(pr)
for p in pr:
if p > lp[i] or i * p >= M... | 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"
] | a = int(input())
for i in range(a):
q, s = map(int, input().split(' '))
*w, = map(int, input().split(' '))
print(min(s, sum(w))) | py |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is t... | [
"bitmasks",
"greedy"
] | from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify
from math import inf, sqrt, ceil, log2
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
from typing import List
from bisect import bisect_left, bisect_right
import... | 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 sys import stdin
input=lambda :stdin.readline()[:-1]
n=int(input())
edge=[[] for i in range(n)]
for i in range(n-1):
a,b=map(lambda x:int(x)-1,input().split())
edge[a].append(b)
edge[b].append(a)
def dfs(root):
par=[-1]*n
dist=[0]*n
todo=[(root,-1)]
while todo:
v,p=todo.pop()
... | 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
class RangeMinQuery:
# O(nlog(n)) construction/space, O(1) range minimum query
def __init__(self, data):
self._data = [list(data)]
n = len(self._data[0])
# self._data[i][j] stores the min of the segment [j, j + 2 ** i] where i is in [1,2,4,8,...,log(N)]
w = 1
... | 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"
] | # https://codeforces.com/problemset/problem/1294/B
test_cases = int(input())
def handle():
lines = int(input())
points = []
for _ in range(lines):
x, y = input().split(" ")
x = int(x)
y = int(y)
points.append((x, y))
points.sort()
y_so_far = points[0][1]
fo... | 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 os
import sys
from io import BytesIO, IOBase
# region fastio
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"... | 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())
A = list(map(int,input().split()))
ans = 0
ce = 0
co = 0
for i in A:
if(i&1):
co+=1
else:
ce+=1
ans = (i&1)^ans
if ce == n:
print("NO")
elif not ans and co == n:
... | 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"
] | t = int(input())
for _ in range(t):
x = int(input())
print(1, x-1) | 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 bisect import *
from collections import *
import sys
import io, os
import math
import random
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
maxint=10**21
def ceil(a, b):
a = -a
k = a // b
k = -k
return k
# arr=list(map(int, input().split()))
input = io.BytesIO(os.read(0, os.fst... | py |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constructio... | [
"brute force",
"data structures",
"dp",
"greedy"
] | from typing import List, Tuple
def return_max(a: List[int]) -> Tuple[List[int], int]:
ans = []; prev_min = float('inf')
s = 0
for e in a:
if e < prev_min:
ans.append(e)
prev_min = e
s += e
else:
ans.append(prev_min)
s += prev_min
... | py |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constru... | [
"data structures",
"dp",
"greedy"
] | # Author Name: Ajay Meena
# Codeforce : https://codeforces.com/profile/majay1638
import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout
from collections import deque
# -------------- INPUT FUNCTIONS ------------------
def get_ints_in_variables(): re... | py |
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 |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a... | [
"implementation",
"math"
] | def solve():
n = int(input())
a = list(map(int,input().split()))
b = a.count(0)
return b + int(sum(a) + b == 0)
for i in range(int(input())):
print(solve()) | 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"
] | for _ in range(int(input())):
[n,k]=list(map(int,input().split(" ")))
arr=list(map(int,input().split(" ")))
arr.sort(reverse=True)
if arr[0]==0:
print("yes")
continue
if k==0:
print("no")
continue
if k==1:
print("yes")
continue
pow=0
while(k**pow<arr[0]):
pow+=... | 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"
] | from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify
from math import inf, sqrt, ceil, log2
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
from typing import List
from bisect import bisect_left, bisect_right
import... | 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"
] | from __future__ import division, print_function
import math
import sys
import os
from io import BytesIO, IOBase
#from collections import deque, Counter, OrderedDict, defaultdict
#import heapq
#ceil,floor,log,sqrt,factorial,pow,pi,gcd
#import bisect
#from bisect import bisect_left,bisect_right
BUFSIZE = 8192... | 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"
] | def solve():
n = int(input())
a = list(map(int, input().split()))
if a.count(-1) == n: return print(0, 0)
store = []
for i in range(n):
if a[i] == -1: continue
neighbours = []
if i > 0: neighbours.append(a[i-1])
if i < n-1: neighbours.append(a[i+1])
... | py |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position... | [
"math"
] | t=int(input())
s=input()
print(len(s)+1)
###################
| 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"
] | test_cases = int(input())
for t in range(test_cases):
s=[]
ws=list(input())
for w in ws:
if len(s) == 0 or s[-1][0] != w:
s.append((w, 1))
else:
s[-1] = (s[-1][0], s[-1][1]+1)
s.reverse()
d=0
p=0
max_l = 0
while s:
c, n = ... | py |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position... | [
"math"
] | a=int(input())
s=input()
cn,cn1=s.count('L'),s.count('R')
print(cn+cn1+1) | py |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algori... | [
"data structures",
"greedy",
"sortings"
] | import os, sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop
from functools import lru_cache
from itertools import accumulate
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(I... | 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"
] | from math import *
def get(f): return f(input().strip())
def gets(f): return [*map(f, input().split())]
for _ in range(get(int)):
n = get(int)
print('7' + '1' * (n - 3 >> 1) if n & 1 else '1' * (n >> 1))
| py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun... | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | import math
from sys import stdin
input = stdin.readline
#// - remember to add .strip() when input is a string
n = int(input())
edges = [-1]
for i in range(n):
temp = []
edges.append(temp)
for _ in range(n-1):
u,v = map(int,input().split())
edges[u].append(v)
edges[v].append(u)
#print... | 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
t = int(input())
for _ in range(t):
x = int(input())
for d in range(1, int(x**0.5) + 1):
if x % d == 0:
ab = x * d - d**2
if ab > 0 and ab % d == 0:
b = ab // d
a = x // d - b
print(a, b)
b... | 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"
] | from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify
from math import inf, sqrt, ceil
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
from typing import List
from bisect import bisect_left, bisect_right
import sys
... | 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())
for i in range(t):
n= int(input())
l=[int(x) for x in input().split()]
l.sort()
l.reverse()
print(*l) | 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 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 |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a... | [
"implementation",
"math"
] | I=input
exec(int(I())*"I();a=[*map(int,I().split())];s=a.count(0);print(s+(s+sum(a)==0));") | 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())
M=[]
def fonction(L):
D=[i+1-L[i] for i in range(len(L))]
if len(D)==len(set(D)):
return L
else:
H=sorted(L,reverse=True)
return H
for i in range (t):
n=int(input())
L=[int(x) for x in input().split()]
M.append(fonction(L))
for k in M:
f... | 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 math
from collections import Counter, deque, defaultdict
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import heapq
import itertools
import bisect
def S():
return sys.stdin.readline().split()
def I():
return [int(i) for... | py |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longe... | [
"greedy",
"implementation"
] | for _ in range (int(input())):
k=int(input())
l=list(map(int,input().split()))
print(len(set(l))) | 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"
] | import math
a=int(input());
ans=0;
for b in range(2,a):
tmp=a;
while tmp>=b:
ans+=(tmp%b);
tmp//=b;
ans+=tmp;
num=a-2
gcd=math.gcd(ans,num);
print(str(ans//gcd)+'/'+str(num//gcd));
| py |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8... | [
"binary search",
"combinatorics",
"number theory"
] |
import math
def u(x,a):
for m in divisors[x]:
sum[m]+=a
def coprime(x):
count = 0
for i in divisors[x]:
count+=sum[i]*mobius[i]
return count
n = int(input())
a = input().split(" ")
maxlcm = 0
b = [False]*100010
for x in range(n):
a[x] = int(a[x])
maxlcm = max(a[x],maxlcm)
b[a[x]] = ... | 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"
] | import math
from collections import *
def solve():
n, m = map(int, input().split())
s = input()
a = [int(i) for i in input().split()]
ans = [0 for i in range(n)]
for i in range(len(a)):
ans[a[i]-1] += 1
for i in range(n-1, 0, -1):
ans[i-1] += ans[i]
d = defaultdi... | 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 io
import os
DEBUG = False
def dfs(trie, root, preorder=None, postorder=None):
stack = [root]
seen = set()
while stack:
nodeId = stack.pop()
if nodeId not in seen:
if preorder:
preorder(nodeId)
stack.append(nodeId)
seen.add(nodeId... | 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):
obj = input()
... | 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"
] | n = int(input())
for i in range(n):
n = int(input())
sp = 0
cur = 0
while n >= 10:
sp += n // 10 * 10
cur = n // 10
n = n % 10 + cur
print(sp + n) | 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 sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from time import time
from itertools import permutations as per
from heapq import heapify,heappush,heappushpop
input=stdin.readline
R=lambda:map(int,input().spl... | 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)}
sweep = [0]*... | py |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne num... | [
"greedy",
"math",
"strings"
] | # LUOGU_RID: 101844775
for _ in range(int(input())):
n = int(input())
s = input()
a = []
for c in s:
if int(c) & 1:
a += int(c),
if len(a) < 2:
print(-1)
else:
print(a[0], a[1], sep='') | py |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero)... | [
"brute force",
"math"
] | #from highlight import *
t = int(input())
for _ in range(t):
res = float("inf")
triple = []
a, b, c = map(int, input().split())
for af in range(1, 2*a+1):
for bf in range(af, 2*b+1, af):
for cf in [c//bf*bf, c//bf*bf+bf]:
if af <= bf <= cf and abs(af-a) +... | 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"
] | for i in range(int(input())):
n,d=map(int,input().split())
print('NO') if (1-n)**2-4*(d-n)<0 else print("YES")
| 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"
] | t = int(input())
while t > 0:
t -= 1
n = int(input())
s = input()
ang, mx, cnt = 0, 0, 0
for i in range(n):
if s[i] == 'A':
ang = 1
mx = max(mx, cnt)
cnt = 0
elif ang and s[i] == 'P':
cnt += 1
mx = max(mx, cnt)
pri... | 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())
ans = list(map(int, input().split()))
ll = [0] * n
rr = [0] * n
s = 0
for i in range(n):
s |= ans[i]
ll[i] = s
s = 0
for i in range(n - 1, -1, -1):
s |= ans[i]
rr[i] = s
mx = 0
mxi = 0
for i in range(n):
s = 0
if i - 1 >= 0: s |= ll[i - 1]... | 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
import math
input = sys.stdin.readline
for __ in range(int(input())):
a, m = [int(Xx) for Xx in input().split()]
a, m = a // math.gcd(a, m), m // math.gcd(a, m)
ans = 1
i = 2
M = m
while i * i <= M:
if m % i == 0:
while m % i == 0:
m = m... | 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
# 1288D
def solve(a):
m, n = len(a), len(a[0])
maxx = max(max(t) for t in a)
def check(t):
idx = [-1] * 256
for i in range(m):
mask = 0
for j in range(n):
if a[i][j] >= t:
mask |= 1 << j
# idx: [... | py |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of ... | [
"bitmasks",
"dp",
"greedy",
"sortings"
] |
import os
import sys
from io import BytesIO, IOBase
# region fastio
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
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"
] |
def solution(n,d,piles):
maxi = piles[0]
for idx,pile in enumerate(piles):
if idx == 0:
continue
while (piles[idx] > 0) and (d - idx) >= 0:
d -= idx
piles[idx] -= 1
maxi += 1
return maxi
t = int(input())
while t > ... | py |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji... | [
"binary search",
"data structures",
"sortings",
"two pointers"
] | n = int(input())
teacher = list(map(int, input().split()))
student = list(map(int, input().split()))
store = []
for i in range(n):
store.append(teacher[i] - student[i])
store.sort()
l, r = 0, n - 1
res = 0
while l < r:
cur = store[r] + store[l]
if cur > 0:
res += r - l
r -... | 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())
for i in range(t):
n, d = input().split()
n = int(n)
d = int(d)
c = 0
for x in range(n):
if(x + math.ceil(d/(x + 1)) <= n):
print("YES")
c += 1
break
if c == 0:
print("NO") | py |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is ... | [
"implementation",
"sortings"
] | def main():
for t in range(int(input())):
n=int(input())
a=[]
for tt in range(n):
a.append(list(map(int,input().split())))
a.sort()
x,y=0,0
z=""
h=True
for i in a:
if i[0]-x>=0 and i[1]-y>=0:
z=z+"R"*... | 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"
] | for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
l=0
h=10**9+7
def check(x):
res=0
for i in range(len(arr)):
if arr[i]==-1:
if i>0 and arr[i-1]!=-1:
res=max(res,abs(arr[i-1]-x))
... | 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 |
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"
] | def main():
t = int(input())
for _ in range(t):
s = input().strip()
i = 0
n = len(s)
res = 0
j = n-1
while i < n and s[i] == '0':
i += 1
while j >= i and s[j] == '0':
j -= 1
while i <= j:
if s[i]... | py |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the followi... | [
"dp",
"greedy",
"strings"
] | import sys
input = sys.stdin.readline
from bisect import bisect
def f(x):
return ord(x)-97
for _ in range(int(input())):
s = input()[:-1]
t = input()[:-1]
d = [[] for i in range(26)]
for i, j in enumerate(s):
d[f(j)].append(i)
w = [len(d[i]) for i in range(26)]
c ... | 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"
] | from bisect import bisect
l = '001 011 022 122 223 333 444'.split()
for _ in range(int(input())): print(bisect(l, '{}{}{}'.format(*sorted(min(int(s), 4) for s in input().split())))) | 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"
] | import bisect
import sys
input = sys.stdin.readline
t = int(input())
pow2 = [1]
for _ in range(20):
pow2.append(2 * pow2[-1])
pow2 = set(pow2)
for _ in range(t):
n, d = map(int, input().split())
p = []
d0 = []
now = 0
l, l0 = [1], [1]
for i in range(2, n + 1):
p.appe... | py |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. Th... | [
"geometry",
"implementation"
] | import sys
def contains(segment,point):
return (min(segment[0][0],segment[1][0])<=point[0]<=max(segment[0][0],segment[1][0]) and
min(segment[0][1],segment[1][1])<=point[1]<=max(segment[0][1],segment[1][1]));
def length(segment):
return ((segment[0][0]-segment[1][0])**2+(segment[0][1]-segmen... | py |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any othe... | [
"dfs and similar",
"graphs",
"shortest paths"
] | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write... | py |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format a... | [
"data structures",
"dp"
] | import os, 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 |
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"
] | def output_ans(ans):
print('YES')
print(len(ans))
for x in ans:
print(x[0], x[1])
if __name__ == '__main__':
n, m, k = [int(x) for x in input().split(' ')]
ans_list = list()
ans_list.append((m - 1, 'R'))
ans_list.append((m - 1, 'L'))
for _ in range(n - 1):
... | py |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of ... | [
"implementation",
"math"
] | n,m = tuple(map(int,input().split()))
steps = 0
if n == m :
print(steps)
elif m%n != 0:
print(-1)
else:
d = m/n
while d % 2 == 0:
d /= 2
steps += 1
while d % 3 == 0:
d /= 3
steps += 1
if d != 1:
steps = -1
print(steps)
| py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.