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 |
|---|---|---|---|---|---|
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())
grid=[]
for j in range(2):
grid.append([0]*n)
co=0
for j in range(q):
r,c=map(int,input().split())
r-=1
c-=1
if grid[r][c]==0:
grid[r][c]=1
e=0
if r==0:
if c-1>=0:
if grid[1][c-1]==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"
] | for i in range(int(input())):
a = [int(_) for _ in input().split()]
b = [int(_) for _ in input().split()]
if a[1] <= sum(b):
print(a[1])
else:
print(sum(b))
| 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"
] | from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
def dfs(p ,prev , lvl):
s = [[p , prev , lvl]]
while(len(s)):
p , prev , lvl = s.pop()
level[p]=lvl
parent[p][0]=prev
for i in range(1,21):
if(parent[p... | 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"
] | n=int(input())
graph=[[] for _ in range(n)]
i=0
for _ in range(n-1):
a,b=map(int,input().split())
a-=1
b-=1
graph[a].append((i,b))
graph[b].append((i,a))
i+=1
ind=-1
for i in range(n):
if len(graph[i])>=3:
ind=i
if ind==-1:
for i in range(n-1):
print(i)
e... | 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"
] | """
f[i][j], a[0,..,i-1], s[i] % h = j, maxscore
f[i][j] = max(f[i - 1][(j - a[i - 1]) % h],
f[i - 1][(j - a[i - 1] + 1) % h]) + (l <= j <= r)
"""
inf = float('inf')
n, h, l, r = list(map(int, input().split()))
a = list(map(int, input().split()))
f = [-inf] * h
f[0] = 0
for i in range(1, n + 1)... | py |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.... | [
"data structures",
"implementation"
] | for _ in range(int(input())):
n = int((input()))
s = input()
cur = (0, 0)
dic = {(0, 0): 0}
l, r = -1, n
for i, a in enumerate(s):
f, s = cur
if a == 'L':
cur = (f - 1, s)
if a == 'R':
cur = (f + 1, s)
if a == 'U':
cur =... | py |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is whi... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | # ======== author: kuanc (@kuantweets) | created: 08/04/22 01:25:01 ======== #
from sys import stdin, stderr, stdout, setrecursionlimit
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
from itertools import accumulate, combinations, permuta... | py |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the p... | [
"brute force",
"data structures",
"implementation"
] | t=int(input())
for _ in range(t):
n,m,k=[int(x) for x in input().split(' ')]
v=[int(x) for x in input().split(' ')]
i,j=0,n-1
k=min(k,m-1)
kk=k
mm=m
ans=max(v)
final=min(v)
for x in range(0,k+1):
ans=max(v)
for y in range(0,m-k):
ans=min(ans,m... | 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"
] |
t=int(input())
for x in range(t):
n=int(input())
i=2
a=[]
while(len(a)<2 and i*i<n):
if n%i==0:
n=n//i
a.append(i)
i=i+1
if len(a)==2 and n not in a:
print("YES")
print(n,*a)
else:
print("NO") | py |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ... | [
"data structures",
"greedy"
] | from collections import defaultdict
n = int(input())
nums = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
s = 0
for j in range(i, n):
s += nums[j]
d[s].append((i+1, j+1))
res = []
for a in d.values():
if len(a)<=len(res):
continue
a.sort(ke... | py |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) an... | [
"geometry",
"greedy",
"math",
"number theory"
] | for _ in range(int(input())):
a, b = map(int, input().split())
if a%b == 0:
print("YES")
else:
print("NO") | 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())
l = list(str(input()))
ans = 0
brk = False
while brk != True:
brk = False
dx = 1
act = False
for i in l[:len(l)-1]:
if i == 'A' and l[dx] == 'P':
l[dx] = 'A'
act = True
dx += 1
i... | 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"
] | from __future__ import division, print_function
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
alphabets = list('abcdefghijklmnopqrstu... | 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 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 |
1286 | C1 | C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients th... | [
"brute force",
"constructive algorithms",
"interactive",
"math"
] | mod = 1000000007
eps = 10**-9
def main():
import sys
from collections import Counter
input = sys.stdin.readline
def ask(l, r):
print(*["?", l, r])
sys.stdout.flush()
N = int(input())
ask(1, N)
ret1 = []
for _ in range(N * (N+1) // 2):
s = inpu... | py |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P... | [
"geometry"
] | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def fun(a):
return a[0]**2+a[1]**2
def main():
n = int(input())
if n%2:
for _ in range(n):
input()
print('NO')
else:
arr = [tuple(map(int,input(... | py |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.I... | [
"binary search",
"brute force",
"implementation"
] | for _ in range(int(input())):
n,s,k=map(int,input().split())
ll=list(map(int,input().split()))
m=(10**9)+1
for t in range(max(1,s-1000),min(n+1,s+1001)):
if t not in ll and abs(s-t)<m:
m=abs(s-t)
print(m) | py |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are differen... | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | 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 = int(input())
print(*sorted(map(int, input().split())))
print(*s... | 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"
] | from statistics import median
import sys
from bisect import bisect_right, bisect_left
import os
import sys
from io import BytesIO, IOBase
from math import factorial, floor, inf, ceil, gcd
from collections import defaultdict, deque, Counter
from functools import cmp_to_key
from heapq import heappop, heappush, heapify
B... | py |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse... | [
"brute force",
"dp",
"greedy",
"implementation"
] | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
ie = next((i for i, ai in enumerate(a, 1) if ai & 1 == 0), None)
if ie is not None:
print(1)
print(ie)
elif n >= 2:
print(2)
print(1, 2)
else:
print(-1)
| 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
def subtree(v):
queue, vis = [v], [False] * (n + 1)
vis[v] = True
while queue:
s = queue.pop()
for i1 in gdict[s]:
if not vis[i1]:
queue.append(i1)
vis[i1] = True
par[i1], level[i1] = s, level[s] + 1
... | 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 x in range(n):
t = int(input())
print(int(t * 1.1111111111111))
| 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"
] | #!/usr/bin/env python3
import math
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
from bisect import bisect_left as bs
def test_case():
n, m = map(int, input().split())
s = input()
p = list(map(int, input().split()))
pref = [[0 for _ in range(26)] for _ in range(n+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"
] |
n = int(input())
A = list(map(int,input().split()))
T = list(map(int,input().split()))
import heapq
nums = list(zip(A,T))
nums.sort(key=lambda x:(x[0],-x[1]))
# print(nums)
total = 0
res = 0
cur = -1
i = 0
heap = []
while i < n or heap:
if not heap:
cur = nums[i][0]
while i < n and nums[i][0] ==... | py |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)L... | [
"brute force",
"math",
"number theory"
] | from collections import Counter
import math
n = int(input())
num = Counter()
ans = 0
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
num[i] = n // i
re = num.most_common()
re.reverse()
for i in re:
if math.gcd(i[0], i[1]) == 1:
print(*i)
break
| py |
1292 | E | E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much... | [
"constructive algorithms",
"greedy",
"interactive",
"math"
] | from collections import defaultdict
from itertools import product
from sys import stdout
def find(s, t):
return tuple(i for i in range(len(s) - len(t) + 1) if s[i:i+len(t)] == t)
class Mock:
def __init__(self, s):
self.s = s
self.cost = 0.0
@property
def n(self):
return len(... | 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
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n,d=map(int,input().split())
max=n*(n-1)//2
if d>max:
print('NO')
continue
dif=max-d
tree=[1]*n
move_to,move_from=1,n-1
while move_from>move_to:
if dif>move_from-move_to:
t... | py |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)L... | [
"brute force",
"math",
"number theory"
] | #! /bin/env python3
# please follow ATshayu
def main():
def gcd(a, b): return a if b == 0 else gcd(b, a%b)
X = int(input())
a, b = 1, 1
ATshayu = int(1e15)
for i in range(1, int(1e6)+1):
if X%i != 0: continue
if gcd(i, X//i) == 1: ATshayu = min(ATshayu, max(i, X//i))
... | 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"
] | #AUTHOR-Jonte_98
import sys
from math import gcd
input = sys.stdin.readline
n = int(input())
A = [int(i) for i in input().split()]
divisors = [[] for _ in range(10**5+2)]
mobius = [1 for _ in range(10**5+2)]
#get all the divisors for every number from 1 to 10**5
for i in range(1,10**5+1):
for j in rang... | py |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, whe... | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | from sys import stdin
input = stdin.readline
def solve(root , bit):
if(trie[root] == [-1 , -1]):return 0
if(trie[root][0] != -1 and trie[root][1] == -1):
ans = solve(trie[root][0] , bit - 1)
elif(trie[root][0] == -1 and trie[root][1] != -1):
ans = solve(trie[root][1] , bit -... | 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"
] | try:
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
... | 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"
] | def solve():
a, b, p = read_ints()
seq = input()
cost = []
prev = '$'
c = 0
for i, e in enumerate(seq, start=1):
if e != prev:
c = a if e == 'A' else b
cost.append((i, c))
prev = e
c = 0
for i in range(len(cost)-1, -1, -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"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
n, q = map(int, input().split())
cur = [[0] * n for _ in range(2)]
trouble_ups = set()
for _ in range(q):
x, y = map(int, input().split())
x -= 1
y -= 1
if x == 0:
if cur[0][y] == 0:
cur[0][y] = 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"
] | def solve(a):
m, n = len(a), len(a[0])
maxx = max(max(t) for t in a)
def ok(t):
idx = [-1] * 256
maxm = 1 << n
for i in range(m):
mask = 0
for j in range(n):
if a[i][j] >= t: mask |= 1 << j
if idx[mask] == -1:
... | py |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate... | [
"binary search",
"brute force",
"math",
"ternary search"
] | from math import ceil
for _ in range(int(input())):
n, d = [int(i) for i in input().split()]
if ceil(d/(n//2+1))+n//2 <= n : print("YES")
else : print("NO") | 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 bisect
def getsum(tree , i):
s=0
i+=1
while i>0:
s+=tree[i]
i-=i&(-i)
return s
def updatebit(tree , n , i , v):
i+= 1
while i <= n:
tree[i] += v
i += i & (-i)
n = int(input())
x = list(map(int , input().split()))
v = list(map(int , input().split()))
p ... | py |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph w... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | import sys
from math import *
from collections import defaultdict
from queue import deque # Queues
from heapq import heappush, heappop # Priority Queues
# parse
lines = [line.strip() for line in sys.stdin.readlines()]
n, m = list(map(int, lines[0].split()))
edges = [set() for i in range(n)]... | 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"
] | # Thank God that I'm not you.
import bisect
from collections import Counter, deque
import heapq
import itertools
import math
import random
import sys
from types import GeneratorType;
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)... | py |
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"
] | t=int(input())
for _ in range(t):
a,b,c,d=map(int,input().split())
if (a+b+c+d)%3==0 and (a+b+c+d)/3>=a and (a+b+c+d)/3>=b and (a+b+c+d)/3>=c:
print('YES')
else:
print('NO') | py |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a s... | [
"brute force",
"strings"
] | t = int(input())
while t>0:
n = int(input())
l = list(map(int, input().split()))
for i in range(n - 2):
if l[i] in l[i + 2:]:
print('YES')
break
else:
print('NO')
t-=1
| py |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format a... | [
"data structures",
"dp"
] | n=int(input())
s=input()
ans=1
d=""
arr=["a"]
for i in range(n):
# print(i,arr,d)
if s[i]<arr[-1]:
d+=str(len(arr)+1)+" "
arr.append(s[i])
else:
for j in range(len(arr)):
if s[i]>=arr[j]:
d+=str(j+1)+" "
arr[j]=s[i]
break
print(len(arr))
print(d) | py |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are prese... | [
"data structures",
"greedy",
"implementation",
"math"
] | n, x = map(int, input().split())
arr, result = [0]*(n), []
mex = 0
for _ in range(n):
arr[int(input())%x] += 1
while arr[mex%x]:
arr[mex%x] -= 1
mex +=1
result.append(mex)
print("\n".join(map(str, result))) | 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
input = sys.stdin.readline
t = int(input())
while(t):
n, m = map(int, input().split())
z = n - m
g = m + 1
k = z // g
print(n * (n + 1) // 2 - k * (k + 1) // 2 * g - (k + 1) * (z % g))
t -= 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"
] | from sys import stdin
input = stdin.readline
def phi(n):
num , i , x = n , 2 , n
while(i * i <= x):
if(n % i == 0):
while(n % i == 0):
n //= i
num = (num // i) * (i - 1)
i += 1
if(n > 1):
num = (num // n) * (n - 1)
... | py |
1295 | C | C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the followi... | [
"dp",
"greedy",
"strings"
] | import sys
from math import sqrt, gcd, factorial, ceil, floor, pi, inf
from collections import deque, Counter, OrderedDict, defaultdict
from heapq import heapify, heappush, heappop
#sys.setrecursionlimit(10**5)
from functools import lru_cache
#@lru_cache(None)
#=================================================... | py |
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"
] | T = 1
for test_no in range(T):
n, q = map(int, input().split())
lava = [[0 for j in range(n)] for i in range(2)]
blockedPair = 0
while q > 0:
q -= 1
x, y = map(lambda s: int(s) - 1, input().split())
delta = +1 if lava[x][y] == 0 else -1
lava[x][y] = 1 - lava[... | 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
# -*- coding: utf-8 -*-
from itertools import accumulate
from collections import defaultdict
class Solution:
"""https://codeforces.com/problemset/problem/1141/F2."""
def sameSumBlocks(self, nums):
# [4 1 2 2 1 5 3]
ps = list(accumulate(nums, initial=0))
n = len(... | 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"
] | for i in range(int(input())):
a=input()
l1=[]
l1.append([int(x) for x in input().split()])
l2=l1[0]
l2.sort()
l2.reverse()
for i in l2:
print(i,end=" ")
print() | 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"
] | test = int(input())
for _ in range(test):
length = int(input())
array = list(map(int, input().split()))
count = 0
if 0 in array:
count += array.count(0)
for i in range(length):
if array[i] == 0:
array[i] = 1
if sum(array) == 0:
count += ... | py |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given... | [
"graphs",
"hashing",
"math",
"number theory"
] | import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from math import gcd
t=int(input())
for tests in range(t):
n,m=map(int,input().split())
C=list(map(int,input().split()))
X=[[] for i in range(n+1)]
for k in range(m):
x,y=map(int,input().split())
X[y].... | 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"
] | 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 |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey... | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | def get_max_rate(rates: list) -> int:
sums = {}
for idx, el in enumerate(rates):
if el in sums:
sums[el] += el + idx
else:
sums[el] = el + idx
return max(sums.values())
def main():
n = int(input())
rates = [int(el) - idx for idx, el in enumerate(input().spl... | py |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is t... | [
"bitmasks",
"greedy"
] | import sys
MAX_DIGIT = 64
def solve():
n, m = map(int, input().split())
alist = map(int, sys.stdin.readline().split())
digit_cnt = [0] * MAX_DIGIT
ticket_cnt = [0] * MAX_DIGIT
two_cnt_map = dict()
for i in range(MAX_DIGIT):
two_cnt_map[1 << i] = i
for a in alist... | py |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ... | [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | import sys, collections, math,bisect
input = sys.stdin.readline
n = int(input())
s = input().rstrip('\n')
stack = []
for i in range(n):
if not stack:
stack.append([s[i],0,i])
else:
if stack[-1][0] <= s[i]:
stack.append([s[i],stack[-1][1],i])
else:
... | py |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey... | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | from collections import Counter
def main():
n = int(input())
bseq = read_ints()
res = Counter()
for i, e in enumerate(bseq):
res[e - i] += e
ans = max(res.values())
print(ans)
def input(): return next(test).strip()
def read_ints(): return [int(c) for c in input().... | 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"
] | t=int(input())
for num in range(0,t):
i=int(input())
o=i//2
p=i%2
if p==0:
print(o*'1')
else:
o=o-1
print('7'+o*'1')
| py |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.E... | [
"math"
] | # cook your dish here
import sys
input = sys.stdin.readline
t=1
#t=int(input())
for _ in range(t):
h,n=map(int,input().split())
d=list(map(int,input().split()))
hh,s,ans=h,0,-1
for i in range(n):
hh+=d[i]
s+=d[i]
if hh<=0:
ans=i+1
break
... | 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"
] | t=int(input())
answer=[]
for i in range(t):
n=int(input())
xp=[]
yp=[]
for j in range(n):
x,y=[int(k) for k in input().split()]
xp.append(x)
yp.append(y)
s=set(xp)
ans=""
posx=0
posy=0
flag=True
for z in s:
l=[]
for y in ra... | py |
1292 | D | D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputÆsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now suffici... | [
"dp",
"graphs",
"greedy",
"math",
"number theory",
"trees"
] | from sys import stdin, stdout
prime = list()
factor = list()
count = list()
dist = list()
N = 0
def find_prime():
global prime
for i in range(2, 5010):
is_prime = True
for j in prime:
if i % j == 0:
is_prime = False
break
if i... | 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"
] | from functools import lru_cache
n=int(input())
a=[*map(int,input().split())]
@lru_cache(None)
def dfs(even,odd,tail):
if even<0 or odd<0:
return n
if even==0 and odd==0:
return 0
idx=even+odd-1
if a[idx]==0:
return min(dfs(even-1,odd,0)+tail,dfs(even,odd-1,1)+1-tail)
... | py |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord... | [
"greedy",
"implementation",
"sortings"
] | for _ in range(int(input())):
n = int(input())
a = sorted(map(int, input().split()))
print(a[n] - a[n - 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"
] | import sys
input=sys.stdin.readline
for _ in range(int(input())):
a,b,c=map(int,input().split())#1w
move=10**6
ans=[0,0,0]
for x in range(1,c+1):
for y in range(x,c+101,x):
cost=abs(a-x)+abs(b-y)
if c%y<y-(c%y):
z=c-c%y
cost+=c%y... | py |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s... | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] |
import string
from sys import stdin
input=stdin.readline
read=lambda :map(lambda s:int(s),input().strip().split())
readi=lambda :int(input())
from collections import defaultdict,Counter
from bisect import bisect_left as bl,bisect_right as br
from random import randint
from math import gcd,ceil
RANDOM = ra... | 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"
] | t = int(input())
for i in range(t):
n,d = map(int,input().split())
if d<=n:
print("YES")
else:
x = (n-1)/2
if d>((n-x)*(x+1)):
print('NO')
else:
print('YES') | 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 os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from sys import stdin, stdout
import io
import math
import heapq
import bisect
import collections
def ceil(a, b):
return (a + b - 1) // b
inf = float('inf')
def get():
return stdin.readline().rstrip()
... | py |
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 collections import deque
def radix_sort(a):
l = len(a)
mx = max(a)
m = 0
while mx > 0:
mx = mx // 10
m += 1
bucket = [deque([]) for _ in range (10)]
for j in range (m):
div = pow(10, j)
for i in ra... | py |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and re... | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | from sys import stdin
import string
input = stdin.readline
n = int(input())
s = [ch for ch in input()[:-1]]
if len(s) == 1:
print(0)
else:
for cycle in range(105):
rem_ct = 0;
for letter in reversed(string.ascii_lowercase):
rem_inds = set()
for i in rang... | py |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossib... | [
"greedy"
] | import sys, 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())
b = list(map(int, input().split()))
visit = [0] * (2 * n + 1)
for i in b:
visit[i] = 1
a = []
for i in range(n):
u = b[i]
... | py |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such... | [
"dp",
"greedy"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
a = list(map(int, input().split()))
dp = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = a[i]
for i in range(2, n + 1):
for l in range(n - i + 1):
r = l + i - 1
dpl = dp[l]
... | py |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.... | [
"data structures",
"implementation"
] | import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
s = input()[:-1]
for i in ['RL', 'LR', 'UD', 'DU']:
a = s.find(i)
if a != -1:
print(a+1, a+2)
break
else:
c, e = 10000000, 0
d = dict()
x = ... | py |
1295 | F | F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from ... | [
"combinatorics",
"dp",
"probabilities"
] | import sys
from itertools import chain
readline = sys.stdin.readline
MOD = 998244353
def compress(L):
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2)}
return L2, C
N = int(readline())
LR = [tuple(map(int, readline().split())) for _ in range(N)]
LR = [(a-1, b) for a, b i... | 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"
] |
###pyrival template for fast IO
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 fil... | py |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memor... | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
ans = "YES"
n,m = map(int,input().split())
mh = ml = m
tx = 0
for _ in range(n):
t,l,h = map(int, input().split())
if tx < t:
mh += t - tx
ml -= t - tx
tx = t
mh = min(mh, h)
ml = max(ml, l)
if mh ... | 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"
] | __author__ = 'Darren'
def solve():
t = int(input())
while t:
run()
t -= 1
def run():
def check_condition_1():
record = {}
common, first, second = None, -1, -1
found = False
for i in range(3):
for j in range(2):
... | 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"
] | # LUOGU_RID: 100466597
n=int(input())
k=0
z=n
for i in range(2,n):
while n!=0:
k+=n%i
n=n//i
n=z
a=max(k,n-2)
b=min(k,n-2)
n=a%b
while n!=0:
a=b
b=n
n=a%b
print(int(k/b),end='/')
print(int((z-2)/b))#s | 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"
] | from __future__ import division, print_function
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
alphabets = list('abcdefghijklmnopqrstu... | 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"
] | start=False
counter=False
o=0
counter1=0
result=[]
for i in range(int(input())):
start=False
counter=False
o=0
counter1=0
x=input()
x=x.rstrip("0")
for j in x:
if j=="0" and not(start):
pass
elif j=="1":
counter=False... | 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 types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
... | py |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph w... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
e = [tuple(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n + 1)]
for u, v in e:
g[u].append(v)
g[v].append(u)
req = 1
while req * req < n:
req += 1
def dfs():
dep = [0] * (n + 1)
par = [0... | py |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "... | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | n , m = map (int , input().split (' '))
store = set()
res = ""
while n>0:
s = input()
if s in store:
res+= s
store.remove(s)
else :
store.add(str (''.join(reversed(s))))
n-=1
midl = ""
for x in store:
if (x == str( ''.join(reversed(x)))):
midl=x
... | 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"
] | x=int(input())
for i in range(x):
a=int(input())
lis=list(map(int,input().split()))
s=set(lis)
lis=list(s)
print(len(lis)) | py |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, whe... | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | def ri(): return int(input())
def rs(): return input()
def rl(): return list(map(int, input().split()))
def rls(): return list(input().split())
def main():
n = ri()
a = rl()
def rec(a, x):
if not len(a) or x < 0:
return 0
on = [i for i in a if i & (1 << x)]
... | 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"
] | t = int(input())
for i in range(t):
n = int(input())
k = n // 2
m = n % 2
ans = ""
if m == 0:
ans += "1" * k
else:
ans += "7"
ans += "1" * (k - 1)
print(ans)
| 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 |
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"
] | t=int(input())
M=[]
def fonction(s):
if 'L' not in s:
return 1
elif 'R' not in s:
return len(s)+1
else:
L=s.split("R")
return len(max(L))+1
for i in range(t):
s=input()
M.append(fonction(s))
for k in M:
print(k)
| py |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+... | [
"dfs and similar",
"sortings"
] | for _ in range(int(input())):
# n=int(input())
n,m=map(int,input().split())
# s=input().strip()
a=list(map(int,input().split()))
# s=list(map(int,input()))
pos = [int(x) for x in input().split()]
for _ in range(m):
for x in pos:
if a[x - 1] > a[x]:
... | py |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko... | [
"implementation",
"strings"
] | n,m = list(map(int,input().split()))
a = input().split()
b = input().split()
for i in range(int(input())):
c = int(input())
print(a[(c-1) % n]+b[(c-1) % m]) | 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 s in [*open(0)][2::2]:
print(len(set(list(map(int, s.split())))))
| 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 _ in range(t):
n, m = map(int, input().split())
score = [int(x) for x in input().split()][:n]
total = 0
for i in range(n): total += score[i]
if m < total: print(m)
else: print(total)
| 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 random, sys, os, math, gc
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce, cmp_to_key
from itertools import accumulate, combinations, permutations, product
from heapq import nsmallest, nlargest, heapify, heappop, heappush
from io import BytesIO, IOBase
from copy ... | py |
1284 | D | D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn l... | [
"binary search",
"data structures",
"hashing",
"sortings"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
W = [(i+1000007)**3 % 998244353 for i in range(N)]
AL, AR, BL, BR = [], [], [], []
for i in range(N):
a, b, c, d = map(int, input().split())
AL.append(a)
AR.append(b)
BL.append(c)
BR.append(d)
def chk(L, R):
D = {s:i for... | 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 sys
input=sys.stdin.readline
n,m,p = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
Pa = [A[i]%p==0 for i in range(n)]
Pb = [B[i]%p==0 for i in range(m)]
for i in range(n):
if not Pa[i]:
x=i
break
for i in range(m):
if not Pb... | py |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, a... | [
"greedy"
] | # ------------------- fast io --------------------
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" no... | 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"
] | t = int(input())
for _ in range(0, t):
n = int(input())
if n%2 == 0:
a = n // 2
n1 = "1" * a
else:
a = n // 2 - 1
n1 = "7" + "1" * a
if n%3 == 0 or n%3 == 2:
a = n // 3
b = n%3 // 2
n2 = "7" * a + "1" * b
elif n%3 == 1:
a ... | 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()))
delta=sorted([ai-bi for ai,bi in zip(a,b)],reverse=True)
# (ai-bi)+(aj-bj)>0
l,r=0,n-1
cnt=0
ct=n-1
while l<r:
if delta[l]+delta[r]>0:
cnt+=ct
ct-=1
l+=1
else:
ct-=1
r-=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"
] | from collections import deque
from sys import stdin
input=stdin.readline
#brute
def bfs(source):
global g,n
dis=[-1]*n
q=deque([source])
dis[source]=0
while q:
t=q.popleft()
for i in g[t]:
if dis[i]==-1:
dis[i]=dis[t]+1
q.ap... | py |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+... | [
"dfs and similar",
"sortings"
] | for t in range(int(input())):
n, m = map(int, input().split())
a = list(map(int, input().split()))
p = list(map(int, input().split()))
while True:
state = False
for i in p:
if a[i - 1] > a[i]:
state = True
a[i - 1], a[i] = a[i], ... | 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"
] | for _ in range(int(input())):
n,x=map(int,input().split())
s=input()
y=s.count('0')-s.count('1')
z=0
inf=False
ans=0
if x==0: ans=1
for i in s:
z+=(i=='0')-(i=='1')
if y==0 and z==x:
inf=True
print(-1)
break
if x-z... | 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"
] | I=input
for _ in[0]*int(I()):
i=0;n=int(I());a=*map(int,I().split()),-2
while a[i]>=i:i+=1
while a[i-1]>=n-i:i+=1
print('YNeos'[i<n::2])
| 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()); l = [ ]
for i in range(n) : l.append(tuple(map(int,input().split())))
l.sort(); x = y = 0; res = 'YES'; s = ''
for i in l :
x1, y1 = i[0], i[1]
if x1 < x or y1 < y : res = 'NO'; break
s += (x1 - x) * 'R' + (y1 - y) * 'U'... | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.