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 |
|---|---|---|---|---|---|
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"
] | def solve(arr,n):
k=0
flag=True
for i in range(n):
if(arr[i]<i):
break
k=i
for i in range(n-k):
if(arr[n-1-i]<i):
flag= False
break
return flag
t=int(input())
while(t>0):
... | 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=lambda :stdin.readline()[:-1]
def fact(n):
res=n
a=[]
i=2
while i*i<=res:
if res%i==0:
cnt=0
while res%i==0:
cnt+=1
res//=i
a.append((i,cnt))
i+=1
if res!=1:
a.append((res,1))
return a
import math
def solve():
... | py |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the ... | [
"math"
] | for _ in range(int(input())):
a, b, c, n = map(int, input().split(' '))
coins = [a, b, c]
coins.sort()
coins_left = n - (coins[2] - coins[0]) - (coins[2] - coins[1])
if coins_left >= 0 and coins_left % 3 == 0:
print("YES")
else:
print("NO") | py |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, ... | [
"math",
"strings"
] | from collections import Counter, deque, defaultdict
import math
from itertools import permutations, accumulate
from sys import *
from heapq import *
from bisect import bisect_left, bisect_right
from functools import cmp_to_key
from random import randint
xor = randint(10 ** 7, 10**8)
# https://docs.python.org/3... | py |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip... | [
"math"
] | import math
whatever = int(input())
for i in range(whatever):
test_case = input().split()
n = int(test_case[0])
g = int(test_case[1])
b = int(test_case[2])
if g > n:
print(n)
continue
total_days = 0
# goo_days = 0
ngood = math.ceil(n/2)
check = False
if ngood %... | 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"
] | import math
import sys
import bisect
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
Mod = 1000000007
# t = int(input())
t=1
while t>0:
t-=1
#n = q(m+1) + r
n = int(input())
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
a1 = [0]*n
a2 = [0]*n
... | py |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can... | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #OMM NAMH SHIVAY
#JAI SHREE RAM
import sys,math,heapq,queue
from collections import deque
from functools import cmp_to_key
fast_input=sys.stdin.readline
MOD=10**9+7
x0,y0,ax,ay,bx,by=map(int,fast_input().split())
xs,ys,t=map(int,fast_input().split())
temp=[[x0,y0]]
while True:
curx=ax*temp[-1][0]+bx
... | 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"
] | import sys; import math;
CASE=0; rla=''
def solve() :
n=int(rla)
if n&1 :
for i in range(n) : a, b=map(int, input().split())
print("NO"); return
else :
x=[]; y=[]
for i in range(n>>1) :
a, b=map(int, input().split())
x.append(a); y.append(b)
... | 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"
] | import sys
input = sys.stdin.readline
n = int(input())
w = list(map(int, input().split()))
x = n-1
l, r, d = 0, 0, 0
c = 0
q = [0]*n
for i, j in enumerate(w):
if c <= 0:
l1 = i
c = j
else:
c += j
if c > d:
d = c
l = l1
r = i + 1
if ... | 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
from math import sqrt
n,m=map(int,input().split())
k=int(-(-sqrt(n)//1))
E=[[] for i in range(n+1)]
D=[0]*(n+1)
for i in range(m):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
D[x]+=1
D[y]+=1
Q=[(d,i+1) for i,d in enumerate(D[1:]... | py |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are righ... | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | """
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
n... | 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"
] | t = int(input())
for i in range(t):
n = int(input())
res = 0
a = list(map(int, input().split()))
mina = float('inf')
maxa = 0
res = 0
for i in range(n):
if a[i] == -1:
if i > 0 and a[i-1] != -1:
mina = min(mina, a[i-1])
ma... | 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"
] | from itertools import permutations
import os
import sys
from io import BytesIO, IOBase
from fractions import Fraction
def main():
t=int(input())
for _ in range(t):
l=int(input())
h=input()
i=0
s=''
while i<len(h):
if int(h[i])%2==1:
... | 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"
] | from math import gcd
max_val = 10**5+1
def solve(arr):
#Lista de Listas que contendrá los divisores de cada uno de los números en el intervalo [1,max_val]
div = [[] for _ in range(max_val)]
#Lista que contendrá el precalculo de la función de Mobius en el intervalo [1,max_val]
mu = [1 for _ i... | py |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is ... | [
"implementation",
"sortings"
] | for t in range(int(input())):
n = int(input())
cord_list = []
for i in range(n):
x, y = map(int, input().split())
cord_list.append((x, y))
cord_list.sort()
r = 0
u = 0
fir = 0
sec = 0
ans = []
while cord_list:
r = abs(cord_list[0][0] - f... | 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())
t = []
ans = ans1 = ""
for i in range(n):
s= input()
r = s[::-1]
if r in t:
ans += r
elif s==r:
ans1 = s
t.append(s)
anss = ans+ans1+ans[::-1]
print(len(anss),anss,end="")
| 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())
ll = list(map(int,input().split()))
ll = sorted(ll,reverse=True)
l1 = []
l2 = []
if n%2 == 0:
l1len = n+1
l2len = n-1
else:
l1len = n
l2len = n
for i in range(len(ll)):
if i % 2 == 0 and len(l... | 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 math
def f():
l1 = input().split(' ')
l2 = input().split(' ')
n = int(l1[0])
x = int(l1[1])
am = 0
for i in range(n):
if int(l2[i]) == x:
print(1)
return 0
am = max(am, int(l2[i]))
if am > x:
print(2)
return 0
else:
... | 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())
for i in range(t):
s = input()
s = list(s.split('R'))
maxim = 0
for i in s:
if len(i) > maxim:
maxim = len(i)
print(maxim + 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"
] | '''
Hala Madrid!
https://www.zhihu.com/people/li-dong-hao-78-74
'''
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.... | py |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-... | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify
from math import inf, sqrt, ceil, log2
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
from typing import List
from bisect import bisect_left, bisect_right
import... | py |
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, m = map(int, input().split())
arr = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
while True:
flag = False
for i in range(m):
if arr[nums[i] - 1] > arr[nums[i]]:
arr[nums[i] - 1], arr[nums[i... | py |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifical... | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | s = list(input())
ans = []
while True:
temp = []
l = 0
r = len(s) - 1
while l < r:
while l < r and s[l] != "(":
l += 1
while l < r and s[r] != ")":
r -= 1
if l < r and s[l] == "(" and s[r] == ")":
s[l] = "0"
s[r] = "0"
... | 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"
] |
n,m,p = tuple(map(int,input().split()))
a = list(map(int,input().split()))
b = list(map(int,input().split()))
i =0
while i<n:
if a[i]%p != 0:
break
i+=1
j =0
while j<m:
if b[j]%p != 0:
break
j+=1
print(i+j)
| py |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfe... | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | import sys
from array import array
from collections import deque
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1... | py |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t... | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
input = sys.stdin.buffer.readline
def process_root(g, r):
start = [r]
seen = {r: 0}
parent = {r: None}
while len(start) > 0:
next_s = []
for x in start:
for y in g[x]:
if y not in seen:
seen[y] = seen[x]+1
... | py |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this... | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | import collections
import math
def prime_range(n):
sieve = [0] * n
pid = {1: 0}
for i in range(2, n):
if not sieve[i]:
sieve[i] = i
pid[i] = len(pid)
for j in range(i * i, n, i):
if not sieve[j]:
sieve[j] = i
return sieve,... | py |
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"
] | n = int(input())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
total1 = sum(arr1)
total2 = sum(arr2)
count = 0
ones = 0
for i in range(len(arr1)):
if arr1[i] == 1 and arr2[i] == 0:
count += 1
elif arr1[i] == 1 and arr2[i] == 1:
ones += 1
needed =... | 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"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
class LowestCommonAncestor:
""" <O(n), O(log(n))> """
def __init__(self, G: "隣接リスト", root: "根", parents):
from collections import deque
self.n = len(G)
self.tour = [0] * (2 * self.n - 1)
self.depth_list = [0] *... | py |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are righ... | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | n, k = map(int, input().split(' '))
deg = [0] * n
neighbors = [[] for i in range(n)]
edges = []
for i in range(n - 1):
a, b = map(int, input().split(' '))
neighbors[a - 1].append(b - 1)
neighbors[b - 1].append(a - 1)
deg[a - 1] += 1
deg[b - 1] += 1
edges.append((a - 1, b - 1))
deg = list(sorted... | 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"
] | import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
def isParallel(p1a,p1b,p2a,p2b):
dx1=p1a[0]-p1b[0]
dy1=p1a[1]-p1b[1]
dx2=p2a[0]-p2b[0]
dy2=p2a[1]-p2b[1]
return dx1==dx2 and dy1==dy2
n=int(input())
xy=[] #[[x,y]]
for _ in ran... | 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"
] | t=int(input())
while(t>0):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a.sort()
b.sort()
for i in range(n):
print(a[i],end=" ")
print()
for i in range(n):
print(b[i],end=" ")
print()
t=t-1 | py |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of ... | [
"implementation",
"math"
] | import math
a = int(input())
n = 0
for i in range(2,a):
x=a
while x:
n+=x%i
x//=i
b=math.gcd(n,a-2)
print(str(n//b)+'/'+str((a-2)//b)) | py |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a ... | [
"combinatorics",
"math"
] | n, m = map(int, input().split())
f = [1]
for i in range(1, 250001):
f.append(f[-1] * i % m)
ans = 0
for i in range(1, n + 1):
ans += ((((f[i] * f[n-i]) % m)) * (n - i + 1) * (n - i + 1)) % m
#print(ans)
print(ans % m)
| 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 sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, p, k = map(int, input().split())
a = list(map(float, input().split()))
s = [tuple(map(float, input().split())) for _ in range(n)]
b = [(a[i], i) for i in range(n)]
b.sort(reverse = True)
pow2 = [1]
for _ in range(p):
pow2.... | py |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of... | [
"dfs and similar",
"dsu",
"graphs"
] | import sys
readline = sys.stdin.readline
class UF():
def __init__(self, num):
self.par = [-1]*num
self.weight = [0]*num
def find(self, x):
if self.par[x] < 0:
return x
else:
stack = []
while self.par[x] >= 0:
stack.a... | 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 math
# def sieve(n):
# arr = [True]*(n+1)
# arr[0] = False
# arr[1] = False
# for p in range(2,math.ceil(pow(n,0.5))):
# if arr[p] == False:
# continue
# for j in range(p*p,n+1,p):
# arr[j] = False
# res = []
# for p in range(2,n+1):
# if ar... | py |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff... | [
"brute force",
"data structures",
"sortings"
] | import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
W=[tuple(map(int,input().split())) for i in range(n)]
A=[tuple(map(int,input().split())) for i in range(m)]
M=[tuple(map(int,input().split())) for i in range(p)]
Q=[[] for i in range(10**6+1)]
for x,y,c in M:
Q[x].append((c,y))
for ... | py |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q... | [
"combinatorics",
"greedy",
"math"
] | n = int(input())
ans = 0
x = n
for i in range(n):
ans += 1 / x
x -= 1
print(ans) | 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 _ in range(t):
n = int(input())
a = list(map(int, input().split()))
if sum(a) % 2 == 1:
print("YES")
elif any((a[i] - a[j]) % 2 == 1 for i in range(n) for j in range(i+1, n)):
print("YES")
else:
print("NO")
| py |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s... | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
n = int(input())
s = input()
min_r = s
k = 1
for i in range(1, n):
if i % 2 == n % 2:
temp = s[i:] + s[:i]
else:
temp = s[i:] + s[:i][::-1]
if temp... | 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())
op=[]
for i in range(t):
m,n=map(int,input().split(' '))
if m%n==0:
op.append('YES')
else:
op.append('NO')
for i in op:
print(i) | py |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t... | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import 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 |
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())
for i in range(t):
k = int(input())
a = input()
angry = False
patient = 0
ans = 0
for j in range(len(a)):
if a[j] == 'A':
angry = True
ans = max(ans, patient)
patient = 0
elif a[j] == 'P' and angry:
patient += 1
... | py |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii i... | [
"dp",
"greedy",
"implementation"
] | t = int(input())
for Cases in range(t):
n = int(input()); a = list(map(int,input().split()))
dp = [0]*(n); dp[0] = a[0]; rem = [0]*n
for i in range(1,n):
dp[i] = max(dp[i-1]+a[i],a[i])
if dp[i] == a[i]: rem[i] = i
elif dp[i] == dp[i-1]+a[i]: rem[i] = rem[i-1]
... | 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"
] | from itertools import groupby
for _ in range(int(input())):
input()
ans = 0
for i, (k, v) in enumerate(groupby(input())):
if i != 0 and k == "P":
ans = max(ans, sum(1 for _ in v))
print(ans)
| py |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.Th... | [
"graphs",
"interactive"
] | from sys import stdout
class Mock:
def __init__(self, cap, a):
self.a, self.cap = a, cap
self.n, self.q = len(a), []
def ask(self, i):
result = self.a[i] in self.q
self.q.append(self.a[i])
if len(self.q) > self.cap:
self.q = self.q[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"
] |
def main():
n=int(input())
adj=[set() for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].add(v)
adj[v].add(u)
leaves=set()
for i in range(1,n+1):
if len(adj[i])==1:
leaves.add(i)
#Iteratively remove leaves.... | 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 collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.... | py |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a... | [
"implementation",
"math"
] | I=input
exec(int(I())*"I();a=[*map(int,I().split())];s=a.count(0);print(s+(s+sum(a)==0));") | py |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal... | [
"greedy",
"sortings"
] | import sys
input = sys.stdin.readline
n, a, b, k = map(int, input().split())
w = list(map(int, input().split()))
d = []
x = a + b
for i in w:
if i % x == 0:
i = x
else:
i %= x
d.append(i)
d.sort()
c = 0
x = 0
for i in d:
x = i//a - (i%a==0)
if k >= x:
k ... | py |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positiv... | [
"greedy",
"implementation",
"math"
] | for _ in range(int(input())):
a,b=map(int,input().split())
if a==b:
print(0)
elif ((b-a)%2==1 and a<b) or ((b-a)%2==0 and a>b):
print(1)
else:
print(2)
| py |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i... | [
"dp",
"strings"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
def solve():
s=input()
t=input()
ns=len(s)
nt=len(t)
inf=10**9
for i in range(nt):
t1=t[:i]
t2=t[i:]
n1=len(t1)
n2=len(t2)
dp=[-1]*(n1+1)
dp[0]=0
for j in range(ns):
ndp=[-1]*(n1+1)
for k in ... | py |
1290 | D | D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.Th... | [
"constructive algorithms",
"graphs",
"interactive"
] | from sys import stdout
class Mock:
def __init__(self, cap, a):
self.a, self.cap = a, cap
self.n, self.q = len(a), []
def ask(self, i):
result = self.a[i] in self.q
self.q.append(self.a[i])
if len(self.q) > self.cap:
self.q = self.q[1:]
... | 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"
] | import os
import time
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 |
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"
] | for _ in range(int(input())):
input()
a = list(map(int, input().split()))
s = sum(x or 1 for x in a)
print(a.count(0) + (s == 0))
| 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 highlight import *
n = int(input())
p = list(map(int, input().split()))
remaining = set(range(1, n+1))
a = []
# 0 = even, 1 = odd, -1 = missing
for i in p:
if i == 0:
a.append(-1)
else:
remaining.remove(i)
if i % 2 == 0:
a.append(0)
else:
... | py |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algori... | [
"data structures",
"greedy",
"sortings"
] | import sys
from collections import defaultdict
from heapq import heapify, heappush, heappop
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
t = list(map(int, sys.stdin.readline().split()))
# create a map that stores list of time for each value of a
umap = defaultdict(list)
for i in rang... | py |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common q... | [
"combinatorics",
"greedy",
"math"
] | n = int(input())
dollars = 0
for i in range(n):
dollars += (1 / n)
n -= 1
print(dollars) | py |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re... | [
"brute force",
"combinatorics",
"math",
"number theory"
] | n,m=map(int, input().split())
l=list(map(int, input().split()))
if n>m:
print(0)
else:
ans=1
for i in range(n):
for j in range(i+1,n):
ans=(ans*abs(l[i]-l[j]))%m
print(ans) | 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"
] | import sys
import math
from collections import Counter
#from decimal import *
import random
alfabet = {'a': 1, 'b': 2,'c': 3,'d': 4,'e': 5,'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,'p': 16,'q': 17,'r': 18,'s': 19,'t': 20,'u': 21,'v': 22,'w': 23,'x': 24,'y': 25,'z': 26}
a... | 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"
] | tests = int(input())
i = 0
while i < tests:
checker = False
len_of_number = int(input())
number = [int(x) for x in list(input())]
if len_of_number == 1:
print(-1)
elif sum(number) == 1:
print(-1)
else:
if sum(number)%2 == 0 and number[-1]%2 != 0:
number = [str(x) for x in number]
print(' ... | py |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii i... | [
"dp",
"greedy",
"implementation"
] | t = int(input())
def max_subarray(arr):
acc = 0
min_acc = 0
max_acc = float("-inf")
for num in arr:
acc += num
max_acc = max(max_acc, acc - min_acc)
min_acc = min(min_acc, acc)
return max_acc
for i in range(t):
n = int(input())
arr = list(map(int, input().split(" ... | py |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are cor... | [
"greedy"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
s = list(input().rstrip())
c = 0
for i in s:
c += 1 if i & 1 else -1
if c:
ans = -1
print(ans)
exit()
ans = 0
c = 0
now = 0
f = 0
for i in s:
c += 1
now += 1 if not i & 1 else -1
... | py |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j... | [
"binary search",
"bitmasks",
"dp"
] | import sys, math
import heapq
from collections import deque
input = sys.stdin.readline
hqp = heapq.heappop
hqs = heapq.heappush
# input
def ip(): return int(input())
def sp(): return str(input().rstrip())
def mip(): return map(int, input().split())
def msp(): return map(str, input().split().rstrip... | py |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff... | [
"brute force",
"data structures",
"sortings"
] | import sys
from array import array
from bisect import *
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda dtype: [dtype(x) for x in input().split()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
tests, inf = 1, 10 ** 18
out = []
max_ = 10 ** 6 + 1
cla... | 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"
] | 'https://codeforces.com/contest/1293/problem/A'
for _ in range(int(input())):
n,s,k=map(int,input().split())
num=list(map(int,input().split()))
for i in range(n):
left=s-i
right=s+i
if(left>=1 and left not in num):
print(i)
break
if(right<=n and right not in num):
print(i)
break
els... | 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"
] | #! /bin/env python3
# please follow ATshayu
def main():
n, a, b, k = map(int, input().split(' '))
h = map(int, input().split(' '))
# solve
def ceil(a, b): return a//b if a%b == 0 else a//b+1
res = []
ans = 0
for ele in h:
x, r = ele//(a+b), ele%(a+b)
if r == 0:... | 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"
] | liste = input().split()
size_problem=int(liste[0])
modulo=int(liste[1])
liste=input().split()
if size_problem>modulo:
print(0)
else:
liste = [eval(i) for i in liste]
liste.sort(reverse=True)
prod =1
for i in range (0,size_problem-1):
for j in range(i+1,size_problem):
... | 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"
] | n,m=map(int,input().split())
a=[int(i)-1 for i in input().split()]
ans1=[i+1 for i in range(n)]
ans2=[-1 for i in range(n)]
for i in set(a):
ans1[i]=1
N=1
while N<n+m:N<<=1
st=[0 for i in range(N<<1)]
pos=[i+m for i in range(n)]
for i in range(n):
st[i+N+m]=1
for i in range(N-1,0,-1):
st[i... | 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"
] | t=int(input())
for _ in range(t):
size=int(input())
path=input()
l,res=0,[-1]
min_length=size+1
pos_idx={(0,0):-1}
x,y=0,0
for r,go in enumerate(path):
if go=="L":
x-=1
elif go=="R":
x+=1
elif go=="U":
y+=1
... | py |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a... | [
"data structures",
"hashing",
"strings"
] | import sys
input = sys.stdin.readline
n=int(input())
t=input().strip()
q=int(input())
ZEROS=[0]*n
ZERO_ONE=[]
ONECOUNT=[0]*n
ind=0
count=0
for i in range(n):
ZEROS[i]=ind
if t[i]=="0":
ind+=1
ONECOUNT[i]=count%2
ZERO_ONE.append(count%2)
count=0
else:
... | 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"
] | def read():
return [int(i) for i in input().split()]
def solve():
[n,m]=read()
a=read()
a.sort()
nax=64
def cb(num,bit):
return (num>>bit)&1
if sum(a)<n:
print(-1)
return
ct=[0 for i in range(nax)]
for i in range(m):
for bit in range(nax):
if cb(a[i],bit):
ct[bit]+=1
ans ... | 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
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
BUFSIZE = 8192
class FastIO(I... | py |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l... | [
"data structures",
"geometry",
"greedy"
] | from __future__ import division, print_function
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
l = list(map(int, input().split()))
# not my solution, from: https://codeforces.com/contest/1299/submission/70653333
su = [l[0]]
cou = [-1, 0]
for k in range(1, n):
nd ... | py |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is whi... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | import 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 |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip... | [
"math"
] | from collections import Counter, deque, defaultdict
import math
from itertools import permutations, accumulate
from sys import *
from heapq import *
from bisect import bisect_left, bisect_right
from functools import cmp_to_key
from random import randint
xor = randint(10 ** 7, 10**8)
# https://docs.python.org/3... | 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"
] | 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.wri... | 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
from array import array
input = lambda: sys.stdin.buffer.readline().decode().strip()
inp = lambda dtype: [dtype(x) for x in input().split()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
Mint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, []
for _ in range(1):
M... | py |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going... | [
"constructive algorithms",
"graphs",
"implementation"
] | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections impor... | py |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The ... | [
"brute force",
"greedy",
"implementation"
] | def fonction(a,b,c):
som=0
if a>0 :
som+=1
a-=1
if b>0:
som+=1
b-=1
if c >0:
som+=1
c-=1
if a>0 and b>0:
som+=1
a-=1
b-=1
if a==b==0 and c>1:
som-=1
a+=1
b+=1
... | 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 feasible(mid,a,b,s,p):
changes = 0
cost = 0
if mid<len(s)-1:
if s[mid]=="A":
cost+=a
else:
cost+=b
for i in range(mid+1,len(s)-1):
if i>0 and s[i]!=s[i-1]:
changes+=1
if s[i]=='A':
cost+=a
... | py |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given... | [
"graphs",
"hashing",
"math",
"number theory"
] | from collections import Counter
from sys import stdin
from math import gcd
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
n, m = map(int, input().split())
values = list(map(int, input().split()))
y_neigh = [[] for i in range(n)]
for i in range(m):
... | 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, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
ans = []
for _ in range(t):
n, m = map(int, input().split())
l = n - m
if l <= m + 1:
ans0 = n * (n + 1) // 2 - l
else:
x = l // (m + 1)
y = l % (m + 1)
ans0 = n... | 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"
] | def pp(a,b,c):
i=0
j=1000000000
while i<=j:
# if b==-3:
m=(i+j)//2
x=b+m*c
# print(i,j,x,a,b,c)
if x==a:
return True
if x>a:
if c>0:
j=m-1
else:
i=m+1
else:
... | 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 time
import os,sys
from datetime import datetime
from math import floor,sqrt,gcd,factorial,ceil,log2
from collections import Counter,defaultdict as dd
import bisect
from itertools import chain
from collections import deque
from sys import maxsize as INT_MAX
from itertools import permutations
from colle... | 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())
a = sorted([list(map(int, input().split())) for _ in range(n)])
if any(y1 < y0 for (_, y0), (_, y1) in zip(a, a[1:])):
print("NO")
else:
print("YES")
x = y = 0
for nx, ny in a:
print(end="R" * (nx - x) + "U" * (ny... | py |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11)... | [
"implementation"
] | n = int(input())
a = [int(x) for x in input().split()][:n]
count, max = 0, 0
check1, loopEnded = False, False
start, end = 0, 0
for i in range(n):
if a[i] == 1:
count += 1
if check1 == False:
start += 1
if i == n - 1: loopEnded = True
else:
count = 0
check1 = True
if count > max: max = count
for i i... | 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 lcm, ceil
min = n = int(input())
sq = ceil(n ** 0.5) + 1
x = 1
while x < sq:
if n % x == 0:
y = n // x
if lcm(x, y) != n:
x += 1
continue
mx = max(x, y)
if mx < min:
min = mx
x += 1
print(n // mx, mx)
| 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"
] | #13B - Letter A
import math
r = lambda: map(int,input().split())
#Function to check if the lines cross
def cross(a, b):
return a[0] * b[1] - a[1] * b[0]
def dot(a, b):
return a[0] * b[0] + a[1] * b[1]
# def l(v):
# return math.hypot(*v)
def on_line(a, b):
return dot(a, b) > 0 and cross(a, b) == 0 and... | 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"
] | class HLD:
def __init__(self, g):
self.g = g
self.n = len(g)
self.parent = [-1]*self.n
self.size = [1]*self.n
self.head = [0]*self.n
self.preorder = [0]*self.n
self.k = 0
self.depth = [0]*self.n
for v in range(self.n):
... | 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"
] | for _ in range(int(input())):
n, x = map(int, input().split())
a = list(map(int, input().split()))
if x in a:
print(1)
else:
a = sorted(a)
i = 0
j = len(a)-1
f = 0
if x%2==0:
while i<=j:
m = (i+j)
if... | 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())
lst = [int(x) for x in input().split()][:n]
sum = 0
for i in range(n):
sum += lst[i]
print(min(m, sum))
| 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] * (n + 1)
s... | 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"
] | t = int(input())
t_c = [tuple(map(int, input().split())) for _ in range(t)]
for i in t_c:
l = None
if i[1] < 9 :
l = 0
elif int((tmp := len(str(i[1]))) * '9') <= i[1]:
l = tmp
else:
l = tmp - 1
print(i[0] * l) | 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"
] | t = int(input()) # t (1≤t≤104) — количество наборов входных данных
for i in range(t):
n = int(input())
#kr = input()
#kr =[int(x) for x in kr]
a = input() ; a = a.split()
a = [int(x) for x in a]
#s = input()
sm = sum(a)
kol = a.count(0)
if sm + kol == 0:
... | 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"
] | # LUOGU_RID: 101844461
n, m = map(int, input().split())
s = input().split()
t = input().split()
for _ in range(int(input())):
x = int(input()) - 1
print(s[x % n] + t[x % m]) | 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
for _ in range(int(sys.stdin.readline())):
a,b,c=map(int,sys.stdin.readline().split())
a1,b1,c1=a,b,c
count=10**9+7
for i in range(1,a*2+1):
for j in range(i,2*b+1,i):
for x in range(j,2*c+1,j):
y=abs(a-i)+abs(b-j)+abs(c-x)
if y<cou... | py |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t... | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
input = sys.stdin.buffer.readline
def process_root(g, r):
start = [r]
seen = {r: 0}
parent = {r: None}
while len(start) > 0:
next_s = []
for x in start:
for y in g[x]:
if y not in seen:
seen[y] = seen[x]+1
... | 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"
] | from audioop import reverse
from sys import stdin, stdout
import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_arr(): return list(map(int, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
t = int(input())
while t:
t-=1
n = ... | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.