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 |
|---|---|---|---|---|---|
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array m... | [
"constructive algorithms",
"sortings"
] | t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()))
print(*sorted(arr, reverse = True)) | 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"
] |
def palindrome(a):
n = len(a)
for i in range(n - 2):
for j in range(i + 2, n):
if a[i] == a[j]:
return True
return False
t = int(input())
for _ in range(t):
input()
a = list(map(int, input().split()))
if palindrome(a):
print("YES")
else:
... | 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"
] | def get_sumDigit(n,base):
sum_digits =0
#digits = []
while n>0:
digit = n%base
#digits.append(digit)
sum_digits += digit
n//=base
#print(*digits[::-1],sep='')
return sum_digits
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
n = int(inp... | py |
1316 | D | D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n b... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | def main():
n = int(input())
board = []
told = []
blocked = []
for r in range(1, n + 1):
endings = list(map(int, input().split()))
board.append([])
told.append([])
for i in range(0, 2 * n, 2):
x, y = endings[i:i + 2]
told[-1].append((x, y))
... | 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()))
LENGTH = 320
block = [i // LENGTH for i in range(n)]
lompat = [0] * n
akhir = [0] * n
for i in range(n - 1, -1, -1):
next = i + p[i]
if next >= n:
akhir[i] = i + n
lompat[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"
] | import io
import os
from collections import defaultdict
# 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 = default
... | 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 itertools import accumulate
from math import ceil
H, n = map(int, input().split())
nums = list(map(int, input().split()))
prefixsum = list(accumulate(nums))
# find the min elmnt
the_min = -min(prefixsum)
last_change = -prefixsum[-1]
# calculate the iteration
turns = 0
if H > the_min and prefi... | py |
1292 | F | F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's a... | [
"bitmasks",
"combinatorics",
"dp"
] | MOD = 1000000007
def isSubset(a, b):
return (a & b) == a
def isIntersect(a, b):
return (a & b) != 0
# Solve for each weakly connected component (WCC)
def cntOrder(s, t):
p = len(s)
m = len(t)
inMask = [0 for i in range(m)]
for x in range(p):
for i in range(m):
if t[i] % s[x] == 0:... | py |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she cam... | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | import sys
input = sys.stdin.buffer.readline
from collections import deque
def radix_sort(a):
l = len(a)
mx = max(a)
m = 0
while mx > 0:
mx = mx // 10
m += 1
bucket = [deque([]) for _ in range (10)]
for j in range (m):
div = pow(10, j)
for i in ra... | py |
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"
] | t = int(input())
for _ in range(t):
m,n = map(int,input().split())
l = list(map(int,input().split()))
p = list(map(int,input().split()))
p.sort()
d,c = 0,0
for i in range(n-1):
if p[i]+1 == p[i+1]:
if c == 0:
x = p[i]
y = p[i+1]
... | py |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller ... | [
"math"
] | def main():
t = int(input())
anss = [0] * t
for it in range(t):
x, y, a, b = map(int, input().split())
d, m = divmod(y - x, a + b)
anss[it] = d if m == 0 else -1
for ans in anss:
print(ans)
main()
| 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"
] | n = int(input())
for i in range(n):
p,q = [int(i) for i in input().split()]
if p==q:
print(0)
elif p<q:
diff = q-p
if diff%2==0:
print(2)
else:
print(1)
elif p>q:
diff = p-q
if diff%2==0:
print(1)
else:
... | 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"
] | def gcd(a, b):
if a > b:
a, b = b, a
if b % a==0:
return a
return gcd(b % a, a)
primes = []
for p in range(2, 10**5+1):
is_prime = True
for p2 in primes:
if p2*p2 > p:
break
if p % p2==0:
is_prime = False
break
... | py |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO... | [
"data structures",
"dsu",
"implementation"
] | def solve():
n,q = (int(i) for i in input().split(" "))
arr = [[0,0] for i in range(n)]
count = 1
for t in range(q):
a,b = (int(i)-1 for i in input().split(" "))
d = 1 if arr[b][a]==1 else -1
arr[b][a] = 1 - arr[b][a]
for dy in range(-1, 2):
... | 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"
] | # ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(... | 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"
] | from sys import stdin
input = stdin.readline
#google = lambda : print("Case #%d: "%(T + 1) , end = '')
inp = lambda : list(map(int,input().split()))
def answer():
cost = 0
ans , cur = n , "?"
for i in range(n - 2 , -1 , -1):
if(s[i] != cur):
cur = s[i]
... | 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"
] | from collections import Counter
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce
# sys.setrecursionlimit(10000000)
def input():
return sys.stdin.readline().strip()
def iinput():
return int(input()... | py |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne num... | [
"greedy",
"math",
"strings"
] | for _ in range(int(input())):
n = int(input())
s = input()
odd = []
for i in range(n):
if (int(s[i]) % 2 != 0):
odd.append(s[i])
if (len(odd) >= 2):
print(''.join(odd[-2:]))
else:
print(-1) | py |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good o... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | t=int(input())
for k in range(t):
nit,x,y=map(int,input().split())
print(max(1,min(nit,x+y-nit+1)),min(x+y-1,nit))
| py |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and re... | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | n=int(input())
s=input()
for _ in range(len(s)):
mx=0
ind=-1
for i in range(len(s)):
a=-1
b=-1
if i>0:
if ord(s[i-1])==ord(s[i])-1:
a=i
if i+1<len(s):
if ord(s[i+1])==ord(s[i])-1:
b=i
if a==i or b... | 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())
arr = []
for i in range(n):
arr.append(tuple(map(int, input().split())))
arr.sort()
valid = True
path = ("R" * arr[0][0]) + ("U" * arr[0][1])
for i in range(1, n):
if arr[i][1] - arr[i - 1][1] < 0:
v... | py |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then... | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | import sys
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()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
Mint, Mlong = 2 ** 31 - 1, 2 ** 63 - 1
out, tests = [... | 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"
] | import sys
zz=1
sys.setrecursionlimit(10**5)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
di=[[-1,0],[1,0],[0,1],[0,-1]]
def fori(n):
return [fi() for i in range(n)]
def inc(d,c,x=1):
d[c]=d[c]+x if c in d else x
def ii():
return input(... | 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 sys import stdin
input = stdin.readline
from math import ceil
inp = lambda : list(map(int,input().split()))
"""
we need n / 2 good days
"""
def answer():
x = n // 2 + (n % 2)
y = x // g
good = y * g
bad = (y - 1) * b
if(x % g):
good += x % g
bad += b
... | 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"
] | # Time complexity: O(n)
# Space complexity: O(n)
# The solution iterates through each vertex and edge once O(n + m)
# Then it iterates through each node it travels and its edge O(k + m)
import math
n, m = map(int, input().strip().split())
outadj = [set() for _ in range(n + 1)]
inadj = [set() for _ in range(n + 1)]
cos... | 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 types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to... | py |
1325 | 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"
] | # watchu lookin at?
import sys
from math import *
# from itertools import *
# from heapq import heapify, heappop, heappush
# from bisect import bisect, bisect_left, bisect_right
from collections import deque, Counter, defaultdict as dd
mod = 10**9+7
# Sangeeta Singh
def input(): return sys.stdin.readline... | py |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shape... | [
"brute force",
"data structures",
"implementation"
] | def predictFeature(a,b):
if a==b:
return a
else:
if 'S' in (a,b):
pass
else:
return 'S'
if 'T' in (a,b):
pass
else:
return 'T'
return 'E'
def hyperSet(n,k,l):
d = {}
for x in l:
if x not in d:
... | py |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. ... | [
"greedy",
"implementation"
] | import os,sys
from random import randint, shuffle
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math
# Fast... | py |
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"
] | T = int(input())
for _ in range(T):
n, x = map(int, input().split(' '))
ls = sorted(list(map(int, input().split(' '))))
if x in ls:
print(1)
elif ls[-1] > x:
print(2)
else:
print((x + ls[-1] - 1) // ls[-1])
| py |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l... | [
"data structures",
"geometry",
"greedy"
] | import sys
input = sys.stdin.buffer.readline
n = int(input())
a = list(map(int, input().split()))
stk = []
for x in a:
s = x
c = 1
while stk and stk[-1][0] * c >= s * stk[-1][1]:
s += stk[-1][0]
c += stk[-1][1]
stk.pop()
stk.append((s, c))
print(''.join('{}\n'.format(s / c) * ... | 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"
] | for t in range(int(input())):
a,b,p=map(int,input().split())
s=input()
n=len(s)
j,rj=0,0
pr=''
for i in range(n-2,-1,-1):
if s[i]!=pr:
if s[i]=='A' and p>=a:
p-=a
elif s[i]=='B' and p>=b:
p-=b
else:
... | 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"
] | import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
w = list(map(int, input().split()))
s = set()
c = 0
for i in range(n):
if w[i] == -1:
if i > 0 and w[i-1] != -1:
s.add(w[i-1])
if i < n-1 and w[i+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"
] | # https://codeforces.com/problemset/problem/1288/C
def f0(n, m):
mod = int(1e9 + 7)
c = 2 * m + 1
dp = [[0] * c for _ in range(n + 1)]
dp[0][0] = 1
for i in range(n):
# TODO 空间压缩
for j in range(c):
for k in range(j, c):
d = k - j
... | 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"
] | from collections import deque,Counter,OrderedDict
from math import *
import sys
import random
from bisect import *
from functools import reduce
from sys import stdin
from heapq import *
import copy
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines... | 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"
] | # 22:32-
import sys
input = lambda: sys.stdin.readline().strip()
from collections import Counter,defaultdict
def get_sums(A):
sum1 = []
for i in range(len(A)):
a,c = A[i]
t = [0]*26 if not sum1 else sum1[-1][::]
t[ord(a)-ord('a')]+=c
sum1.append(t)
return sum1
S = input()
C = Counter(S)
... | 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"
] | import sys
input = sys.stdin.readline
output = sys.stdout.write
def main():
tests = int(input().rstrip())
for i in range(tests):
a, b = map(int, input().rstrip().split())
cond1 = a % 2 == 1 and b % 2 == 1
cond2 = a % 2 == 0 and b % 2 == 0
res = 1
if a == b... | py |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she cam... | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | import sys
input = sys.stdin.buffer.readline
from collections import deque
def countingSort(arr, exp1):
n = len(arr)
output = [0] * (n)
count = [0] * (10)
for i in range(0, n):
index = arr[i] // exp1
count[index % 10] += 1
for i in range(1, 10):
count[i] += ... | 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"
] | row1 = int(input())
for r1 in range(row1):
l1 = input().split(' ')
row2 = int(l1[0])
tem = int(l1[1])
a = tem
b = tem
t1 = 0
state = 0
for r2 in range(row2):
l2 = input().split(' ')
t2 = int(l2[0])
c = int(l2[1])
d = int(l2[2])
a = a+... | 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"
] | from collections import deque
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def bfs(s):
q = deque()
q.append(s)
dist = [inf] * (n + 1)
dist[s] = 0
ans0 = n
while q:
i = q.popleft()
di = dist[i]
if di > p:
return... | 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 = list(map(int, input().split()))
groups = [a[0]]
counts = [1]
for i in range(1, len(a)):
ai = a[i]
if groups[-1] == ai:
counts[-1] += 1
else:
groups.append(ai)
counts.append(1)
best_count = 0
if groups[-1] == 1 and groups[0] == 1:
best_count = c... | py |
1292 | E | E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much... | [
"constructive algorithms",
"greedy",
"interactive",
"math"
] | import sys
n, L, minID = None, None, None
s = []
def fill(id, c):
global n, L, s, minID
L -= (s[id] == 'L')
s = s[0:id] + c + s[ id +1:]
minID = min(minID, id)
def query(cmd, str):
global n, L, s, minID
print(cmd, ''.join(str))
print(cmd, ''.join(str), file=sys.stderr)
... | py |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format ... | [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | import 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 |
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, os
input = sys.stdin.buffer.readline
def f(u, v):
os.write(1, b"%s %d %d\n" % (a, u, v))
w = int(input())
return w
def bfs(s):
q, k = [s], 0
visit[s] = 1
while len(q) ^ k:
i = q[k]
for j in G[i]:
if not visit[j]:
q.append(j... | py |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey... | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | from collections import defaultdict
import sys
input=sys.stdin.readline
n=int(input())
a=list(map(int,input().strip().split()))
d=defaultdict(int)
mx=max(a)
for i in range(n):
d[a[i]-i-1]+=a[i]
mx=max(mx,d[a[i]-i-1])
print(mx) | py |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,... | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | import sys
input = sys.stdin.readline
import bisect
n = int(input())
a, b = [], []
for i in range(n):
w = list(map(int, input().split()))[1:]
if sorted(w) == w[::-1]:
a.append(w[0])
b.append(w[-1])
a.sort()
print(n**2 - sum(bisect.bisect_right(a, i) for i in b)) | py |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 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 ... | [
"greedy"
] | 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 |
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"
] | count_of_ex = int(input())
rob1 = [int(x) for x in input().split()]
rob2 = [int(x) for x in input().split()]
rob1_dom = 0
rob2_dom = 0
i = 0
while i < count_of_ex:
if rob2[i] > rob1[i]:
rob2_dom += 1
elif rob1[i] > rob2[i]:
rob1_dom += 1
i += 1
if rob1_dom == 0:
print(-1)
else:
if rob1_dom > rob... | py |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between ... | [
"greedy",
"implementation",
"math"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
h,w=map(int,input().split())
mat=[]
for i in range(h):
mat.append(list(map(lambda x:int(x)-1,input().split())))
def calc(col):
ok=[0]*h
for i in range(h):
if col[i]!=-1:
ok[(i-col[i])%h]+=1
res=h
for i in range(h):
res=mi... | 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"
] | t = int(input())
for i in range(t):
n = int(input())
x = input()
ans = []
for i in x:
i = int(i)
if i % 2 == 1:
ans.append(i)
if len(ans) > 1:
print(ans[0], ans[1], sep = "")
else:
print(-1) | py |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e.... | [
"binary search",
"greedy",
"implementation"
] | import sys
import math
import collections
from heapq import heappush, heappop
from functools import reduce
input = sys.stdin.readline
ints = lambda: list(map(int, input().split()))
def factors(n):
return list(set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) i... | 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"
] | # 2022-07-03T13:11:49Z
def proc(n, s):
s = list(map(ord, s))
while True and len(s) > 1:
to_remove = []
for i in range(len(s)):
if i == 0:
if s[i] == s[i + 1] + 1:
to_remove.append(i)
elif i == len(s) - 1:
if s[i] == s[... | 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"
] | n=int(input())
f=[[[1000,1000]for _ in range(n+1)]for _ in range(n+1)]
f[0][0]=[0,0]
for i,v in enumerate(map(int,input().split())):
for j in range(i+2):
if v==0 or v%2:f[i+1][j][1]=min(f[i][j][0]+1,f[i][j][1])
if v%2==0:f[i+1][j][0]=min(f[i][j-1][0],f[i][j-1][1]+1)
print(min(f[n][n//2])) | py |
1311 | C | C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons ... | [
"brute force"
] | t = int(input())
for _ in range(t):
n, m = map(int, input().split())
s = input()
p = list(map(int, input().split()))
mp = [0] * n
for value in p:
mp[value - 1] += 1
for i in range(n - 1, 0, -1):
mp[i - 1] += mp[i]
occ = [0] * 26
for i in range(len(s)):
... | py |
1286 | C1 | C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients th... | [
"brute force",
"constructive algorithms",
"interactive",
"math"
] | import sys, random
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18
LI = lambda : list(map(int, input().spl... | py |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossib... | [
"greedy"
] | for i in range(int(input())):
n = int(input())
b = list(map(int , input().split()))
dic = {}
l = []
for j in range(1 , 2*n+1):
dic[j] = 1
for j in range(n):
dic[b[j]] = 0
for j in range(n):
l.append(b[j])
# print(b[j] ,end= " ")
dic[b[j]]=0... | 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())
for _ in range(0, t):
n, m = map(int, input().split())
n, m = max(n, m), min(n, m)
if n%m == 0:
print("YES")
else:
print("NO") | py |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a cont... | [
"implementation",
"strings"
] | t = int(input())
for _ in range(t):
s = input().strip('0')
print(s.count('0')) | py |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 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 ... | [
"greedy"
] | import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
from itertools import permutations
from operator import itemgetter
# sys.setrecursionlimit(2*10**5+1000... | py |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero)... | [
"brute force",
"math"
] | from math import inf, sqrt
def main():
t = int(input())
while t:
a, b, c = list(map(int, input().split(' ')))
res = inf
res_list = list()
for i in range(1, 10001):
for j in range(i, 20001 ,i):
now = abs(j - b) + abs(i - a)
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"
] | for _ in range(int(input())):
a, b = map(int, input().split())
print(a*(len(str(b+1)) - 1)) | py |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to ... | [
"implementation"
] | t=int(input())
for i in range(t):
a,b,x,y=[int(j) for j in input().split()]
z1=(a-1-x)*b
z2=x*b
z3=a*(b-1-y)
z4=a*y
print(max(z1,z2,z3,z4)) | py |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji... | [
"binary search",
"data structures",
"sortings",
"two pointers"
] | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
arr = [a[i] - b[i] for i in range(n)]
arr.sort(reverse=True)
r = n - 1
res = 0
for i in range(n):
while r > i and arr[i] + arr[r] <= 0:
r -= 1
#print(f'i: {i}, r: {r}')
if r - i > 0:
res += r - i
print(res) | 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())):
a='R'+input()+'R'
b=0
c=0
for j in range(len(a)):
if a[j]=='R':
c=max(c,j-b)
b=j
print(c)
| py |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko... | [
"implementation",
"strings"
] | n = [int(_) for _ in input().split()]
a = [_ for _ in input().split()]
b = [_ for _ in input().split()]
for i in range(int(input())):
s = int(input())
v1 = s % n[0]
v2 = s % n[1]
print(''.join(a[v1-1])+ ''.join(b[v2-1]))
| 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"
] | def main_function():
n = int(input())
s = list(input())
counter_1 = 0
counter_2 = 0
for i in s:
if i == ")":
counter_2 += 1
else:
counter_1 += 1
if counter_1 != counter_2:
print(-1)
else:
is_started = False
one_c... | py |
1284 | D | D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn l... | [
"binary search",
"data structures",
"hashing",
"sortings"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
W = [(i+12345)**2 % 998244353 for i in range(N)]
AL, AR, BL, BR = [], [], [], []
for i in range(N):
a, b, c, d = map(int, input().split())
AL.append(a)
AR.append(b)
BL.append(c)
BR.append(d)
def chk(L, R):
... | 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"
] | input()
a = b = 0
for x, y in zip(input(), input()):
a += x > y
b += x < y
print(-1 if a==0 else b//a+1) | py |
1304 | E | E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then... | [
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.wr... | 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"
] | a=int(input())
for i in range(a):
n=int(input())
a1=list(map(int, input().split()))
a2=list(map(int, input().split()))
a1.sort()
a2.sort()
for j in range(n):
print(a1[j],end=" ")
print()
for j in range(n):
print(a2[j],end=" ")
print()
| 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"
] | import sys
for i in range(int(sys.stdin.readline())):
s = sys.stdin.readline().strip()
s += 'R'
m = 0
lc = 1
for j in s:
if j == 'L':
lc += 1
continue
m = max(lc, m)
lc = 1
print(m)
| 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 math
import copy
import itertools
import bisect
import sys
from heapq import heapify, heappop, heappush
input = lambda: sys.stdin.readline().rstrip("\r\n")
def ilst():
return list(map(int,input().split()))
def islst():
return list(map(str,input().split()))
def inum():
re... | 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"
] | q = int(input())
for i in range(q):
w, e, r, t = map(int, input().split())
y = max(w, e, r)
u = min(w, e, r)
o = w + e + r - y - u
p = (y - u) + (y - o)
if p <= t:
if (t - p) % 3 == 0:
print("YES")
else:
print("NO")
else:
print("NO") | 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 i in range(int(input())):
n1, n2 = map(int, input().split())
a_dados = list(map(int, input().split()))
p_posicoes = list(map(int, input().split()))
for i in range(n2):
for j in p_posicoes:
if a_dados[j-1]> a_dados[j]:
a_dados[j-1],a_dados[j] = a_dados[j],a_da... | 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())
for _ in range(T):
n = int(input())
A = sorted(list(map(int, input().split())))
B = sorted(list(map(int, input().split())))
print(*A)
print(*B) | py |
1312 | F | F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have t... | [
"games",
"two pointers"
] | import sys
readline = sys.stdin.buffer.readline
T = int(readline())
Ans = [None]*T
for qu in range(T):
N, x, y, z = map(int, readline().split())
A = list(map(int, readline().split()))
ts = 200
dp = [[0]*3 for _ in range(ts)]
table = [[[0]*4 for _ in range(3)] for _ in range(ts+8)]
... | py |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subse... | [
"brute force",
"dp",
"greedy",
"implementation"
] | import sys
import math
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 list(map(int, ... | py |
1292 | E | E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much... | [
"constructive algorithms",
"greedy",
"interactive",
"math"
] | import sys
t = int(input())
def get():
ans = ""
for i in range(n): ans = ans + S[i]
return ans
def query(pat):
print("Querying ", pat, file = sys.stderr)
print("? " + pat, flush = True)
A = list(map(int, input().split()))
for k in A[1:]:
for i in range(len(pat)):
S[k-1+i] = pat[i]
... | 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)]
INF=2*(10**9)
Q=[[] for i in range(10**6+1)]
for x,y,c in M:
Q[x].appe... | py |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusiv... | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | n = int(input());jaya= [0]*(n+1);l = []
for i in range(n-1):
a,b = map(int,input().split());a -= 1;b -= 1;jaya[a] += 1;jaya[b] += 1;l.append([a,b])
m = 0;mex = n-2
for a,b in l:
if jaya[a] == 1 or jaya[b] == 1:print(m);m+= 1
else:print(mex);mex -= 1 | py |
1292 | E | E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much... | [
"constructive algorithms",
"greedy",
"interactive",
"math"
] | import sys
t = int(input())
def get():
ans = ""
for i in range(n): ans = ans + S[i]
return ans
def query(pat):
print("Querying ", pat, file = sys.stderr)
print("? " + pat, flush = True)
A = list(map(int, input().split()))
for k in A[1:]:
for i in range(len(pat)):
S[k-1+i] = pat[i]
... | 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"
] | def f0(n, m):
mod = int(1e9 + 7)
c = 2 * m + 1
dp = [[0] * c for _ in range(n + 1)]
dp[0][0] = 1
for i in range(n):
# TODO 空间压缩 / 斜率优化
for j in range(c):
for k in range(j, c):
dp[i + 1][k] = (dp[i + 1][k] + dp[i][j]) % mod
return dp[-1][-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"
] | # import sys
# sys.stdin = open('ip.txt','r')
# sys.stdout = open('op.txt','w')
import math
from bisect import *
R=lambda:map(int,input().split())
t,=R()
while t:
t-=1;
n, = R()
arr = list(R())
presum = 0;
k1 =float('-inf')
k2 =float('-inf')
all_sum = sum(arr)
s = 0; e = len(arr)
#... | py |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero)... | [
"brute force",
"math"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
m=10**5
div=[[] for i in range(m)]
for i in range(1,m):
for j in range(i,m,i):
div[j].append(i)
def solve():
a,b,c=map(int,input().split())
ans=10**9
for i in range(10**4):
C=c+i
for B in div[C]:
for A in div[B]:
... | 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 factorial as fact
mod = 10**9 + 7
def C(n, k):
return fact(n) // (fact(k) * fact(n - k))
n, m = map(int, input().split())
print(C(n + 2*m - 1, 2*m) % mod) | 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"
] | T = int(input())
for _ in range(T):
a,b = map(int,input().split())
ans=0
diff=0
if(a==b):
ans = 0
elif(a>b):
diff=a-b
ans+= 1
if(diff%2!=0):
ans+= 1
elif(a<b):
diff=b-a
ans+=1
if(diff%2!=1):
ans+=1... | py |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. ... | [
"greedy",
"implementation"
] | import sys
from math import sqrt, gcd, factorial, ceil, floor, pi, inf
from collections import deque, Counter, OrderedDict
from heapq import heapify, heappush, heappop
#sys.setrecursionlimit(10**6)
#======================================================#
input = lambda: sys.stdin.readline()
I = lambda: int(inp... | 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())):
a= [(0, 0)]
n= int(input())
for i in range(n):
x, y= map(int, input().split())
a.append((x, y))
a.sort()
s= str()
for k in range(1, n+1):
if a[k][0] < a[k-1][0] or a[k][1] < a[k-1][1]:
print('NO')
break
... | 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
input = sys.stdin.readline
n, m = map(int, input().split())
d = [1]
c = 0
for i in range(1, n+1):
d.append(d[-1]*i%m)
for i in range(1, n+1):
c += (n-i+1)*d[n-i+1]*d[i]%m
c %=m
print(c) | py |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array m... | [
"constructive algorithms",
"sortings"
] | t = int(input())
for _ in range(t):
n = int(input())
num = list(map(int, input().split()))
num.sort()
num = num[::-1]
num = list(map(str, num))
print(" ".join(num)) | 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())
lst = [int(x) for x in input().split()][:n]
cnt, m_cnt = 0, 0
cnt2, m_cnt2 = 0, 0
if lst[0] == lst[-1] and lst[0] == 1:
cnt = 1
for j in range(n - 1):
if lst[j] == 1: cnt += 1
else:
pos = j
break
if cnt > m_cnt: m_cnt = cnt
for j in range(n - 2, pos, -1):
if lst[j] ==... | py |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good o... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | #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 |
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"
] | from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
def powmin2(x, r):
return pow(x, r - 2, r)
def comb(m, n, k):
res = 1
for i in range(n):
res = (res * (m - i)) % k
pro_mod = 1
for i in range(2, n + 1):
pro_mod = (... | py |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between ... | [
"greedy",
"implementation",
"math"
] | from 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.st... | 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 bisect
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_min(s, t):
s += l1
t += l1
ans = inf
while s <= t:
if s % 2 == 0:
s //= 2
else:
ans = min(ans, mi[s])
s = (s + 1) // 2
if t % 2... | 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"
] | def process(M):
n = len(M)
m = len(M[0])
answer = 0
for j in range(1, m+1):
d = {}
for i in range(n):
entry = M[i][j-1]
if entry % m == j % m and entry <= n*m:
if j < m:
entry1 = entry//m
else:
... | py |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The... | [
"greedy",
"implementation"
] | n=int(input())
left=input()
right=input()
leftlist=[[] for _ in range(27)]
for i in range(n):
if left[i]!='?':
leftlist[ord(left[i])-ord('a')].append(i)
else:
leftlist[26].append(i)
res=[]
temp=[]
for i in range(n):
if right[i]=='?':
temp.append(i)
else:... | py |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array m... | [
"constructive algorithms",
"sortings"
] | for _ in range(int(input())):
n = int(input())
arr = list(map(int,input().split()))
arr.sort(reverse=True)
print(*arr) | py |
1325 | B | B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longe... | [
"greedy",
"implementation"
] | for i in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
s=set(l)
print(len(s)) | py |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossib... | [
"greedy"
] | def find_nextmax(arr,x):
for i in range(len(arr)):
if arr[i]>x:
y=arr[i]
arr[i]=0
return y
return -1
for _ in range(int(input())):
n=int(input())
b=list(map(int,input().split()))
a=[]
for i in range(2*n):
if i%2==0:
a.a... | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.