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 |
|---|---|---|---|---|---|
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"
] | import os
import sys
from io import BytesIO, IOBase
from collections import Counter
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 |
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, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
from itertools import permutations
# sys.setrecursionlimit(2*10**5+10000)
BUFSIZE = 8192
class Fas... | py |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, whe... | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | import sys
input=lambda:sys.stdin.readline().rstrip()
def calc(A,i,j,k):
if k==0:
return 0
if A[i]%(k*2)>=k or A[j]%(k*2)<k:
return calc(A,i,j,k//2)
index=i+[l%(k*2)>=k for l in A[i:j+1]].index(1)
return k+min(calc(A,i,index-1,k//2),calc(A,index,j,k//2))
def solve():
n=int(input())
A=sorted(list(ma... | py |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longe... | [
"greedy",
"implementation"
] | t=int(input())
for i in range(t):
n=int(input())
arr=list(map(int,input().split()))
c=set(arr)
print(len(c)) | py |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, whe... | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def binary_trie():
G0, G1, cnt = [-1], [-1], [0]
return G0, G1, cnt
def insert(x, l):
j = 0
for i in range(l, -1, -1):
cnt[j] += 1
if x & pow2[i]:
if G1[j] == -1:
G0... | 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"
] | T = int(input())
for ti in range(T):
s, t = input().strip(), input().strip()
N = len(t)
for i in range(1, N+1):
dp = [0]+[-1]*i
for l, c in enumerate(s):
for j in range(i, -1, -1):
tmp = dp[j]
if dp[j] != -1 and i + dp[j] < N and \
... | 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"
] | import os
import sys
from io import BytesIO, IOBase
MOD0 = 10 ** 9 + 7
MOD1 = 998244353
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.... | py |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ... | [
"data structures",
"greedy"
] | from collections import defaultdict
n = int(input())
arr = list(map(int, input().split()))
pre = [0]*(n+1)
for i in range(n):
pre[i+1] = pre[i] + arr[i]
mp = defaultdict(list)
for i in range(n):
for j in range(i,n):
sum = pre[j+1] - pre[i]
mp[sum].append((i,j))
k = 0
ans ... | 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"
] | # -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List
"""
created by shhuan at 2020/3/13 21:15
"""
def check(x, y, N):
return 1 <= x <= N and 1 <= y <= N
def dfs(x, y, d, marks, X, ... | 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"
] | import sys
input = sys.stdin.readline
test = int(input())
for _ in range(test):
s = input().rstrip()
t = input().rstrip()
n = len(s)
m = len(t)
ansls = []
pos = [[1000 for i in range(26)] for j in range(n+2)]
for i in range(n+1)[::-1]:
if i < n:
for j in range(26):
pos[i][j]... | 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"
] | from collections import defaultdict as dc
n=int(input())
a,b=list(input()),list(input())
frqa=dc(lambda:list())
frqb=dc(lambda:list())
for i in range(n):frqa[a[i]].append(i)
for i in range(n):frqb[b[i]].append(i)
i=96
ans=list()
#print(ord('?'))=63
while i<=122:
i+=1
c=chr(i)
if c in frqa and c... | py |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position... | [
"math"
] | l = int(input())
input()
print(l + 1) | py |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distrib... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 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 |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she cam... | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | import sys
input = sys.stdin.buffer.readline
def radix(a):
digits = len(str(max(a)))
for i in range (digits):
b = [[] for _ in range (10)]
e = pow(10, i)
for j in a:
num = (j//e)%10
b[num].append(j)
a *= 0
for l in b:
... | py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun... | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno... | py |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for an... | [
"brute force",
"greedy",
"math"
] | # 13:17-
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
A = list(map(int, input().split()))
cnt = [0]*32
for i in range(32):
for a in A:
if a&(1<<i):
cnt[i]+=1
find = -1
for i in range(31,-1,-1):
if cnt[i]==1:
find = i
break
if find>=0:
idx = 0
for i in r... | 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 = ... | 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"
] | for _ in range(int(input())):
n = int(input())
m, t = 0, 0
a = input()
if n == 1 or len(set(a)) == 1:
print(0)
continue
j = a.index('A')
for i in range(j + 1, n):
if a[i] == 'P':
t += 1
else:
m = max(m, t)
t = 0
... | py |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse... | [
"brute force",
"dp",
"greedy",
"implementation"
] | for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
for i in range(n):
if arr[i] % 2 == 0:
print(1)
print(i + 1)
break
else:
if n == 1:
print(-1)
else:
print(2)
p... | py |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the nu... | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | from sys import stdin
input = stdin.readline
import math
for case in range(int(input())):
n, m = map(int, input().split())
ans = n * (n + 1) // 2
small = (n - m)//(m + 1); avg_split = (n - m)/(m + 1)
large = small + 1
num_large = (n - m) % (m + 1)
num_small = m + 1 - num_large
... | 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"
] | R=lambda:map(int,input().split())
t,=R()
for _ in[0]*t:
n,k=R();a=*R(),;r='YES'
while any(a):
if[x%k for x in a if x%k]>[1]:r='NO'
a=[x//k for x in a]
print(r)
| py |
1284 | D | D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn l... | [
"binary search",
"data structures",
"hashing",
"sortings"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
N=100101
n = int(input())
rand = [((i+12345)**3)%998244353 for i in range(N*2+20)]
al,ar,bl,br=[],[],[],[]
for _ in range(n):
a,b,c,d=map(int,input().split())
al.append(a)
ar.append(b)
bl.append(c)
br.append(d)
def calk(l,r):
ma={s:idx f... | 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 _ in [0]*int(input()):
a,b = map(int, input().split())
print(a*(len(str(b+1))-1)) | py |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly,... | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] |
def main():
t=int(input())
allans=[]
for _ in range(t):
n,s=input().split()
n=int(n)
s=s+'$'
seq=[] # [isIncreasing,length]
prev=None
l=0
for c in s:
if c!=prev:
if l>0: # not first
... | 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 sys
from math import *
from collections import *
inp = lambda: sys.stdin.buffer.readline().decode().strip()
out=sys.stdout.write
# n=int(inp())
# arr=list(map(int,inp().split()))
def solve():
u,v=map(int,inp().split())
if v%2!=u%2 or u>v:
print(-1)
return
if u==v==0:
... | 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"
] | from operator import itemgetter
import sys
import bisect
input = sys.stdin.readline
class BIT():
"""区間加算、区間取得クエリをそれぞれO(logN)で答える
add: 区間[l, r)にvalを加える
get_sum: 区間[l, r)の和を求める
l, rは0-indexed
"""
def __init__(self, n):
self.n = n
self.bit0 = [0] * (n + 1)
s... | py |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit... | [
"greedy"
] | t = int(input())
for _ in range(t):
segments = int(input())
if segments < 2:
print("1")
else:
rem = segments % 2
if rem:
total_ones = segments - 3
total = "7"+("1"*(total_ones//2))
print(total)
else:
ones = "1"*(... | 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"
] | #z=int(input())
import math
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}
alfabet_2={'1':"a", '2':"b", '3':"c", '4':"d", '5':"e", '6':"f", '7':"g",... | py |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusiv... | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | import sys
input = sys.stdin.readline
n = int(input())
d = [[] for i in range(n)]
w = []
for i in range(n-1):
a, b = map(lambda x:int(x)-1, input().split())
d[a].append((b, i))
d[b].append((a, i))
q = []
for i in d:
if len(i) >= 3:
q = i
break
if q == []:
for i i... | 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"
] | n = int(input())
output = [ ]
for i in range(n):
A, B = [int(x) for x in input().split()]
output.append(A * (len(str(B+1)) - 1))
print(*output, sep = "\n") | 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
input=sys.stdin.readline
a = [0 for i in range(3505)]
q = int(input())
for _ in range(q):
n, m, k = map(int, input().split())
a[1:] = list(map(int, input().split()))
k = min(k, m-1)
re, ans = n-k, 0
for l in range(1, n-re+2):
r, x, len = l + re - 1, int(1e9), n-m+1
... | 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"
] | mod=int(1e9+7)
def read():
return [int(i) for i in input().split()]
"""
dp[i][j]: dp[i+x][j-x]
next[i][j]: dp[i][j]+dp[i-1][j]+dp[i][j-1]+dp[i-1][j-1]
increasing in a, decreasing in b
ndp[i][j]: dp[i][j] + dp[i][j+1] + dp[i-1][j]
"""
def main():
n,m=read()
# a: increasing, b: decreasing
... | 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"
] | for i in [*open(0)][1:]:
x,y,a,b=map(int,i.split())
a+=b
y-=x
print([y//a,-1][y%a>0]) | py |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any othe... | [
"dfs and similar",
"graphs",
"shortest paths"
] | import bisect
import collections
import copy
import enum
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(3001)
input = sys.stdin.readline
ng= collections.defaultdict(list)
sp = coll... | py |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are an... | [
"greedy",
"implementation"
] | t = int(input())
while t > 0:
t -= 1
n = int(input())
s = input()
ang, mx, cnt = 0, 0, 0
for i in range(n):
if s[i] == 'A':
ang = 1
mx = max(mx, cnt)
cnt = 0
elif ang and s[i] == 'P':
cnt += 1
mx = max(mx, cnt)
print(mx)
... | 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 _ in range(t):
k = int(input())
s = input()
ans = 0
while "AP" in s:
s = s.replace("AP", "AA")
ans += 1
print(ans) | 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"
] | # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
import os
import sys
from io import BytesIO, IOBase
import math
from heapq import heappop, heappush, heapify, heapreplace
from collections import defaultdict, deque, OrderedDict
from bisect import bisect_left, bisect_righ... | py |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. ... | [
"data structures",
"dsu"
] | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
p = list(map(int, input().split()))
BLOCK_LENGTH = 350
block = [i//BLOCK_LENGTH for i in range(n)]
jumps = [0] * n
end = [0] * n
for i in range(n - 1, -1, -1):
nex = i + p[i]
if nex >= n:
jumps[i] = 1
end[... | 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"
] | from sys import stdin
input = stdin.readline
u, v = [int(x) for x in input().split()]
if u > v or (v-u)%2 == 1: print(-1)
elif u == v == 0: print(0)
elif u == v: print(1); print(u)
else:
x = (v-u)//2
# if ((u+x)^x) == u and u+x+x == v: print(2); print(u+x, x)
if (u&x) == 0: print(2); print(u+x,... | 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())
for i in range(t):
a,b=map(int,input().split())
print(a*(len(str(b+1))-1))
| py |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagram... | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | def charToInt(c): #'a'->0
return ord(c)-ord('a')
def main():
s=input()
n=len(s)
arr=[charToInt(c) for c in s]
p=makeArr(0,n,26)
for i in range(n):
p[i][arr[i]]+=1
for i in range(1,n):
for j in range(26):
p[i][j]+=p[i-1][j]
def g... | py |
13 | C | C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. ... | [
"dp",
"sortings"
] | import bisect
import copy
import gc
import itertools
from array import array
from fractions import Fraction
import heapq
import math
import operator
import os, sys
import profile
import cProfile
import random
import re
import string
from bisect import bisect_left, bisect_right
from collections import de... | 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"
] | i=lambda:input().split()
i();a,b=i(),i();c=d=0
for i,x in enumerate(a):c+=x>b[i];d+=b[i]>x
print([[1--(d+1-c)//max(1,c),1][c>d],-1][c<1]) | py |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly,... | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] | #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
t = int(input())
for _ in range(t):
n, s = input().split()
n = int(n)
hi, prev = n, 0
mi = [0] * n
for i in range(n):
if i == n - 1 or s[i] == '>':
for j ... | 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, Counter,deque
from math import sqrt, log10, log, floor, factorial,gcd
from bisect import bisect_left, bisect_right
from itertools import permutations,combinations
import sys, io, os
input = sys.stdin.readline
# input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# sys.s... | py |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagram... | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | # Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
def main():
s=input().rstrip()
n=len(s)
dp=[[0 for _ in range(26)] for _ in range(n+1)]
for i,v in enumerate(s):
dp[i+1][ord(v)-97]=1
for j in range(26):
... | 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"
] | import math
n, m = [int(x) for x in input().split()]
s, t = input().split(), input().split()
lowermn = min(n, m)
ip = int(input())
for _ in range(ip):
year = int(input()) - 1
print(s[year%n] + t[year%m])
| 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"
] | for i in range(int(input())):
l = input().split("R")
l.sort()
print(len(l[-1])+1) | py |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given... | [
"graphs",
"hashing",
"math",
"number theory"
] | import sys
input = sys.stdin.buffer.readline
def gcd(a, b):
if a > b:
a, b = b, a
if b % a==0:
return a
return gcd(b % a, a)
t = int(input())
for i in range(t):
n, m = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
G = []
for... | py |
1141 | A | A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of ... | [
"implementation",
"math"
] | def main(list):
res = 0
if list[1]%list[0]!=0:
return -1
else:
k = list[1]//list[0]
while k>1:
if k%3==0:
k//=3
res+=1
elif k%2==0:
k//=2
res+=1
else:
re... | 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"
] | for i in' '*int(input()):
x,y,a,b=map(int,input().split())
print([(y-x)//(a + b),-1][(y-x)%(a+b)>0])
| 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"
] | from math import comb as c
n, m = map(int, input().split())
print(c(n + 2 * m - 1, 2 * m) % 1000000007)
| 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"
] | from math import ceil
H,n=map(int,input().split())
array=list(map(int,input().split()))
cumsum=[array[0]]
minm=array[0]
for i in range(1,n):
val=cumsum[-1]+array[i]
minm=min(minm,val)
cumsum.append(val)
if cumsum[-1]>=0:
if minm+H>0:
print(-1)
else:
for i in range(n):
... | py |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the n... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
... | py |
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"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m = map(int, input().split())
l = n + 5
fact = [1] * (l + 1)
for i in range(1, l + 1):
fact[i] = i * fact[i - 1] % m
ans = 0
for i in range(1, n + 1):
c = n - i + 1
ans += pow(c, 2, m) * fact[i] % m * fact[n - i] ... | py |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be ... | [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | def solve(lsts):
points = []
for i in range(len(lsts)):
points.append((lst[i][0], 0, i))
points.append((lst[i][1], 1, i))
points.sort()
open = set()
increased = [0] * len(lsts)
original = 0
for i in range(len(points)):
p = points[i]
if p... | 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"
] | #editorial solution
t = int(input())
for _ in range(t):
n, s, k = map(int, input().split())
a = set(map(int, input().split()))
ans = 0
for i in range(k+1):
if (s-i >= 1 and not s-i in a) or (s+i <= n and not s+i in a):
ans = i
break
print(ans)
| py |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, whe... | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
from itertools import permutations
# sys.setrecursionlimit(2*10**5+10000)
BUFSIZE = 8192
class FastIO(IOBase... | 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"
] | # Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
import sys
input = sys.stdin.readline
from collections import defaultdict
from collections import Counter
from string import ascii_lowercase
from functools import lru_cache
from collections impo... | py |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. ... | [
"greedy",
"implementation"
] | for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split(' ')))
if n == 1:
print('Yes')
continue
left, right = [], []
cntL, cntR = 0, 0
for i in range(n):
if arr[i] >= i:
cntL += 1
if arr[n-1-i] >= i:
cntR += 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 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 |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii i... | [
"dp",
"greedy",
"implementation"
] | def solve():
n = int(input())
aseq = read_ints()
acc1 = acc2 = 0
for i in range(n-1):
acc1 += aseq[i]
acc2 += aseq[n-i-1]
if acc1 <= 0 or acc2 <= 0:
return False
return True
def main():
t = int(input())
output = []
for _ in range(t... | 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"
] | # NOT MY CODE
# https://codeforces.com/contest/1324/submission/73179914
## PYRIVAL BOOTSTRAP
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
# This decorator allows for recursion without actually doing recursion
from types import GeneratorType
def bootstrap(f, stack=[]):
... | 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"
] | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def euler_path(n,path):
height = [0]*n+[10**10]
euler,st,visi,he = [],[0],[1]+[0]*(n-1),0
first = [-1]*n
while len(st):
x = st[-1]
euler.append(x)
if first[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"
] | def solve():
s = input()
a = ['']*60
i = 30
vis = set()
for j in range(len(s)):
if j == 0:
a[i] = s[j]
vis.add(s[j])
elif a[i-1] == s[j]: i -= 1
elif a[i+1] == s[j]: i += 1
elif a[i-1] == '':
if s[j] in vis:
... | py |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagram... | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | s=input()
n=len(s)
d={}
for i in range(26):
d[chr(ord("a")+i)]=0
arr=[0 for i in range(n)]
c=0
i,j=0,0
while(j<n):
d[s[j]]+=1
if d[s[j]]==1:c+=1
while(c==3):
arr[i]=j
d[s[i]]-=1
if d[s[i]]==0:c-=1
i+=1
j+=1
for k in range(i,n):
arr[k]=n
# print(arr)
for _ in range(int(inp... | py |
1312 | G | G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type... | [
"data structures",
"dfs and similar",
"dp"
] | import io
import os
DEBUG = False
def dfs(trie, root, preorder=None, postorder=None):
stack = [root]
seen = set()
while stack:
nodeId = stack.pop()
if nodeId not in seen:
if preorder:
preorder(nodeId)
stack.append(nodeId)
seen.add(nodeId... | py |
1311 | C | C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons ... | [
"brute force"
] | from heapq import heappush,heappop,_heapify_max,heapify
import operator as op
import sys
from bisect import bisect_left as b_l
from bisect import bisect_right as b_r
from collections import defaultdict, deque
from functools import reduce
from math import ceil, factorial, gcd, sqrt,log2,log
INT_MAX = sys.maxsi... | py |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for an... | [
"brute force",
"greedy",
"math"
] | import sys
input = sys.stdin.readline
n = int(input())
w = list(map(int, input().split()))
d = [-1]*35
for i in range(n):
x = w[i]
j = 0
while x:
if x % 2:
if d[j] == -1:
d[j] = i
else:
d[j] = -2
x >>= 1
j += 1
... | py |
1285 | E | E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be ... | [
"brute force",
"constructive algorithms",
"data structures",
"dp",
"graphs",
"sortings",
"trees",
"two pointers"
] | import io
import os
from collections import Counter, defaultdict, deque
# From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the segment tree with data"""
self._default =... | 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
def find(x):
if x == pre[x]:
return x
else:
pre[x]=find(pre[x])
return pre[x]
def merge(x,y):
x = find(x)
y = find(y)
if x != y:
pre[x] = y
siz[y] +=siz[x]
def cal(x):
return min(siz[find(x)],siz[find(x+k)])
def Solve(i): ... | py |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit... | [
"greedy"
] | from 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 |
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 math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, functools, copy,statistics
inf = float('inf')
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readl... | py |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii i... | [
"dp",
"greedy",
"implementation"
] | import itertools
for t in range(int(input())):
n = int(input())
a = list(itertools.accumulate(map(int, input().split())))
if min(a[:-1]) <= 0 or max(a[:-1]) >= a[-1]:
print('NO')
else:
print('YES')
| 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"
] | from sys import stdin
input = stdin.readline
import math
n, a, b, k = map(int, input().split())
h = list(map(int, input().split()))
ans = 0; s = []
for e in h:
if e % (a + b) == 0:
rem = a + b
else:
rem = e % (a + b)
if a >= rem:
ans += 1
continue
else:
need =... | 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"
] | t=int(input())+1
while t := t-1:
n,g,b=[int(x) for x in input().split()]
mid=(n+1)//2
fb,re=mid//g,mid%g
comb=(b*(fb-1))
ans= 0
if re != 0:
comb+=b
ans+=re
ans=mid+comb
comb=n-mid-comb
if comb >0:
ans+=comb
print( ans ) | py |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then... | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
... | py |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vac... | [
"greedy",
"implementation"
] | for q in range(int(input())):
n,d = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
ans = arr[0]
for i in range(1,n):
temp = min(arr[i], d//i)
ans += temp
d -= temp*(i)
print(ans)
| 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, 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().split()));... | 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"
] | import re
import functools
import random
import sys
import os
import math
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce
from itertools import accumulate, combinations, permutations
from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush
from... | py |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of ... | [
"implementation",
"math"
] | # LUOGU_RID: 100463992
n=int(input())
k=0
z=n
for i in range(2,n):
while n!=0:
k+=n%i
n=n//i
n=z
a=max(k,n-2)
b=min(k,n-2)
n=a%b
while n!=0:
a=b
b=n
n=a%b
print(int(k/b),end='/')
print(int((z-2)/b)) | 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"
] | #Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me,
import sys
#then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize,
import os
#just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails
from io import Byt... | py |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a s... | [
"brute force",
"strings"
] | for _ in " "*int(input()):
a=int(input());z="NO"
k=list(map(int,input().split()))
for i in range(a-2):
if k[i] in k[i+2:]:z="YES";break
print(z) | py |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such... | [
"dp",
"greedy"
] | from sys import stderr
N = 505
dp1 = [N*[-1] for _ in range(N)]
dp2 = N*[int(1e9)]
def calculate1():
for l in range(n):
dp1[l][l+1] = a[l]
for d in range(2,n+1):
for l in range(n+1-d):
r = l + d
for mid in range(l+1, r):
lf = dp1[l][mid]
... | 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"
] | #from itertools import *
#from math import *
#from bisect import *
#from collections import *
#from random import *
#from decimal import *
#from heapq import *
#from itertools import * # Things Change ....remember :)
import sys
input=sys.stdin.readline
def inp():
return int(input())
def st():... | py |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between ... | [
"greedy",
"implementation",
"math"
] | import sys
input = sys.stdin.readline
from collections import defaultdict
def main():
n,m = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(n)]
for i in range(n):
for j in range(m):
A[i][j] -= 1
if n == m == 1:
if A[0][0] == 0:
... | py |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positiv... | [
"greedy",
"implementation",
"math"
] | for i in range(int(input())):
a,b=map(int,input().split())
if(a==b):
print(0)
elif(a%2==0 and b%2==0):
if(a>b):
print(1)
else:
print(2)
elif(a%2==1 and b%2==1):
if (a > b):
print(1)
else:
print(2)
e... | 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"
] | import math
import collections
import sys
def inpu():
return input().split(' ')
def inti(a):
for i in range(len(a)):
a[i] = int(a[i])
return a
def inp():
a = inpu()
a = inti(a)
return a
def solution():
n, m, k = map(int, input().split())
c = 0
i = 0
if k > 4*n*m-2... | 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"
] | def check(x):
l, r = 0, k
while l < r:
m = l + (r - l) // 2
if arr[m] == x:
return m
elif arr[m] > x:
r = m
else:
l = m + 1
return -1
for _ in range(int(input())):
n, s, k = map(int, input().split())
arr = list... | 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 = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [0 for i in range(m)]
c = [0 for i in range(m)]
for i in a:
b[i % m] += 1
c[i % m] = i
for i in b:
if (i > 1):
print(0)
exit()
# print([i for i in range(1, 10)])
tot = 1
for i in range(m):
if b[i] == 1:
... | py |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are prese... | [
"data structures",
"greedy",
"implementation",
"math"
] | import sys
q,x=map(int,sys.stdin.readline().split())
mex = 0
map=dict()
for _ in range(q):
v=int(sys.stdin.readline())%x
if v in map:
map[v + x*map[v]] = 1
map[v] += 1
else:
map[v] = 1
while mex in map:
mex += 1
print(mex) | 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"
] | for i in[*open(0)][1:]:print(max(map(len,i.replace("\n","").split("R")))+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"
] | def lex(s,k):
if (len(s)-k)%2==1:
t = s[k-1:] + s[0:k-1]
else:
t = s[k-1:] + s[0:k-1][::-1]
return t
for times in range(int(input())):
n = int(input())
s = input()
st = lex(s,1)
ansk = 1
for k in range(2,n+1):
if lex(s,k)<st:
st = lex(s,k)
ansk = k
print(st)
print(ansk) | py |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tr... | [
"binary search",
"dp",
"greedy",
"strings"
] | t=int(input());
for i in range(0,t):
z=0
e=input().split()
a=int(e[0])
b=int(e[1])
p=int(e[2])
s=str(input())
j=len(s)-2
r=len(s)
c=0
while(j>=0):
l=s[j]
while(s[j]==l and j>=0):
j-=1
if(l=='A'):
c+=a
else:
c+=b
... | py |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ... | [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | n=int(input())
s=input()
arr=[]
for i in range(n):
arr.append((s[i],i))
arr.sort(key=lambda x:(x[0],x[1]))
# print(arr)
new=[0 for i in range(n)]
for i in range(n):
new[arr[i][1]]=i
arr=new
color=[-1 for i in range(n)]
st=[]
fin=[]
i=0
index=0
yes=1
# print(arr)
colored={}
while(i<n):
# print(... | 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"
] | import sys
import math
import heapq
from collections import defaultdict,Counter,deque
input = sys.stdin.readline
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return ... | py |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a ... | [
"combinatorics",
"math"
] | from itertools import permutations
def solve(n):
ans = [0 for i in range(n)]
for p in permutations(range(n)):
for st in range(n):
mx = mn = p[st]
for en in range(st, n):
mx = max(mx, p[en])
mn = min(mn, p[en])
if mx - mn == en - st:
ans[en - st] += 1
... | py |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is t... | [
"bitmasks",
"greedy"
] | import sys
import threading
input=sys.stdin.readline
from collections import Counter,defaultdict,deque
from heapq import heappush,heappop,heapify
#threading.stack_size(10**8)
#sys.setrecursionlimit(10**6)
def ri():return int(input())
def rs():return input()
def rl():return list(map(int,input().split()))
def... | py |
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"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
s=input().strip()
d=[0]*1000
e=[0]*1000
hist=[0]*26
for i in s:
j=ord(i)-ord('a')
for k in range(26):
e[k*26+j]+=hist[k]
hist[j]+=1
d[j]+=1
print(max(d+e))
| 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"
] | print(sum(1/i for i in range(1,int(input())+1)))
#??
| py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.