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 |
|---|---|---|---|---|---|
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"
] | n = int(input())
s = input()
s = list(s)
cnt = 0
for i in range(25, -1, -1):
c = chr(97+i)
j = 0
while j < len(s):
if s[j] == c and (j != 0 and ord(s[j-1])+1 == ord(c) or j != len(s)-1 and ord(s[j+1])+1 == ord(c)):
s.pop(j)
cnt += 1
j = -1
j ... | py |
1301 | E | E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be des... | [
"binary search",
"data structures",
"dp",
"implementation"
] | import sys
readline = sys.stdin.readline
def accumulate2d(X):
N = len(X)
M = len(X[0])
for i in range(0, N):
for j in range(1, M):
X[i][j] += X[i][j-1]
for j in range(0, M):
for i in range(1, N):
X[i][j] += X[i-1][j]
return X
... | 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]
print(min(m, total))
| py |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The... | [
"greedy",
"implementation"
] | n=int(input())
l=input()
r=input()
ldic={}
rdic={}
for i in range(n):
if l[i] in ldic:
ldic[l[i]].append(i)
else:
ldic[i]=[i]
for i in range(n):
if r[i] in rdic:
rdic[r[i]].append(i)
else:
rdic[r[i]]=[i]
li=[]
for i in range(n):
li.append([l[i],i])
l... | py |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.I... | [
"math",
"number theory"
] | import sys
import math
from math import *
import builtins
input = sys.stdin.readline
def print(x, end='\n'):
sys.stdout.write(str(x) + end)
# IO helpers
def get_int():
return int(input())
def get_list_ints():
return list(map(int, input().split()))
def get_char_list():
s = input()
return lis... | py |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by... | [
"geometry",
"greedy",
"math"
] | import sys
from math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm, radians, tan, log2
from collections import deque, Counter, OrderedDict, defaultdict
from heapq import heapify, heappush, heappop
#from sortedcontainers import SortedList
#sys.setrecursionlimit(10**5)
from functools import lru_cach... | 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 array
import bisect
import heapq
import json
import math
import collections
import random
import re
import sys
import copy
from functools import reduce
import decimal
from io import BytesIO, IOBase
import os
import itertools
import functools
from types import GeneratorType
import fractions
from... | 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, l):
c = 0
for i in range(1, n):
c = max(c, abs(l[i] - l[i - 1]))
return c
t = int(input())
while(t):
n = int(input())
l = list(map(int, input().split()))
a = []
for i in range(n - 1):
if(l[i] != -1 and l[i + 1] == -1):
a.append(l[i... | 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 heapq
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... | py |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse... | [
"brute force",
"dp",
"greedy",
"implementation"
] | import math
def main():
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
ev = 0
ods = []
for i in range(n):
if (a[i] & 1) == 0:
ev = i + 1
else:
ods.append(i + 1)
if ... | 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"
] |
def main():
n = int(input())
a = readIntArr()
dp = [[-1 for _ in range(n)] for __ in range(n)]
# dp[l][r] = the value that a[l:r] can become
for l in range(n):
dp[l][l] = a[l]
for gap in range(2, n + 1):
for l in range(n):
r = l + gap - 1
... | 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 io
import os
# PSA:
# The key optimization that made this pass was to avoid python big ints by using floats (which have integral precision <= 2^52)
# None of the other optimizations really mattered in comparison.
# Credit for this trick goes to pajenegod: https://codeforces.com/blog/entry/77309?#comment-622486... | py |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re... | [
"brute force",
"combinatorics",
"math",
"number theory"
] | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
w = list(map(int, input().split()))
if n > m:
print(0)
else:
c = 1
for i in range(n):
for j in range(i+1, n):
c = c * (abs(w[i]-w[j])) % m
if c == 0:
print(c)
... | 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 = sys.stdin.readline
show = sys.stdout.write
for _ in range(int(input())):
n = int(input())
f = False
arr = list(map(int, input().split()))
i = 0
while i<n and arr[i] >= i:
i+=1
while i<n:
if arr[i-1]>arr[i]:
i+=1
continue
else:
... | py |
1288 | C | C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (in... | [
"combinatorics",
"dp"
] | import math
n, m = map(int, input().split())
result = math.factorial(n+(2*m)-1)//(math.factorial(2*m)*math.factorial(n-1))
print(int(result) % (1000000007))
| 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"
] | import sys, random
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18
LI = lambda : list(map(int, input().spl... | py |
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)
"""
n, h, l, r = list(map(int, input().split()))
a = list(map(int, input().split()))
f = [[float('-inf')] * h for _ in range(n + 1)]
f[0][0] = 0
for i in... | 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"
] | R=lambda:map(int,input().split())
t,=R()
for _ in[0]*t:
n,d=R();r=i=0
for x in R():m=min(d,i*x);r+=m//i if i else x;d-=m;i+=1
print(r) | py |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of... | [
"implementation",
"strings"
] | # aabb babb babb babb baba
# bbaa bbaa baaa baba baba
# baba aaba abba abaa abab
for _ in range(int(input())):
a1 = input()
a2 = input()
a3 = input()
flag = 0
for i in range(len(a1)):
if a1[i] != a3[i] and a2[i] != a3[i]:
flag = 1
break
if flag == 1:
... | py |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (... | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
# Read input and build the graph
inp = [int(x) for x in sys.stdin.buffer.read().split()]; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
# Relabel to spee... | 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"
] | from sys import stdin
input = stdin.readline
#google = lambda : print("Case #%d: "%(T + 1) , end = '')
inp = lambda : list(map(int,input().split()))
def answer():
for q in range(int(input())):
y = int(input())
y -= 1
ans = a[y % n] + b[y % m]
print(ans)
... | 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, exit
from collections import deque
N = int(input())
arr = list(map(int, stdin.readline().split()))
# sieve, prime list, dictionary of primes
# lp is largest prime
MAX = 1_000_005
pid = {1:0}
pr = []
lp = [0]*MAX
for i in range(2, MAX):
if not lp[i]:
lp[i] = i
pr.append(i)
pid[i] = l... | 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"
] | t=int(input())
for k in range(t):
n=int(input())
a=[*map(int,input().split())]
#print(a)
kt=False; kq=-1; s=[]
for i in range(n):
if a[i]%2==0 :
s.append(i+1)
kt=True
break
if kt :
print(len(s))
print(*s)
else :
for i in range(n):
if a[i]%2!=0 :
s.append(i+1)
if le... | 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"
] | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def solve(s,t):
if len(t) == 1:
if s.count(t[0]):
return 'YES'
return 'NO'
for i in range(1,len(t)):
dp = [[-1000]*(i+1) for _ in range(len(s)+1)]
dp... | 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"
] | 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 |
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"
] | # If you win, you live. You cannot win unless you fight.
from math import sin
from sys import stdin,setrecursionlimit
input=stdin.readline
import heapq
rd=lambda: map(lambda s: int(s), input().strip().split())
ri=lambda: int(input())
rs=lambda :input().strip()
from collections import defaultdict as unsafedict... | py |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The... | [
"greedy",
"implementation"
] | import sys
def II(): return int(sys.stdin.readline())
def LI(): return [int(num) for num in sys.stdin.readline().split()]
def SI(): return sys.stdin.readline().rstrip()
from collections import defaultdict
k = II()
l = defaultdict(list)
r = defaultdict(list)
for ind, char in enumerate(zip(SI(), SI())):... | 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"
] | from sys import stdin
input = stdin.readline
def answer():
maxrank = min(n , x + y - 1)
if((x + y) <= n):
minrank = 1
else:
m = min(x , y)
if(m != n):minrank = (x + y + 1) - n
else:minrank = n
return [minrank , maxrank]
for T in ran... | py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun... | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
def query(u , v):
print('?' , u , v , flush = True)
return int(input())
def dfs(p , prev):
yes = True
for i in child[p]:
if(done[i]):continue
if(i == prev):continue
... | 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"
] | q=int(input())
for i in range(q):
n, m=[int(k) for k in input().split()]
rho=[m, m]
last=0
c=[]
for j in range(n):
c.append([int(k) for k in input().split()])
for j in range(n):
w=c[j]
t=w[0]-last
rho=[rho[0]-t, rho[1]+t]
if rho[0]>w[2] or rho[... | 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()
d = dict()
d[(0, 0)] = 0
x, y = 0, 0
l, r = -1, n
for i, c in enumerate(s):
x += (1 if c == 'R' else 0) - (1 if c == 'L' else 0)
y += (1 if c == 'U' else 0) - (1 if c == 'D' else 0)
if (x, y) in d:
... | 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"
] | import math
def primeFactors(n,arr):
while(n%2==0):
arr.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
arr.append(i)
n = n // i
if n > 2:
arr.append(n)
return arr
from collections import Counter
t=int(input())
while(t):
t-=1
n=int(input())
... | 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"
] | cases = int(input())
for c in range(cases):
jumps = input()
pos_r = []
pos_r.append(0)
for i in range(len(jumps)):
if (jumps[i] == 'R'):
pos_r.append(i+1)
pos_r.append(len(jumps) + 1)
r = 0
for h in range(len(pos_r) - 1):
r = max(r, pos_r[h+1]-pos_r[h])
... | 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 os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if se... | py |
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 bisect
import heapq
import sys
from types import GeneratorType
from functools import cmp_to_key
from collections import defaultdict, Counter, deque
import math
from functools import lru_cache
from heapq import nlargest
import random
inf = float("inf")
# sys.setrecursionlimit(1000000)
class FastIO... | py |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n b... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | import itertools as it
from collections import deque
n = int(input())
bd = [[] for _ in range(n)]
for i in range(n):
lt = list(map(int, input().split()))
for j in range(n):
bd[i].append((lt[j*2]-1, lt[j*2+1]-1))
def rpath(tr, tc, r, c):
q = deque([(r, c)])
while q:
i, j = ... | py |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (... | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
input = sys.stdin.readline
from collections import deque
N=int(input())
E=[[] for i in range(N+1)]
for i in range(N-1):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
Q=deque()
USE=[0]*(N+1)
Q.append(1)
H=[0]*(N+1)
H[1]=1
USE[1]=1
P=[-1]*(N+1)
QI=deque()
w... | 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"
] | import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int,minp().split())
def sub(s1,s2):
d = dict()
for i in s1:
d[i] = d.get(i,0)+1
for i in s2:
d[i] = d.get(i,0)-1
for j in d:
if d[j] > 0:
return j
return 'a'
ans ... | 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"
] | #! /bin/env python3
def cmp(k1, k2):
p1, p2 = k1, k2
d1, d2 = 1 , 1
for i in range(n):
if s[p1] > s[p2]: return 1
if s[p1] < s[p2]: return -1
if p1 == n:
if (n-k1+1)&1 == 1:
p1, d1 = k1, -1
else: p1 = 0
if p2 == n:
... | 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())
even=odd=0
l=list(map(int,input().split()))
for i in l:
if i%2==0:
even+=1
else:
odd+=1
if sum(l)%2!=0:
print("YES")
else:
if even!=0 and odd!=0:
print("YES")
... | 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"
] | from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def update(l, r, s):
q, ll, rr, i = [1], [0], [l1 - 1], 0
while len(q) ^ i:
j = q[i]
l0, r0 = ll[i], rr[i]
if l <= l0 and r0 <= r:
lazy[j] += s
... | 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"
] | #https://codeforces.com/contest/1325/problem/C
import sys
from collections import *
sys.setrecursionlimit(10**5)
itr = (line for line in sys.stdin.read().strip().split('\n'))
INP = lambda: next(itr)
def ni(): return int(INP())
def nl(): return [int(_) for _ in INP().split()]
def solve(n, g, edge):
... | py |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q... | [
"combinatorics",
"greedy",
"math"
] | import sys
# sys.stdin=open("input.txt","r")
# sys.stdout=open("output.txt","w")
n=int(input())
ans,num=0,n
for i in range(1,n+1):
ans+=(1/num)
num-=1
print(ans) | py |
1307 | C | C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letter... | [
"brute force",
"dp",
"math",
"strings"
] | import sys
import math
from collections import *
from functools import cmp_to_key
mod=998244353
def get_ints():
return map(int, sys.stdin.readline().strip().split())
#test=int(input())
#while test:
#test-=1
s=str(input())
n=len(s)
b=set()
a={}
res=-float("inf")
for j in range(1,n):
for i in range(2... | 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 i in range(t):
arr=list(map(int,input().split()))
total=sum(arr)
maximum=max(arr[0:3])
if(total%3==0 and total/3 >= maximum):
print("YES")
else:
print("NO")
| 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 |
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())
teachs = list(map(int,input().split()))
studs = list(map(int,input().split()))
diffs = [teachs[i]-studs[i] for i in range(n)]
res = 0
diffs.sort()
# print(diffs)
l , r = 0 , n - 1
while l < r:
if diffs[l] > -diffs[r]:
res += r - l
r -= 1
else:... | py |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of... | [
"implementation",
"strings"
] | # from collections import Counter
ints = lambda: list(map(int, input().split()))
tw = lambda n: (n&(n-1)==0) and n!=0
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
def solve():
# by Azimjonm2333
a=input()
b=input()
c=input()
for i in range(l... | 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"
] | size: int = int(input())
diff: list[int] = []
a = list(map(int,input().split()))
b = list(map(int,input().split()))
for i in range(size):
diff.append(a[i]-b[i])
diff.sort()
l: int = 0
r: int = diff.__len__()-1
ans:int = 0
while l < r :
if diff[r] + diff[l] > 0 :
ans += r - l
... | 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"
] | t = int(input())
for i in range(t):
s = input()
if len(s) <= 2:
print(0)
else:
first_index = 0
for i in range(len(s)):
if s[i] == '1':
first_index = i
break
last_index = 0
for i in range(len(s) - 1, -1, -1):
... | py |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord... | [
"greedy",
"implementation",
"sortings"
] | t = int(input())
for i in range(t):
n = int(input())
m = 2 * n
arr = list(map(int, input().split()))[:m]
arr.sort()
print(abs(arr[n-1] - arr[n])) | py |
1301 | E | E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be des... | [
"binary search",
"data structures",
"dp",
"implementation"
] | def main():
import sys
input = sys.stdin.buffer.readline
# max
def STfunc(a, b):
if a > b:
return a
else:
return b
# クエリは0-indexedで[(r1, c1), (r2, c2))
class SparseTable():
def __init__(self, grid):
# A: 処理したい2D配列
... | 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"
] | # LUOGU_RID: 100980329
for i in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
a.sort()
print(a[n]-a[n-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"
] | # 6 5
# 5 0 3 1 2
# 1 8 9 1 3
# 1 2 3 4 5
# 9 1 0 3 7
# 2 3 0 6 3
# 6 4 1 7 0
import sys
input = lambda: sys.stdin.buffer.readline().decode().strip()
max_a = 10**9
min_a = 0
def solve():
n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
# binary sea... | py |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shape... | [
"brute force",
"data structures",
"implementation"
] | n=int(input().split()[0])
s={input()for _ in[0]*n}
a=[['SET'.find(x)for x in y]for y in s]
print(sum(''.join('SET '[(3-x-y,x)[x==y]]for x,y in
zip(a[i],a[j]))in s for i in range(n)for j in range(i))//3)
| 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 gc
import heapq
import itertools
import math
from collections import Counter, deque, defaultdict
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import threading
from heapq import *
from fractions import Fraction
import bisect
def S... | py |
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"
] | import sys, threading
import math
from os import path
from collections import deque, defaultdict, Counter
from bisect import *
from string import ascii_lowercase
from functools import cmp_to_key
from random import randint
from heapq import *
from array import array
from types import GeneratorType
def readInts():
... | 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"
] | import sys
from sys import stdin
from collections import deque
def NC_Dij(lis,start):
ret = [float("inf")] * len(lis)
ret[start] = 0
q = deque([start])
plis = [i for i in range(len(lis))]
while len(q) > 0:
now = q.popleft()
for nex in lis[now]:
... | py |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal... | [
"greedy",
"sortings"
] | # 13:01-
import sys
input = lambda: sys.stdin.readline().rstrip()
N,a,b,K = map(int, input().split())
A = list(map(int, input().split()))
total = a+b
ans = 0
B = []
for i in range(N):
t = A[i]%total
if t==0:
t = total
if t>a:
B.append((t-a-1)//a+1)
else:
ans += 1
B.sort(reverse=True)
wh... | py |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. ... | [
"math",
"number theory",
"probabilities"
] | import sys
input = sys.stdin.readline
from math import sqrt
import random
n=int(input())
A=list(map(int,input().split()))
random.shuffle(A)
MOD={2,3,5}
USED=set()
for t in A[:31]:
if t in USED:
continue
else:
USED.add(t)
for x in [t-1,t,t+1]:
if x<=5:
... | 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"
] | import os, sys, io
# switch to fastio
fast_mode = 0
# local file test -> 1, remote test --> 0
local_mode = 0
if local_mode:
fin = open("./data/input.txt", "r")
fout = open("./data/output.txt", "w")
sys.stdin = fin
sys.stdout = fout
if fast_mode:
input = io.BytesIO(os.read(sys.stdin.... | 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 |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then... | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | import sys
# Testing out some really weird behaviours in pypy
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(p... | py |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l... | [
"data structures",
"geometry",
"greedy"
] | import sys
input = sys.stdin.buffer.readline
N = int(input())
a = list(map(int, input().split()))
s = [(0, N)]
for x in a:
c = 1
while s[-1][0] * c >= x * s[-1][1]:
y, d = s.pop()
x += y
c += d
s.append((x, c))
s.reverse()
s.pop()
i = 0
while len(s):
x, c = s.pop()
for j in ra... | py |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points mo... | [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify, nlargest
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sy... | 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 = [int(i) for i in input().split(" ")]
a = input().split(" ")
b = input().split(" ")
t = int(input())
for i in range(t):
year = int(input())
print(a[year%(n[0]) - 1]+b[year%(n[1]) - 1])
| py |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; f... | [
"combinatorics",
"math"
] |
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
n,m=map(int, input().split())
md=998244353
if n==2:
print(0)
else:
ans=ncr(m,n-1,md)
ans=(ans*(n-2))%md
ans=(ans*pow(2,n-3,md))%... | 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"
] | n = int(input())
x = input()
def remove(tmp, x):
removed = 0
if len(tmp) >= 2 and tmp[0] == x and tmp[1] == x - 1:
removed += 1
tmp.pop(0)
i = 0
n = len(tmp)
while i < n:
if i == 0:
if len(tmp) >= 2 and tmp[0] == x and tmp[1] == x - 1:
remov... | py |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey... | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | n = int(input())
b = list(map(int, input().split()))
smth = dict()
for i in range(n):
if not (b[i] - i) in smth:
smth[b[i] - i] = 0
smth[b[i] - i] += b[i]
ans = 0
for el in smth:
ans = max(ans, smth[el])
print(ans) | py |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b)... | [
"math"
] | for t in range(int(input())):
a, b = map(int, input().split())
print(a * (len(str(b + 1)) - 1)) | py |
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 = input()
s = input()
a = 0
for i in s:
a += int(i)
m = int(s)
flag = True
while True:
if a % 2 == 0 and int(s) % 2 != 0:
print(s)
flag = False
break
a -= int(s[-1])
s = s[0:-1]
... | py |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller ... | [
"math"
] | t=int(input())
for i in range(t):
x,y,a,b=map(int,input().split())
k=(y-x)%(a+b)
if k:
print(-1)
else:
print((y-x)//(a+b)) | py |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n b... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | def main():
n = int(input())
board = []
told = []
blocked = []
for r in range(1, n + 1):
endings = list(map(int, input().split()))
board.append([])
told.append([])
for i in range(0, 2 * n, 2):
x, y = endings[i:i + 2]
told[-1].append(... | 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 io
import os
from array import array
# Rewrote in C++
DEBUG = False
if DEBUG:
from functools import lru_cache
def solveTopDown(N, P, K, audienceScore, playerScore):
# Choose P players and K audience members from N people
assert len(audienceScore) == len(playerScore) == N
# S... | 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"
] | class BIT:
def __init__(self, n):
self.n = n
self.bit = [0]*(self.n+1) # 1-indexed
def init(self, init_val):
for i, v in enumerate(init_val):
self.add(i, v)
def add(self, i, x):
# i: 0-indexed
i += 1 # to 1-indexed
while i <= self.n:
... | 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"
] | """ A : Determine if three line segments form A """
def cross(vecA, vecB):
return vecA[0] * vecB[1] - vecA[1] * vecB[0]
def dot(vecA, vecB):
return vecA[0] * vecB[0] + vecA[1] * vecB[1]
def angle(lineA, lineB):
x1, y1 = (lineA[0][0] - lineA[1][0], lineA[0][1] - lineA[1][1])
x2, y2 = (... | py |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, yo... | [
"greedy",
"math",
"number theory"
] | from sys import stdin,stdout
input = stdin.readline
from math import gcd,ceil,sqrt,inf,factorial
# from collections import Counter
# from heapq import heapify,heappop,heappush
# from time import time
# from bisect import bisect, bisect_left
for _ in range(int(input())):
n = int(input())
p = int(n)
... | py |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal... | [
"greedy",
"sortings"
] | n, a, b, k = map(int, input().split())
l = []
p = 0
for h in map(int, input().split()):
r = (h - a)%(a+b)
if r <= b:
l.append(r//a + (r % a != 0))
else:
p += 1
l.sort()
s = 0
for i in l:
s += i
if s > k:
break
p += 1
print(p)
| py |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e.... | [
"binary search",
"greedy",
"implementation"
] | from collections import deque
N,M,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
def count(w):
l = deque(B[:w])
num = l.count(0)
ans = 0
for i in range(w,M):
if num==0:ans += 1
if l.popleft()==0:num-=1
if B[i]==0:num+=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 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
self.write ... | 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"
] | import sys
input = sys.stdin.readline
from bisect import bisect_left
n = int(input())
g = [[] for _ in range(n)]
c = [0] * n
for i in range(n):
p, c[i] = map(int, input().split())
if p != 0:
g[p - 1].append(i)
else:
root = i
s = [root]
v = [0] * n
d = [[] for _ in range(n)]
... | 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"
] | # でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
def main(n, d):
P = [0] + list(range(n - 1))
C = [set() for _ in range(n)]
for v in range(n - 1):
C[v].add(v + 1)
D = list(range(n))
Vd = [set() for _ in range(n)]
for v in range(n):
Vd[v].add(v)
L = [n - 1]
B = [0... | 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"
] | import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lam... | 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 sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, data, default=float('inf'), func=min):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._le... | 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"
] | g = dict()
n = int(input())
a = list(map(int,input().split()))
for i in range(n):
total = 0
for j in range(i,n):
total += a[j]
if total in g:
g[total].append((i + 1,j + 1))
else:
g[total] = [(i+1,j+1)]
ans = 0
res = []
for k in g:
t = -1
tem... | py |
1307 | E | E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer... | [
"binary search",
"combinatorics",
"dp",
"greedy",
"implementation",
"math"
] | import bisect
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m = map(int, input().split())
s = list(map(int, input().split()))
mod = pow(10, 9) + 7
x = [[] for _ in range(n + 1)]
for i in range(n):
x[s[i]].append(i + 1)
y = [[] for _ in range(n + 1)]
for _ in range(m)... | py |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is ... | [
"implementation",
"sortings"
] | for _ in range(int(input())):
n = int(input())
cords = []
for i in range(n):
a, b = map(int, input().split())
cords.append([a, b])
cords = sorted(cords, key = lambda t: t[0])
cords = sorted(cords, key = lambda t: t[1])
prevx = 0
prevy = 0
ans = ''
flag = F... | py |
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"
] | import sys
input = sys.stdin.readline
output = sys.stdout.write
def main():
tests = int(input().rstrip())
for i in range(tests):
length_ = int(input().rstrip())
list_ = list(map(int, input().rstrip().split()))
if length_ % 2 == 0:
i = 0
for num in li... | 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 sys
input = sys.stdin.readline
A = int(input())
res = 0
def calc(x, base):
v = 0
while x > 0:
v += x % base
x //= base
return v
def gcd(a, b):
return a if b == 0 else gcd(b, a%b)
for i in range(2, A):
res += calc(A, i)
d = gcd(res, A-2)
print(f'{... | 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"
] |
def naive(n, a):
xor = 0
for i in range(n):
for j in range(i + 1, n):
xor ^= (a[i] + a[j])
return xor
def main():
n = int(input())
a = readIntArr()
m = 25
# m = 4
xorparity = [0] * m
for twopow in range(m):
base = 2 ** tw... | 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"
] | t=int(input(""))
def test(l):
a,b=int(l[0]),int(l[1])
if a%b==0:
return "YES"
else:
return "NO"
l=[]
for i in range(t):
s=input("").split(" ")
c=test(s)
l.append(c)
for j in range(len(l)):
print(l[j])
| py |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)L... | [
"brute force",
"math",
"number theory"
] | from math import gcd
n = int(input())
x, y = 1e19, 1e19
i = 1
while i*i <= n:
if n % i == 0 and gcd(i, n//i) == 1:
if n//i < max(x, y):
x, y = i, n//i
i += 1
print(x, y) | 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],m... | py |
1296 | B | B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer numb... | [
"math"
] | def f():
t=int(input())
for i in range(t):
n=int(input())
ans=0
while True:
d=(n//10)*10
ans=ans+d
n=(n-d)+(d//10)
if n<10:
ans=ans+n
break
print(ans)
f()
| 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=list(map(int,input().split()))
l.sort(reverse=True)
l=list(map(str,l))
print(" ".join(l))
| 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"
] | import sys,math,heapq,queue
fast_input=sys.stdin.readline
h,n=map(int,fast_input().split())
d=list(map(int,fast_input().split()))
for i in range(1,n):
d[i]+=d[i-1]
m=min(d)
if h+m<=0:
for i in range(n):
if d[i]+h<=0:
print(i+1)
break
elif h+d[-1]>=h:
... | 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"
] | from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
def answer():
left , s = [-1 for i in range(n)] , []
for i in range(n - 1 , -1 , -1):
while(len(s) and a[s[-1]] >= a[i]):
left[s.pop()] = i
s.append(i)
right , s = [n... | py |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1... | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | u,v=map(int,input().split())
if u>v or (u%2!=v%2):
print(-1)
elif u==0 and v==0:
print(0)
elif u==v:
print(1)
print(u)
else:
x=(v-u)//2
if u&x==0:
print(2)
print(u+x,x)
else:
print(3)
print(u,x,x) | py |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arrange... | [
"dfs and similar",
"greedy",
"implementation"
] | import sys,heapq
from collections import defaultdict,deque
import math
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s)-1]))
def in... | py |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format a... | [
"data structures",
"dp"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
n=int(input())
s=[ord(i)-97 for i in input()]
c=[-1]*27
ans=[]
for i in s:
mx=max(c[i+1:])
c[i]=mx+1
ans.append(mx+2)
print(max(ans))
print(*ans) | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.